Accessing API in Python

There are many internets API which offer data in json format. Such data can be easily used in python using python requests module. In the current post we will use requests python module toghether with Json format to find prognosed maximum temperature per day, for next 8 days based on openweathermap API. Documentation for requests module can be consulted in many links on internet, 

for example, here or in this site.

At the date of writing this short intro in accessing API and using output in JSON format, latest requests release can be found for example on community update link.

If not yet installed, python requests modul as usual can be installed via pip: 

python -m pip install requests

We will exemplify how to use requests and get JSON data for openweathermap.org API. 

openweathermap have many API, just checking on openweathermap website we will exemplify for "Current Weather Data" which have documentation at API doc 

Before doing something in Python for many of the presented endpoints we will need to get an API key, and understand API call. For API key, we need to create an account or profile on openweathermap.org site, after that in the profile it is a link where we can obtain an API key. This is easy, and let's presume we get it and now we have an API key.

For call current weather data API, based on documentation API call is 

https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}

In this URL:

  • endpoint is https://api.openweathermap.org/data/2.5/weather
  • parameters are:
  • lat for latitude
  • lon for longitude
  • appid is the API key discussed before
  • in  documentation exist other parameters like mode, units, lang

Parameters lat and lon can be obtained from internat, example from this site: https://www.latlong.net/, or from here https://www.gps-coordinates.net/, there are also some others. 

For lat 44.451209, lon 26.13391 and appid 70g04e4613056b159c2761a9d9e664d2 url for call is

https://api.openweathermap.org/data/2.5/onecall?lat=44.451209&lon=26.13391&appid=70g04e4613056b159c2761a9d9e664d2

Observation: appid is a fictive one here, you will need to obtain one from openweathermap site as mentioned prior. 

Loading it in browser we obtain:

Weather API In Browser

Figure 1: Weather API loaded In Browser

In this image it is a bunch of data, it looks difficult to use it effectively. Using python, we overcome this and we can extract or use data that we need. Simple call to this API using Python is in below code:

import requests

Weather_url = "https://api.openweathermap.org/data/2.5/onecall"

api_key = "70g04e4613056b159c2761a9d9e664d2"

weather_params = {

    "lat": 44.451209,

    "lon": 26.13391,

    "appid": api_key,

}

response = requests.get(Weather_url, params=weather_params)

We used get function from requests module, there is requests.get(.....)

Like parameters for get I used:

  • string Weather_url which is string with endpoint as mentioned in API doc
  • params which contain API parameters according with documentation. This "params" is a dictionary that contain parameters (lat, lon and appid ) means requests.get accept params like a dictionary with pairs key:value.

The output of the code is just "Process finished with exit code 0" and for the begining we can think it is not too useful. We can use supplimentary response.status_code it will give: 

print(response.status_code)

#output 

200

Here status_code  give well know response status code universal for any http request (example of other status code: 201, 401, 404 etc). For a complete list see: "List of HTTP status codes

In instruction: response = requests.get(Weather_url, params=weather_params)

response is an object, a class. If in GUI environment we just type response, intelisense will show a bunch of methods and variable for this class like below:  

Some methods from response module

Figure 2: Some methods from response module

Using response.json() will give in python output exact json data that we see in Figure 1, but this is displayed in a single line like:

{'lat': 44.4512, 'lon': 26.1339, 'timezone': 'Europe/Bucharest', 'timezone_offset': 10800.........text omitted ............ }

means:

Json output

Figure 3: Json output

This data still seems hard to analyze, however as we see there it seems similar with a dictionary, we can see structure of this in a Json viewer. 

There are many online Json viewers, I selected first Json data from Figure 1 using CTRL+A, press CTRL+C and then go to Json online https://jsonformatter.org/json-viewer viewer and press CTRL+V and there is:

Data In Json Viewer

Figure 4: Data in Json Viewer

We understand from here easy json structure where we see {} there is about dictionary, where is [] there is about list. 

Looking to Figure 4 if we need to access daily[0] list we will write

weather_1=response.json() # this is entire json data output

print(weather_1["daily"][0])

Expanding further there is: 

Maximum temperature for a day in Json output

Figure 5: Maximum temperature for a day in Json output

We see struture, hence for accessing daily max temperature for day 0 we will use 

weather_1=response.json() # this is entire json data output

print(weather_1["daily"][0]["temp"]["max"])

it will display 283.93 max temperature for daily[0]. 

Observation: above temperature is in Kelvin scale (to convert to celsius degtree we need to use "Kelvin value" - 273.15)


The code for find maximum temperature in next 8 days is:

import requests

Weather_Endpoint = "https://api.openweathermap.org/data/2.5/onecall"

api_key = "70g04e4613056b159c2761a9d9e664d2"

weather_params = {

    "lat": 44.451209,

    "lon": 26.13391,

    "appid": api_key,

}

response = requests.get(Weather_Endpoint, params=weather_params)

response.raise_for_status()

weather_1=response.json()

weather_2_daily = weather_1["daily"]

daily_max_temp=[]

for i in range(8):

    daily_max_temp.append(float(weather_2_daily[i]["temp"]["max"]))

    print(f"Maximum temperature in day {i} is {round(daily_max_temp[i]-273.15, 2)} Celsius degree")

print(f"Maximum daily temperature in next 8 days is {round(max(daily_max_temp)-273.15,2)} Celsius degree")


#output is: 

Maximum temperature in day 0 is 11.09 Celsius degree

Maximum temperature in day 1 is 14.41 Celsius degree

Maximum temperature in day 2 is 16.2 Celsius degree

Maximum temperature in day 3 is 17.99 Celsius degree

Maximum temperature in day 4 is 13.5 Celsius degree

Maximum temperature in day 5 is 13.01 Celsius degree

Maximum temperature in day 6 is 16.81 Celsius degree

Maximum temperature in day 7 is 16.82 Celsius degree

Maximum daily temperature in next 8 days is 17.99 Celsius degree

About the code: 

- weather_1 represent entire json output data

- weather_2_daily=weather_1["daily"] is a list based on Figure 4

- we defined an empty list with daily_max_temp=[]

- weather_2_daily[i]["temp"]["max"] is basicaly maximum daily temperature in day "i" in Kelvin degree.