Calling REST APIs
These days getting data from external web sources almost always involves a REST API. And they tend to follow a similar pattern where you call a url with some parameters in the url and that url returns a json document with the results. Requests is the library of choice in Python land and it shouldn’t surprise anyone that Neptyne ships with that piece of software out of the box. In this
how-to we’re going to combine two providers to create a little weather app where we take the name of a city, look up its coordinates and then pass the coordinates on to a weather provider. Let’s start with the geocoding. Using openstreetmap’s nomatim is free and does not require any registration.
We do pass in a headers object with a user agent identifying ourselves as Neptyne; this allows the provider to see how we are and in case of problems, they can even contact us. We can call this method from the spreadsheet like this:
The function returns two numbers, which are then according to Neptyne’s spilling rules put in A5 and A6.
The good people at https://api.met.no/ provide a free and very extensive weather API that is easy to call. It returns a lot of data so all we need to do is specify which bits we’re interested in. For today’s example that is just the current weather and it looks something like this:
We’re using the same headers for the same reason. The last line specifies where exactly to look, but if you’re interested try the other fields too. It’s good stuff.
Once we have that up, we can complete our spreadsheet:
We call the get_weather function on the results of the geocoding function. Any time we change the city, the geocoder will be called and the results of that will be fed into the weather API. Aren’t spreadsheets great?
Here’s the completed app: https://app.neptyne.com/-/l0ww78rhcd