Pulling TfL Line Status using REST APIs

The London Underground is the oldest underground train system in the world. Despite its age however, its owners (Transport for London) seemed to have spared no effort to ensure that the network runs as smoothly as possible.

I recently learnt learning that Transport for London (TfL) had an open API for anyone who wanted to use it, allowing anyone who signed up (dont skip this!) to pull live information at will.

I knew I had to give it a shot.

Script

I put together a Python script which allowed me to send a REST GET Request to TfL and retrieve data for an Underground Line of my choice.

Here’s a Python script I wrote up with can query TfL for the status of an Underground Line using REST APIs:

import requests
import json

print(
    "\n" +
    "Which line do you want the status for?" +
    "\n" +
    "\n" + "Your options are:" +
    "\n" +
    "\n" + "District" +
    "\n" + "Central" +
    "\n" + "Circle" +
    "\n" + "Piccadilly" +
    "\n" + "Waterloo-City" +
    "\n" + "Bakerloo" +
    "\n" + "Hammersmith-City" +
    "\n" + "Jubilee" +
    "\n" + "Metropolitan" +
    "\n" + "Victoria" +
    "\n" + "Northern" +
    "\n"
    )
    
line = input()

reply = requests.get("https://api.tfl.gov.uk/Line/" + line + "/Status")

data = reply.json()

Status = (data[0]["lineStatuses"][0]["statusSeverityDescription"])

print(
    "\n" + "Line: " + line +
    "\n" + "Status: " + Status +
    "\n"
    )

Script Theory

In short, the above script:

  • Imports the necessary 3rd party libraries needed to work
  • Presents the user with a list of available options to query
  • Waits for input
  • Makes a GET request to a specific TfL provided URL for line data
  • Pulls, extracts and displays the requested information in a friendly format

Note that you must enter the Line names “Hammersmith-City” and “Waterloo-City” with the hyphen. Any other variants of the name and TfL wont recognise them.

Output

All being well, you should expect output like this:

Line: Central
Status: Good Service

Nothing too wild, but a nice and easy way to get the information you need in a nice and clean manner.

Conclusion

It’s true that this information is easily accessible on your favourite travel app at a glance (perhaps even in a fancy widget on your homescreen) but for anyone who wants to challenge themselves or who wants to pull this data themselves to see how the big app-makers do it anyway, its a great small project.

References



Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Subscribe to Blog

Enter your email below to subscribe to this blog.

Blog Stats

  • 57,367 hits

Me Elsewhere

Ads

Menu