Search code examples
pythonrequestresponse

Using variable in an API request in Python


I would like to know how to use a variable in the following API call:

response=requests.get('https://api.darksky.net/forecast/f3bc3bd870812cc013666f2bfb75b45d/50,1,2019-11-18T22:05:45+00:00')

instead of the random values 50 and 1 in this example, I would like to put my variables for latitude and longitude, integrated in a for loop. When I try this is not working and a 400 error happens. Is it a syntax error or is it impossible ? I read the whole documentation of this API and nothing indicates that it's impossible.

[EDIT]Example of a try :

for i in range(0,precision):
    
    response=requests.get('https://api.darksky.net/forecast/f3bc3bd870812cc013666f2bfb75b45d/latitude[i],longitude[i],2019-11-18T22:05:45+00:00')
    json_data = json.loads(response.text)  
    
    wind_speed[i]=json_data["currently"]["windSpeed"]
    wind_dir[i]=json_data["currently"]["windBearing"]

In this example for i=0, latitude[i]=51.4888 and longitude[i]=-3.16657

and here is the error message

  File "C:/Users/ab79/Documents/GPX WEATHER/test.py", line 8, in <module>
    print(json_data["currently"]["windSpeed"])

KeyError: 'currently'

Solution

  • I would do something like this:

    base_url = 'https://api.darksky.net/forecast/f3bc3bd870812cc013666f2bfb75b45d/{},{},2019-11-18T22:05:45+00:00'
    url = base_url.format(latitude[i],longitude[i])
    r = requests.get(url)
    
    data = r.json()
    

    You're running into an issue because you're trying to inject the variables directly into the url string. Try using a .format() (above) or an f-string like this:

    url = f'https://api.darksky.net/forecast/f3bc3bd870812cc013666f2bfb75b45d/{latitude[i]},{longitude[i]},2019-11-18T22:05:45+00:00'
    r = requests.get(url)
    data = r.json()