Find current weather of any city using OpenWeatherMap API in Python


In this tutorial, we are going to get the weather of a city using OpenWeatherMap API. To use the OpenWeatherMap API, we have to get the API key. We will get it by creating an account on their website.

Create an account and get your API Key. It's free until 60 calls per minute. You have to pay if you want more than that. For this tutorial, the free version is enough. We need requests module for the HTTP requests and JSON module to work with the response. Follow the below steps to the weather of any city.

  • Import the requests and JSON modules.

  • Initialize the base URL of the weather API https://api.openweathermap.org/data/2.5/weather?.

  • Initialize the city and API key.

  • Update the base URL with the API key and city name.

  • Send a get request using the requests.get() method.

  • And extract the weather info using the JSON module from the response.

Example

Let's see the code.

# importing requests and json
import requests, json
# base URL
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
# City Name CITY = "Hyderabad"
# API key API_KEY = "Your API Key"
# upadting the URL
URL = BASE_URL + "q=" + CITY + "&appid=" + API_KEY
# HTTP request
response = requests.get(URL)
# checking the status code of the request
if response.status_code == 200:
   # getting data in the json format
   data = response.json()
   # getting the main dict block
   main = data['main']
   # getting temperature
   temperature = main['temp']
   # getting the humidity
   humidity = main['humidity']
   # getting the pressure
   pressure = main['pressure']
   # weather report
   report = data['weather']
   print(f"{CITY:-^30}")
   print(f"Temperature: {temperature}")
   print(f"Humidity: {humidity}")
   print(f"Pressure: {pressure}")
   print(f"Weather Report: {report[0]['description']}")
else:
   # showing the error message
   print("Error in the HTTP request")

Output

If you run the above program, you will get the following results.

----------Hyderabad-----------
Temperature: 295.39
Humidity: 83
Pressure: 1019
Weather Report: mist

Conclusion

If you find any difficulty in following the tutorial, mention them in the comment section.

Updated on: 12-Feb-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements