Python · Module 14 · Lesson 21 min read

Weather CLI using an API

Project goal

Type a city name and see the current weather, using a real web API end to end.

Skills you'll combine

HTTP requests, JSON parsing, error handling, environment variables, and formatted output.

Steps

  1. Get a free API key from OpenWeatherMap (or use Open-Meteo, which needs no key).
  2. Store the key in an environment variable, never in code: export OPENWEATHER_API_KEY=...
  3. Build the request with params= and a timeout.
  4. Handle the failure cases separately: no internet, city not found (404), bad key (401), rate limit (429).
  5. Pull the fields you need out of the JSON and print them nicely.

Ideas to extend it

A 5-day forecast, °C/°F switch, caching results for 10 minutes, or reading cities from command-line arguments with argparse.

💻 Needs internet and requests, so run it on a computer.

Example

Python
import os
import requests

API_URL = "https://api.openweathermap.org/data/2.5/weather"

def get_weather(city: str, api_key: str) -> dict | None:
    try:
        resp = requests.get(
            API_URL,
            params={"q": city, "appid": api_key, "units": "metric"},
            timeout=10,
        )
    except requests.exceptions.RequestException as e:
        print("Network error:", e)
        return None

    if resp.status_code == 404:
        print(f"City '{city}' not found")
        return None
    if resp.status_code == 401:
        print("Invalid API key")
        return None
    resp.raise_for_status()
    return resp.json()

def show(data: dict) -> None:
    main, weather = data["main"], data["weather"][0]
    print(f"{data['name']}: {main['temp']:.1f}°C, {weather['description']}")
    print(f"Feels like {main['feels_like']:.1f}°C · Humidity {main['humidity']}%")

if __name__ == "__main__":
    key = os.environ.get("OPENWEATHER_API_KEY")
    if not key:
        raise SystemExit("Set the OPENWEATHER_API_KEY environment variable first")
    city = input("City: ").strip() or "Kathmandu"
    data = get_weather(city, key)
    if data:
        show(data)