API purpose: Commuting Data
Signup: No Signup
Documentation: https://api-portal.tfl.gov.uk/docs
Github: https://github.com/gregario/API-Month/tree/master/Day3%20Maps Comment: surprisingly challenging
So as I said yesterday today I want to find the arrival time of my local train so I can plan my morning breakfast intake! It turned out to be quite challenging… Firstly a comment on the TFL (transport for london) API services. They’re all over the place. I found the following resources to extract data about journeys, stop locations and times:
https://api.tfl.gov.uk/#Journey
and two sets of documentation at:
https://api-portal.tfl.gov.uk/docs
So I eventually used the API portal to get access to arrival times, it wasn’t the most straightforward information set to work with however. Check out the photo!
The photo shows a typical API response from a station arrival time call. We want one variable from this giant list! This is a good time to work with a list like this as many API’s are complex like this one so it gives me an opportunity to go through the detail and figure out how to extract the data.
I got to play with some good stuff here such as operating on, iterating over and extracting conditional data from JSON objects. Also doing operations on time while pulling the current real time from the python datetime module.
The key for the code here is that the API is a list where each element in the list is a JSON object (that we manipulate as a python dict). Confused? I was… But its OK to work with in practice. What happens here is we write some code to loop through the list and for every JSON element in the list do a value search for arrival time. This gives us the arrival time of all trains into my station. However I only want certain trains heading in one direction. So I run an if with the loop checking for the relevant trains. If they are present pop the arrival time from that train into a new array. Then we have an array with all the relevant arrival times. Just sort that and you have the train that will arrive first. Pop that out and you have a variable to work with. YAY. Taking that from the current time gives you the number you are looking for.
I’ve explained the logic of what I want to do now let’s look at the code. If you are reading this (I do doubt anyone is) I am trying to improve the way in which I write these tutorials. Today I’m trying to explain how all the code works as comments. Hopefully one can understand how it works just from that.
|
|
And it works!
I’ve never been so happy to see some command line arguments! This was day three but I ran over time so I’m going to immediately do day 4 too 🙂 Stay tuned.