Python for Network Engineers

Use Python to Access Rest Api

by: George El., January 2019, Reading time: 3 minutes

Click the button

The above is in javascript but we will get the same output using python requests library. The code is only a few lines. We will use the openweathermap api from http://openweathermap.org. You have to register first in order to get the api key by email. They have a detailed documentation about their api. We will query about london weather.

import requests
r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=c4e5433fxxxxxxxxxxxxxxxxxxxx')
print(r.text)
print(type(r.text)) #str
data=r.json()
print(type(data)) #dict

the output is

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":310,"main":"Drizzle","description":"light intensity drizzle rain","icon":"09d"},{"id":521,"main":"Rain","description":"shower rain","icon":"09d"}],"base":"stations","main":{"temp":282.05,"pressure":1003,"humidity":81,"temp_min":281.15,"temp_max":283.15},"visibility":10000,"wind":{"speed":6.2,"deg":210},"clouds":{"all":90},"dt":1547641200,"sys":{"type":1,"id":1414,"message":0.0049,"country":"GB","sunrise":1547625503,"sunset":1547655766},"id":2643743,"name":"London","cod":200}
<class 'str'>
{'coord': {'lon': -0.13, 'lat': 51.51}, 'weather': [{'id': 310, 'main': 'Drizzle', 'description': 'light intensity drizzle rain', 'icon': '09d'}, {'id': 521, 'main': 'Rain', 'description': 'shower rain', 'icon': '09d'}], 'base': 'stations', 'main': {'temp':
282.05, 'pressure': 1003, 'humidity': 81, 'temp_min': 281.15, 'temp_max': 283.15}, 'visibility': 10000, 'wind': {'speed': 6.2, 'deg': 210}, 'clouds': {'all': 90}, 'dt': 1547641200, 'sys': {'type': 1, 'id': 1414, 'message': 0.0049, 'country': 'GB', 'sunrise': 1547625503, 'sunset': 1547655766}, 'id': 2643743, 'name': 'London', 'cod': 200}
<class 'dict'>

although it looks the same from the type keyword, you will see that the first is text while the second is dictionary. It’s a common practice to convert the text from the api to lists/dictionaries in python or javascript objects in javascript in order to be able to handle it. you can also request this url from your browser. what you will get back is the same text like this

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":721,"main":"Haze","description":"haze","icon":"50n"},{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09n"},{"id":701,"main":"Mist","description":"mist","icon":"50n"}],"base":"stations","main":{"temp":278.96,"pressure":1029,"humidity":87,"temp_min":278.15,"temp_max":280.15},"visibility":8000,"wind":{"speed":2.6,"deg":300},"clouds":{"all":40},"dt":1547193000,"sys":{"type":1,"id":1414,"message":0.0026,"country":"GB","sunrise":1547193745,"sunset":1547223292},"id":2643743,"name":"London","cod":200}

this text is in json format, key value pairs and lists of key value pairs. in order to be able to use it, we have to convert it to python structure, that is dictionary. this is what r.json() does. After we convert the text to dictionary we can access the various fields of the dictionary like this. this is a dictionary that contains other dictionaries. you can access the values by specifying thw keyword

print(data['coord'])
print(data['weather'][0]['main'])
print(data['main']['temp'])

{'lon': -0.13, 'lat': 51.51}
Haze
278.96

i recommend using https://jsoneditoronline.org/ for prettyfing the api response. there are also plugins for browsers to prettify the output. you can also use the python method json.dumps

import json
print(json.dumps(data, indent=4))

which will print it like this
{
    "coord": {
        "lon": -0.13,
        "lat": 51.51
    },
    "weather": [
        {
            "id": 721,
            "main": "Haze",
            "description": "haze",
            "icon": "50n"
        },
        {
            "id": 300,
            "main": "Drizzle",
            "description": "light intensity drizzle",
            "icon": "09n"
        },
        {
            "id": 701,
            "main": "Mist",
            "description": "mist",
            "icon": "50n"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 278.96,
        "pressure": 1029,
        "humidity": 87,
        "temp_min": 278.15,
        "temp_max": 280.15
    },
    "visibility": 8000,
    "wind": {
        "speed": 2.6,
        "deg": 300
    },
    "clouds": {
        "all": 40
    },
    "dt": 1547193000,
    "sys": {
        "type": 1,
        "id": 1414,
        "message": 0.0023,
        "country": "GB",
        "sunrise": 1547193744,
        "sunset": 1547223293
    },
    "id": 2643743,
    "name": "London",
    "cod": 200
}

another way to traverse a dictionary is using the following:

for key in data:
    print(key,data[key])

this will print

coord {'lon': -0.13, 'lat': 51.51}
weather [{'id': 721, 'main': 'Haze', 'description': 'haze', 'icon': '50n'}, {'id': 300, 'main': 'Drizzle', 'description': 'light intensity drizzle', 'icon': '09n'}, {'id': 701, 'main': 'Mist', 'description': 'mist', 'icon': '50n'}]
base stations
main {'temp': 278.96, 'pressure': 1029, 'humidity': 87, 'temp_min': 278.15, 'temp_max': 280.15}
visibility 8000
wind {'speed': 2.6, 'deg': 300}
clouds {'all': 40}
dt 1547193000
sys {'type': 1, 'id': 1414, 'message': 0.0023, 'country': 'GB', 'sunrise': 1547193744, 'sunset': 1547223293}
id 2643743
name London
cod 200
comments powered by Disqus