Bay Area Rapid Transit
TransportationUsing the BART API to Get Train Information
The BART API provides a simple way to access real-time train information. With this API, developers can build applications that show train schedules, departures, and estimated arrival times. In this article, we'll explore how to use the BART API to get train information using JavaScript.
Getting Started
Before you can use the BART API, you'll need to sign up to get your API key. You can sign up for free at http://api.bart.gov/docs/overview/authentication.aspx.
Once you have your API key, you can start making requests.
Making Requests
The BART API provides a simple HTTP interface that responds with XML data. To make a request, you'll need to provide your API key and specify the command you want to execute.
Here's an example of how to make a request for the current train schedules:
const xhr = new XMLHttpRequest();
xhr.open(
"GET",
"http://api.bart.gov/api/sched.aspx?cmd=routesched&route=1&key=YOUR-API-KEY",
true
);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const responseXML = xhr.responseXML;
console.log(responseXML);
}
};
xhr.send();
In this example, we're using the XMLHttpRequest
object to make a GET request to the BART API. We're specifying the cmd=routesched
parameter to get information about the current train schedules. We're also specifying the route=1
parameter to get information about trains on the Red Line.
Once we receive a response, we parse the XML data using the responseXML
property of the XMLHttpRequest
object.
Conclusion
That's all there is to it! With the BART API, developers can quickly and easily access real-time train information. Whether you're building a mobile app or a web app, this API provides a simple way to get the data you need.
Now, it's your turn to get creative! Start exploring the BART API and see what kind of cool applications you can build!