Home > Back-end >  How to iterate through several api calls and several dictionnary keys in the same time?
How to iterate through several api calls and several dictionnary keys in the same time?

Time:09-21

Here is my problem : I need to call this API > https://openweathermap.org/api/one-call-api.

My goal is to get in a dataframe the daily forecast weather on the next 7 seven days for a list of specific cities (based on their GPS coordonnates). I need to interate through 35 cities but here is a sample with 2 cities and a static way to get the keys a need.

A example of call for one city and containing the info for the next 7 days :

https://api.openweathermap.org/data/2.5/onecall?lat=48.6355232&lon=-1.5102571&exclude=hourly,current,minutely&appid=be02e7c76c38ec4e28e37a166d60abb7

So I have done that for the moment :

import requests

url = "https://api.openweathermap.org/data/2.5/onecall"
lat = ["48.6355232", "47.3215806"]
lon = ["-1.5102571", "5.0414701"]
output_results = []
for lat,lon in zip(lat, lon):
    r = requests.get(url, params={"lat":lat, "lon":lon, "exclude":"hourly,current,minutely", "appid":"be02e7c76c38ec4e28e37a166d60abb7"})
    output_results.append(r.json())


print(output_results[0]["lat"]) #latitude
print(output_results[0]["lon"]) #longitude
print(output_results[0]["daily"][0]["dt"]) #date
print(output_results[0]["daily"][0]["temp"]["day"]) #temperature
print(output_results[0]["daily"][0]["wind_speed"]) #wind speed
print(output_results[0]["daily"][0]["clouds"]) # clouds density

How could I iterate through the coordonnates list AND the keys I need ?

I would like to structure my final dataframe this way : df structure

Thanks for your help !

CodePudding user response:

Maybe this is what you're hoping to achieve:-

import requests
import pandas as pd
from datetime import datetime

url = "https://api.openweathermap.org/data/2.5/onecall"
lat = ["48.6355232", "47.3215806"]
lon = ["-1.5102571", "5.0414701"]
params = {"exclude": "hourly,current,minutely",
          "appid": "be02e7c76c38ec4e28e37a166d60abb7"}
columns = ['Date', 'Latitude', 'Longitude',
           'Temperature', 'Wind speed', 'Clouds']
DATA = []
with requests.Session() as session:
    for lat, lon in zip(lat, lon):
        params['lat'] = lat
        params['lon'] = lon
        r = session.get(url, params=params)
        r.raise_for_status()
        d = r.json()['daily'][0]
        dt = datetime.fromtimestamp(d['dt']).strftime('%d/%m/%Y')
        DATA.append([dt, lat, lon, d['temp']['day'],
                    d['wind_speed'], d['clouds']])
df = pd.DataFrame(DATA, columns=columns)
print(df)
  • Related