Build a simple Python weather application using the OpenWeatherMap API. Learn to send HTTP requests, process JSON responses, handle errors, and display city weather details.
Learning focus:
Develop a simple Weather Application using Python that retrieves current weather information from an external Weather API.
The application should allow users to enter a city name and display its current weather information.
Register at OpenWeatherMap API and obtain a free API key.
Open the terminal or command prompt and execute:
pip install requests
Library: requests
Purpose: To send HTTP requests to the Weather API and receive weather information.
Create a project folder named WeatherApp with the following files:
WeatherApp/
│
├── config.py
├── weather.py
└── main.py
config.py (API Configuration)Store the API key and API URL in this file.
API_KEY = "type your api key here"
BASE_URL = "https://api.openweathermap.org/data/2.5/weather"
Replace your_api_key_here with your actual API key.
weather.py (API Integration)**This file will contain the function responsible for retrieving weather information.
import requests
from config import API_KEY, BASE_URL
def get_weather(city):
# API request parameters
params = {
"q": city,
"appid": API_KEY,
"units": "metric"
}
try:
# Send GET request to the Weather API
response = requests.get(
BASE_URL,
params=params,
timeout=10
)
# Check for HTTP errors
response.raise_for_status()
# Convert JSON response into a Python dictionary
data = response.json()
# Extract required weather information
weather = {
"city": data["name"],
"country": data["sys"]["country"],
"temperature": round(data["main"]["temp"]),
"humidity": data["main"]["humidity"],
"wind": data["wind"]["speed"],
"description": data["weather"][0]["description"]
}
return weather
# Handle HTTP errors
except requests.exceptions.HTTPError:
if response.status_code == 404:
print("Error: City not found.")
elif response.status_code == 401:
print("Error: Invalid API key.")
else:
print("Error: Unable to retrieve weather data.")
# Handle connection and timeout errors
except requests.exceptions.RequestException:
print("Error: Please check your internet connection.")
# Handle JSON and missing data errors
except (KeyError, ValueError):
print("Error: Invalid weather data received.")
return None
main.py (Main Application)**This file will accept the city name from the user and display the weather information.
import weather
print("===== WEATHER APPLICATION =====")
city = input("Enter city name: ")
weather = weather.get_weather(city)
if weather:
print("\n===== CURRENT WEATHER =====")
print("City:", weather["city"])
print("Country:", weather["country"])
print("Temperature:", weather["temperature"], "°C")
print("Weather:", weather["description"])
print("Humidity:", weather["humidity"], "%")
print("Wind Speed:", weather["wind"], "m/s")
else:
print("Unable to display weather information.")
Open the terminal in the project folder and execute:
python main.py
Sample Output
Example output – illustrative values
Enter city name: Dera Ghazi Khan
Dera Ghazi Khan, PK
Clear Sky
Humidity
35%
Wind Speed
3.5 m/s
| Concept | Learning outcome |
|---|---|
| API Integration | Connect Python with an external API |
| Requests Library | Send HTTP GET requests |
| JSON Handling | Extract information from JSON responses |
| Dictionaries | Store and access weather information |
| Functions | Organize code into reusable functions |
| Exception Handling | Handle API and connection errors |
| Modules | Divide the application into separate files |
5-Day Weather Forecast
Retrieve and display weather information for the next five days.
Retrieve and display weather information for the next five days
Web-Based Weather Application
Use Python Flask with HTML and CSS to develop a web application.