Exploring the TfL API with JavaScript

The Transport for London (TfL) API provides a wealth of real-time data related to London's public transportation system. Here we'll take a look at how to access this information using JavaScript.

Getting Started

Before we can start using the TfL API, we need to register for an API key. Visit the TfL API website at https://api.tfl.gov.uk and click on the "Sign Up" link in the top right corner. Once you've registered and received your API key, we can proceed with making requests.

Making Requests

To make requests to the TfL API with JavaScript, we can use the built-in fetch function. Here's an example of a simple request to retrieve all Tube lines:

const appId = 'YOUR_API_ID'; // insert your obtained API ID here
const apiKey = 'YOUR_API_KEY'; // insert your obtained API key here

fetch(`https://api.tfl.gov.uk/Line/Mode/tube?app_id=${appId}&app_key=${apiKey}`)
  .then(response => response.json())
  .then(data => console.log(data));

In this example, we pass our API ID and key as query parameters in the URL. The response is returned as a JSON object, which we can then log to the console or use in other ways.

Working with Data

Once we've received data from the TfL API, we can work with it as needed. Here's an example that shows how to extract information about a specific Tube line:

const lineId = 'victoria';
fetch(`https://api.tfl.gov.uk/Line/${lineId}?app_id=${appId}&app_key=${apiKey}`)
  .then(response => response.json())
  .then(data => {
    console.log(`Name: ${data.name}`);
    console.log(`Status: ${data.lineStatuses[0].statusSeverityDescription}`);
  });

This code retrieves data for the Victoria line, and then logs its name and current status to the console. We can use this data in our web or mobile applications to provide real-time information to users.

Conclusion

The TfL API provides a powerful way to access real-time data related to London's public transportation system. With JavaScript, we can easily make requests to this API and work with the data it returns. By leveraging this information, we can create applications that help users navigate the city's transportation network more efficiently.

Related APIs

Public APIs — A directory of free and public apis

Built by @mddanishyusuf