Weather App using OpenWeatherMap API
IntermediateBuild a real-time weather application with Python APIs
1) Project Overview
The Weather App fetches real-time weather information (temperature, humidity, weather description, etc.) for any city using the OpenWeatherMap API.
Users simply type the name of a city, and the program displays:
- π‘οΈ Temperature
- π§ Humidity
- π₯οΈ Weather condition
- π¬οΈ Wind speed
π‘ Why it's useful: Understanding weather conditions is one of the most common use-cases for APIs. This project teaches how to connect Python with external data sources, handle JSON responses, and display meaningful results.
2) Learning Objectives
By completing this project, learners will master:
| Concept | Description |
|---|---|
| APIs (Application Programming Interfaces) | How to fetch live data from the web using HTTP requests |
| HTTP requests with requests | Learn to make GET requests and handle API responses |
| JSON data handling | Parse and extract data from JSON (JavaScript Object Notation) |
| Error handling | Manage invalid city names or network errors gracefully |
| Functions and Code Reusability | Write modular, reusable, and well-structured functions |
| Formatted Output | Present real-time data clearly in the console |
3) Step-by-Step Explanation
Follow these steps to build the weather app:
- Setup the Project File β Create a Python file: weather_app.py
- Install Required Library β Open your terminal or VS Code terminal and install the requests library (if not already installed):
pip install requests - Get Free API Access β
- Go to https://openweathermap.org/api
- Sign up for a free account
- Generate your API key (you'll need it in your code)
- Import Libraries β We'll use requests for API communication and json to parse the response
- Create the Weather Fetch Function β Define a function that takes the city name and retrieves data from the OpenWeatherMap API
- Handle Errors β If the user enters an invalid city name, the app should gracefully inform them instead of crashing
- Display Data in a User-Friendly Way β Print temperature, weather description, humidity, and wind speed neatly formatted
- Make the Program Interactive β Allow the user to enter multiple cities in a loop until they choose to exit
4) Complete, Verified, and Well-Commented Python Code
You can copy this into a file named weather_app.py and run it.
# --------------------------------------------------------------
# π€οΈ Weather App using OpenWeatherMap API
# Author: Your Name
# Level: Intermediate
# Verified: Python 3.8+
# --------------------------------------------------------------
import requests # For making HTTP requests
# ==============================
# Step 1: Define API base URL and key
# ==============================
API_KEY = "your_api_key_here" # Replace with your actual OpenWeatherMap API key
BASE_URL = "https://api.openweathermap.org/data/2.5/weather"
# ==============================
# Step 2: Define function to get weather data
# ==============================
def get_weather(city_name):
try:
# Construct API URL with parameters
url = f"{BASE_URL}?q={city_name}&appid={API_KEY}&units=metric"
# Make GET request to fetch data
response = requests.get(url)
# Convert response data (JSON) into Python dictionary
data = response.json()
# If city not found
if data["cod"] == "404":
print("β City not found. Please check the name and try again.\n")
else:
# Extract important information
city = data["name"]
country = data["sys"]["country"]
temperature = data["main"]["temp"]
humidity = data["main"]["humidity"]
wind_speed = data["wind"]["speed"]
weather_desc = data["weather"][0]["description"].capitalize()
# Display formatted output
print(f"\nπ Weather Report for {city}, {country}:")
print(f"π‘οΈ Temperature: {temperature}Β°C")
print(f"π§ Humidity: {humidity}%")
print(f"π¬οΈ Wind Speed: {wind_speed} m/s")
print(f"π₯οΈ Condition: {weather_desc}")
print("-" * 45 + "\n")
except requests.exceptions.RequestException:
print("β οΈ Network error! Please check your internet connection.\n")
# ==============================
# Step 3: Main program loop
# ==============================
def main():
print("========== π¦οΈ Weather App ==========")
print("Get real-time weather updates easily!")
print("====================================\n")
while True:
city = input("Enter city name (or type 'exit' to quit): ").strip()
if city.lower() == "exit":
print("π Thank you for using the Weather App! Goodbye!")
break
if city == "":
print("β οΈ Please enter a valid city name.\n")
else:
get_weather(city)
# ==============================
# Step 4: Run the program
# ==============================
if __name__ == "__main__":
main()
β’ Tested with real API data
β’ Handles invalid inputs and network errors
β’ Runs smoothly on Python 3.8β3.12
β’ Easy to customize and extend
5) Example Output (Terminal Sample)
User Input:
Output:
π‘οΈ Temperature: 15Β°C
π§ Humidity: 62%
π¬οΈ Wind Speed: 3.5 m/s
π₯οΈ Condition: Broken clouds
---------------------------------------------
If user enters an invalid city:
β City not found. Please check the name and try again.
If user exits:
π Thank you for using the Weather App! Goodbye!
6) Extension Challenge
π― To make this project more advanced
| Challenge | Description |
|---|---|
| π Add a GUI using Tkinter | Create a simple interface with text boxes and buttons for entering cities |
| π Display 5-day forecast | Use the /forecast endpoint of the API |
| πΊοΈ Add Location Auto-detect | Use geocoder or ipinfo API to get weather for the user's current location |
| πΎ Save recent searches | Write the last 5 searched cities to a CSV or text file |
7) Summary
In this project, you learned how to:
- β Use APIs to fetch real-time data
- β Handle JSON responses
- β Build interactive command-line applications
- β Manage errors and network exceptions
π¬ "Congratulations! You've just connected Python with the real world β and built your first API-powered app!"
This project is a solid step toward more advanced Python projects such as:
- GUI dashboards
- Weather forecasting with visualization
- IoT-based smart weather devices