Search code examples
pythonruntime-erroropenweathermap

Error 400 to limit number in Openweathermap API


I'm trying to use Openweathermap and I'm using their docs to get the calls.
I don't know why but I get always this error:

{'cod': '400', 'message': '{limit} is not a number'}

This is my code:

import requests
import json

API_KEY = "49edcdeb737a08b5371c42f85fb4ce3d"
weather_url = "http://api.openweathermap.org/geo/1.0/direct?q={city_name},{country_code}&limit={limit}&appid="
final_url = weather_url + API_KEY

limit = "1"
city_name = "Brindisi"
country_code = "3166"

weather_data = requests.get(final_url).json()

print(weather_data)

Solution

  • You are not replacing the query parameters with actual values. q={city_name},{country_code}&limit={limit} is hard coded in the url and is invalid.

    You can use the F-string in python to replace placeholder value with actual value.

    limit = "1"
    city_name = "Brindisi"
    country_code = "3166"
    
    weather_url = f"http://api.openweathermap.org/geo/1.0/direct?q={city_name},{country_code}&limit={limit}&appid="
    final_url = weather_url + API_KEY