Using the HEA Public API for Real-Time Bus Data

The Honolulu Authority for Rapid Transportation (HEA) provides a public API that allows developers to access real-time bus data for the island of Oahu. In this blog post, we'll explore how to use this API with JavaScript to build an application that displays live bus information.

Getting Started

To get started using the HEA API, you'll need to obtain an API key by registering on their website. Once you have your key, you can start making requests to the API endpoint.

The API endpoint is http://hea.thebus.org/api_info.asp. To retrieve real-time bus data, you'll need to add /bus to the end of the endpoint URL. For example, the full URL to retrieve real-time bus information for route 2 would be http://hea.thebus.org/api_info.asp/bus?route=2&c=3.

Retrieving Bus Information

To retrieve bus information, we can use the built-in fetch() method in JavaScript. The following code shows how to retrieve real-time bus data for route 2:

const apiKey = "your_api_key";
const routeNumber = "2";
const busEndpoint = `http://hea.thebus.org/api_info.asp/bus?route=${routeNumber}&c=3&api=${apiKey}`;

fetch(busEndpoint)
  .then(response => response.json())
  .then(data => {
    // Do something with the data
  });

In the code above, we first define our API key and the route number that we want to retrieve bus information for. We then construct the full API endpoint URL by appending the route number and our API key to the base URL.

We then use the fetch() method to make the API request, passing in our endpoint URL as an argument. Once we receive a response from the API, we convert it to JSON format using the .json() method.

Finally, we can do something with the data by passing it to a function or storing it in a variable.

Handling Errors

As with any API request, there's always the possibility of encountering an error. To handle errors with the HEA API, we can use a try-catch block:

fetch(busEndpoint)
  .then(response => {
    if (!response.ok) {
      throw new Error("Network response was not OK");
    }
    return response.json();
  })
  .then(data => {
    // Do something with the data
  })
  .catch(error => {
    console.error("Error:", error);
  });

In the code above, we first check if the API response was OK by checking the response.ok property. If it's not, we throw an error with a helpful message.

We then continue processing the data as before. If an error is encountered at any point, it will be caught by the .catch() block and we can handle it accordingly.

Conclusion

In this blog post, we've explored how to use the HEA API with JavaScript to retrieve real-time bus data for Oahu. We've seen how to make API requests, handle errors, and process the response data. With this knowledge, you can now build powerful applications that leverage real-time bus information for the island of Oahu.

Related APIs