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.

HEADERS = {'User-Agent': "Neptyne/1.0 (https://www.neptyne.com; team@neptyne.com)"}
def get_lat_lng(city):
    data = requests.get(
        'https://nominatim.openstreetmap.org/search',
        headers=HEADERS,
        params={'q': city, 'format': 'json'},
    ).json()
    return data[0]['lat'], data[0]['lon']

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:

=get_lat_lng (A2)
A
B
C
D
1
City
2
New York
3
4
Location
5
40.7127281
6
-74.0060152

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:

def get_weather(lat, lon):
    url = f"https://api.met.no/weatherapi/locationforecast/2.0/compact?lat={lat}&lon={lon}"
    data = requests.get(url, headers=HEADERS).json()
    return data['properties']['timeseries'][0]['data']['instant']['details']

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:

=get_weather (A5,A6)
A
B
C
D
1
air_pressure_at_sea_level
1004
2
air_temperature
20.2
3
cloud_area_fraction
85.2
4
relative_humidity
73.4
5
wind_from_direction
101
6
wind_speed
4.3

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