Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find current weather of any city using OpenWeatherMap API in Python
In this tutorial, we will retrieve the current weather of any city using the OpenWeatherMap API in Python. OpenWeatherMap provides a free weather API that allows up to 60 calls per minute without cost.
Prerequisites
Before getting started, you need to:
Create a free account at OpenWeatherMap
Generate your API key from the dashboard
Install the
requestsmodule if not already available
Required Modules
We need two Python modules for this tutorial ?
requests ? for making HTTP requests to the API
json ? for parsing the JSON response (built-in module)
Step-by-Step Implementation
Follow these steps to fetch weather data ?
Import the required modules
Set up the base URL and API credentials
Construct the complete API URL
Make the HTTP request
Parse and display the weather information
Complete Example
Here's the complete implementation to get weather data for any city ?
import requests
import json
# Base URL for OpenWeatherMap API
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
# City name and API key
CITY = "London"
API_KEY = "your_api_key_here" # Replace with your actual API key
# Construct the complete URL
URL = BASE_URL + "q=" + CITY + "&appid=" + API_KEY
# Make HTTP request
response = requests.get(URL)
# Check if request was successful
if response.status_code == 200:
# Parse JSON response
data = response.json()
# Extract main weather data
main = data['main']
temperature = main['temp']
humidity = main['humidity']
pressure = main['pressure']
# Extract weather description
weather_report = data['weather']
# Display weather information
print(f"{CITY:-^30}")
print(f"Temperature: {temperature}K ({temperature - 273.15:.2f}°C)")
print(f"Humidity: {humidity}%")
print(f"Pressure: {pressure} hPa")
print(f"Weather: {weather_report[0]['description'].title()}")
else:
print(f"Error: Unable to fetch weather data (Status code: {response.status_code})")
The output of the above code is ?
-----------London------------ Temperature: 285.32K (12.17°C) Humidity: 81% Pressure: 1013 hPa Weather: Few Clouds
Enhanced Version with Error Handling
Here's an improved version with better error handling and temperature conversion ?
import requests
import json
def get_weather(city_name, api_key):
"""Fetch weather data for a given city"""
base_url = "https://api.openweathermap.org/data/2.5/weather?"
complete_url = f"{base_url}q={city_name}&appid={api_key}"
try:
response = requests.get(complete_url, timeout=5)
if response.status_code == 200:
data = response.json()
# Extract weather information
main = data['main']
weather = data['weather'][0]
# Convert temperature from Kelvin to Celsius
temp_celsius = main['temp'] - 273.15
feels_like_celsius = main['feels_like'] - 273.15
weather_info = {
'city': data['name'],
'country': data['sys']['country'],
'temperature': round(temp_celsius, 1),
'feels_like': round(feels_like_celsius, 1),
'humidity': main['humidity'],
'pressure': main['pressure'],
'description': weather['description'].title(),
'visibility': data.get('visibility', 'N/A')
}
return weather_info
elif response.status_code == 404:
return {"error": "City not found"}
else:
return {"error": f"API error: {response.status_code}"}
except requests.exceptions.Timeout:
return {"error": "Request timeout"}
except requests.exceptions.RequestException as e:
return {"error": f"Request failed: {str(e)}"}
# Usage example
city = "Paris"
api_key = "your_api_key_here" # Replace with your actual API key
result = get_weather(city, api_key)
if 'error' in result:
print(f"Error: {result['error']}")
else:
print(f"\n{'='*40}")
print(f"Weather in {result['city']}, {result['country']}")
print(f"{'='*40}")
print(f"Temperature: {result['temperature']}°C")
print(f"Feels like: {result['feels_like']}°C")
print(f"Humidity: {result['humidity']}%")
print(f"Pressure: {result['pressure']} hPa")
print(f"Description: {result['description']}")
print(f"Visibility: {result['visibility']} meters")
Key Features
| Feature | Description | Benefit |
|---|---|---|
| Temperature Conversion | Converts Kelvin to Celsius | More readable format |
| Error Handling | Handles API errors and timeouts | Robust application |
| Structured Data | Returns organized weather information | Easy to use and extend |
Common API Response Codes
200 ? Success, weather data retrieved
401 ? Invalid API key
404 ? City not found
429 ? API rate limit exceeded
Conclusion
The OpenWeatherMap API provides an easy way to fetch real-time weather data in Python. Always include proper error handling and consider converting temperature units for better user experience. Remember to keep your API key secure and never commit it to version control.
