How to connect to weather API using requests?

I am trying to learn Requests and practicing by connecting to the weather API. But for some reason I can’t get it to work? It is clear the weather API is wanting the param in a certain way that I cannot seem to figure out how it translates to Requests.

Here is my code:

r = requests.get('http://api.openweathermap.org/data/2.5/weather', q={'Anderson'})

Here is the link to the API page: https://openweathermap.org/current

I see the weather pages wants the param in terms of q = city, but the error I get is:

TypeError: request() got an unexpected keyword argument 'q'

Also here the the Requests page that I am referring to: http://docs.python-requests.org/en/master/

Thanks for the help!

Answer

Please review the requests user manual, at least the quickstart guide. The RESTful API you are about to use expects GET request with q="City Name" parameter. Moreover you must have the appid and add it for every request.

  1. Register you application and choose a pricing plan https://openweathermap.org/price
  2. Pass both q="City Name" and APPID=xxx parameters

Here is corresponding request:

api_url = 'http://api.openweathermap.org/data/2.5/weather'
appid = ...    
r = requests.get(url=api_url, params=dict(q='Anderson', APPID=appid))

Leave a Reply

Your email address will not be published. Required fields are marked *