In this article, I'll talk about how to get current weather of any city using openweathermap API with Python.
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
I am going to use following python packages:
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.
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["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