Weather Data API
Examples
This tutorial shows you how to get started using Weather API in Python. The snippets of code on this page can be put together to make your own script for extracting data.
Make sure requests
and pandas
libraries are installed.
Installing requests
pip install requests
Installing pandas
pip install pandas
# Libraries needed (pandas is not standard and must be installed in Python)
import requests
import pandas as pd
Retrieve data from weather data API
The next block of code retrieves data from weather data API using the requests.get
function. Its first argument is the endpoint we are going to get data from, in this case the weather
endpoint. The next argument is a dictionary containing the parameters that we need to define in order to retrieve data from this endpoint: timeStart
, timeEnd
, interval
, longitude
, latitude
, parameters
# Define endpoint and parameters
endpoint = 'https://irh.nibio.no/weather/weatheradapter/'
parameters = {
'timeStart': '2024-02-19T07:00:00Z',
'timeEnd': '2024-02-20T12:00:00Z',
'interval': '3600',
'latitude': '-14.159339',
'longitude': '33.776864',
'parameters': '1001,3001'
}
# Issue an HTTP GET request
response = requests.get(endpoint, parameters)
if response.status_code == 200:
# Extract JSON data
json = response.json()
location_weather_data = json['locationWeatherData'][0]
data = location_weather_data['data']
df = pd.DataFrame(data, columns=['Instantaneous temperature at 2m', 'Instantaneous RH at 2m (%)'])
print (df)
else:
print('Error! Returned status code %s' % response.status_code)
If the above block returned an error, then the rest cannot be run. If it printed out a success, then we are all set.
We will use the pandas library to insert the weather data into a table format. This is useful for doing all kinds of analysis on the returned data. If you only want to print or save the data, then pandas won't be necessary, and you can simply loop over the elements in the data variable.
Result from the weather data API
Using pandas, we have formatted the data into a table for easy understanding of the data.
Instantaneous temperature at 2m Instantaneous RH at 2m (%)
0 32.6 55.700000
1 33.4 52.700000
2 34.4 48.700000
3 34.8 46.900000
4 34.9 46.500000
.. ... ...
216 29.3 79.366667
217 29.5 79.000000
218 29.7 78.633333
219 29.9 78.266667
220 30.1 77.900000