Fetching live weather data is a practical real-world task, and building a Weather App helps you learn API integration, JSON handling, error management, and optionally web development. In this project, we will build:
- A command-line (CLI) Weather App in Python
- An optional Flask-based web interface to display weather for a city
- Support for units (metric/imperial), error handling, and basic caching
Prerequisites
- Python 3.7+ installed
- Basic knowledge of Python (functions, modules, I/O)
- Internet access
- requests library (install using pip install requests)
- Optional: Flask (install using pip install flask)
Step 1. Get an API Key from OpenWeatherMap
- Register (free) at openweathermap.org
- Navigate to the API section and generate an API key (called appid)
- Note: Free tier allows reasonable usage for learning; be mindful of rate limits
Store your API key securely (environment variable recommended).
Example for Linux/macOS:
export OWM_API_KEY="your_api_key_here"
Example for Windows (PowerShell):
$env:OWM_API_KEY="your_api_key_here"
Step 2. CLI Weather App (weather_cli.py)
import os
import requests
from datetime import datetime
API_KEY = os.getenv("OWM_API_KEY")
BASE_URL = "https://api.openweathermap.org/data/2.5/weather"
def get_weather(city: str, units: str = "metric"):
if not API_KEY:
raise RuntimeError("OpenWeatherMap API key not found. Set OWM_API_KEY environment variable.")
params = {
"q": city,
"appid": API_KEY,
}
if units in ("metric", "imperial"):
params["units"] = units
try:
response = requests.get(BASE_URL, params=params, timeout=10)
response.raise_for_status()
data = response.json()
except requests.RequestException as e:
print(f"Network or request error: {e}")
return None
if data.get("cod") != 200:
print(f"Error from API: {data.get('message', 'Unknown error')}")
return None
return data
def format_and_print(data, units="metric"):
name = data["name"]
country = data["sys"]["country"]
weather_desc = data["weather"][0]["description"].title()
temp = data["main"]["temp"]
feels_like = data["main"]["feels_like"]
humidity = data["main"]["humidity"]
wind_speed = data["wind"]["speed"]
timestamp = datetime.fromtimestamp(data["dt"]).strftime("%Y-%m-%d %H:%M:%S")
unit_symbol = "°C" if units == "metric" else "°F" if units == "imperial" else "K"
speed_unit = "m/s" if units in ("metric", "") else "mph"
print(f"\nWeather in {name}, {country} at {timestamp}")
print("-" * 40)
print(f"Condition : {weather_desc}")
print(f"Temperature : {temp}{unit_symbol}")
print(f"Feels Like : {feels_like}{unit_symbol}")
print(f"Humidity : {humidity}%")
print(f"Wind Speed : {wind_speed} {speed_unit}")
print("-" * 40)
def main():
print("=== Python Weather CLI ===")
city = input("Enter city name: ").strip()
if not city:
print("City name cannot be empty.")
return
unit_choice = input("Units - (1) Metric (°C), (2) Imperial (°F), (3) Kelvin: ").strip()
if unit_choice == "1":
units = "metric"
elif unit_choice == "2":
units = "imperial"
else:
units = None
data = get_weather(city, units=units if units else "")
if data:
format_and_print(data, units=units if units else "")
if __name__ == "__main__":
main()
Run with
python weather_cli.py

Join the conversation! Your thoughts help the community grow.