Get Current Weather Data of any city in Python
In this tutorial, we will show you how to get weather information using OpenWeatherMap API. To call the API, you will need to have their API Key which you can get by creating an account on OpenWeatherMap. Get API key at https://home.openweathermap.org/api_keys. You can make 60 calls per minute to the API in free plan.
import urllib.request
import json
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
API_KEY = "Get API Key from OpenWeatherMap"
def get_weather(city):
URL = BASE_URL + "q=" + city + "&appid=" + API_KEY
f = urllib.request.urlopen(URL)
if f.status == 200:
data = f.read().decode('utf-8')
return json.loads(data)
return None
weather_data = get_weather("Boston")
print(weather_data)
print("Main data = ", weather_data["main"])
The above code will give the following output:
{'coord': {'lon': -71.0598, 'lat': 42.3584}, 'weather': [{'id': 801, 'main': 'Clouds', 'description': 'few clouds', 'icon': '02n'}], 'base': 'stations', 'main': {'temp': 263.76, 'feels_like': 259.66, 'temp_min': 259.21, 'temp_max': 267.12, 'pressure': 1042, 'humidity': 64}, 'visibility': 10000, 'wind': {'speed': 2.06, 'deg': 240}, 'clouds': {'all': 20}, 'dt': 1644993419, 'sys': {'type': 2, 'id': 2013408, 'country': 'US', 'sunrise': 1645011573, 'sunset': 1645049841}, 'timezone': -18000, 'id': 4930956, 'name': 'Boston', 'cod': 200}
Main data = {'temp': 263.76, 'feels_like': 259.66, 'temp_min': 259.21, 'temp_max': 267.12, 'pressure': 1042, 'humidity': 64}
Main data = {'temp': 263.76, 'feels_like': 259.66, 'temp_min': 259.21, 'temp_max': 267.12, 'pressure': 1042, 'humidity': 64}