Tutorials  Articles  Notifications  Login  Signup


RK

Rajan Kumar

Founder at HackersFriend Updated July 25, 2019, 2:11 p.m. ⋅ 2329 views

Get current weather of any city with python using openweathermap API


In this article, I'll talk about how to get current weather of any city using openweathermap API with Python.

 

Approach

We'll call openweathermap API with a GET request, then It'll response with JSON data of our requested city. We'll parse this JSON data and use in our program. In order to use openweathermap API you need to have an API key. You can get it from their website or from here

 

Requirements

I am going to use following python packages:

  • requests
  • json

So, if you like to follow along, you need to install these packages. 

If you have these packages already installed you are good to go. Otherwise, you can simply install these pckages using following command:

pip install package-name

You need to replace package-name with the name of package you want to install.

Once you are done installing all the required packages, you can continue further.

 

Implementation

Here is code to implement this apporach.

import requests, json 

# Pass your API key here 
api_key = "Your_API_Key"

 
ow_url = "http://api.openweathermap.org/data/2.5/weather?"

# Pass city name 
city = input("Enter city name: ") 

call_url = ow_url + "appid=" + api_key + "&q=" + city 


# Fire a GET request to API 
response = requests.get(call_url) 


# fetch data from JSON response
data = response.json() 

if data["cod"] != "404": 
 
	city_res = data["main"] 

	current_temperature = city_res["temp"] 

	current_pressure = city_res["pressure"]  
	
    current_humidiy = city_res["humidity"] 

	wthr = data["weather"] 

	weather_description = wthr[0]["description"] 

	# print following values 
	print(" Temperature (in kelvin unit) = " +
					str(current_temperature) +
		"\n atmospheric pressure (in hPa unit) = " +
					str(current_pressure) +
		"\n humidity (in percentage) = " +
					str(current_humidiy) +
		"\n description = " +
					str(weather_description)) 

else: 
	print(" City Not Found ") 

 

 Enter city name: Delhi
 Temperature (in kelvin unit) = 300.15
 atmospheric pressure (in hPa unit) = 990
 humidity (in percentage) = 60
 description = cloudy

 



HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.


Create a free account