Transport for Auckland, New Zealand

Transportation

Accessing Auckland Transport API using JavaScript

Are you looking for a way to get real-time public transport information for Auckland, New Zealand? Look no further than the Auckland Transport (AT) API! In this post, we'll walk through how to access the AT API using JavaScript.

Getting Started

To use the AT API, you'll need an API key, which you can obtain for free by signing up at https://dev-portal.at.govt.nz/. Once you have your API key, you're ready to start making requests.

API Endpoints

The AT API provides a variety of endpoints for different types of public transport information. Some popular endpoints include:

  • https://api.at.govt.nz/v2/gtfs/stopTimesByStopId/:stop_id: get arrival and departure times for a particular bus stop.
  • https://api.at.govt.nz/v2/publicTransportNetworks: get a list of all public transportation networks.
  • https://api.at.govt.nz/v2/publicTransportStops: get a list of all public transportation stops.

For our example, we'll use the stopTimesByStopId endpoint to get the arrival and departure times for a particular bus stop.

Making Requests

To make requests to the AT API in JavaScript, we'll use the Fetch API. Here's some example code to get arrival and departure times for the "Wellington St at Queen St" bus stop:

const stopId = 1002; // ID of the Wellington St at Queen St bus stop
const apiKey = 'YOUR_API_KEY_HERE'; // Replace with your own API key
const url = `https://api.at.govt.nz/v2/gtfs/stopTimesByStopId/${stopId}?api_key=${apiKey}`;

fetch(url)
  .then(response => response.json())
  .then(data => {
    // Do something with the arrival/departure times
    console.log(data);
  })
  .catch(error => console.error(error));

This code sets the stopId variable to the ID of the "Wellington St at Queen St" bus stop, and the apiKey variable to your personal API key. It then constructs the URL for the stopTimesByStopId endpoint, including the stopId and apiKey as query parameters.

The fetch method is then used to make the request to the API, and the response data is parsed as JSON using the response.json() method. Finally, the arrival/departure times are logged to the console.

Conclusion

By using the Auckland Transport API and Fetch API in JavaScript, we were able to get real-time public transport information for Auckland. With this information, we can build powerful applications that help people navigate the city more efficiently. Happy coding!

Related APIs