Skip to content
Kuza Ndoto Academy

Project: Weather App

Beginner → IntermediateChapter 10 · Page 54 of 568 min readUpdated 15 Nov 2026

In this project you'll build a weather app that calls a real web API and shows the current conditions for East African cities, or any place you search for. You'll learn how to request data from the internet, read JSON responses and handle the many ways network calls can fail.

The goal

We'll use Open-Meteo, a free weather API that doesn't need an account or API key for non-commercial use. Our app will:

  • show a menu of cities (Nairobi, Mombasa, Kisumu, Kampala, Dar es Salaam and Kigali);
  • let the user search for any other place by name, using Open-Meteo's geocoding service;
  • display the current conditions, temperature, humidity and wind speed;
  • handle no internet connection, slow replies, server errors, unexpected data and unknown places without crashing.

Step 1: Set up the project

We'll use the popular requests library, so create a virtual environment first (see pip & virtual environments):

mkdir weather-app
cd weather-app
python -m venv .venv
.venv\Scripts\Activate.ps1          # Windows PowerShell
# source .venv/bin/activate         # macOS / Linux
python -m pip install requests

Step 2: Make your first API call

An API (application programming interface) is a web address that returns data for programs instead of a page for people. Open-Meteo takes the latitude and longitude in the URL and returns JSON. Try this short test:

import requests

url = "https://api.open-meteo.com/v1/forecast?latitude=-1.29&longitude=36.82&current=temperature_2m"
response = requests.get(url, timeout=10)

print(response.status_code)
print(response.json()["current"])

Live data changes constantly, so this is only an example of what you might see:

200 {'time': '2026-03-14T09:30', 'interval': 900, 'temperature_2m': 21.4}

Status code 200 means success. response.json() turns the JSON reply into Python dictionaries and lists. When we ask for more values, the full reply looks something like this (simplified example):

{
  "latitude": -1.25,
  "longitude": 36.875,
  "timezone": "Africa/Nairobi",
  "current_units": {
    "time": "iso8601",
    "interval": "seconds",
    "temperature_2m": "°C",
    "relative_humidity_2m": "%",
    "wind_speed_10m": "km/h",
    "weather_code": "wmo code"
  },
  "current": {
    "time": "2026-03-14T09:30",
    "interval": 900,
    "temperature_2m": 21.4,
    "relative_humidity_2m": 68,
    "wind_speed_10m": 11.2,
    "weather_code": 2
  }
}

The weather_code is a standard WMO number (0 means clear sky, 61 means light rain, 95 means thunderstorm), so our program needs a dictionary to turn codes into words. Notice too that the API snaps your coordinates to the nearest point on its weather grid, which is why the latitude came back slightly different.

Step 3: Plan the error handling

Network code fails far more often than ordinary code. A good app expects that:

ProblemHow we detect it
No internet or the server can't be reachedrequests.exceptions.ConnectionError
The server is too slowtimeout=10 raises requests.exceptions.Timeout
The server replies with an error status (400, 404, 500...)response.raise_for_status() raises HTTPError
The reply isn't valid JSONrequests.exceptions.JSONDecodeError
The JSON is missing fields we expectKeyError
A place name isn't foundThe geocoding reply has no "results"

All requests go through one helper, get_json(), so this handling is written once.

menu city: coordinates already known User inputcity or search Geocoding APIname → lat, lon Forecast APIlat, lon → JSON Reportprinted for user get_json() catches the error friendly message, no crash
Figure 1. Searched places go through the geocoding API first; menu cities skip it because their coordinates are stored in CITIES. If either request fails, the user sees a clear message and the menu carries on.

Step 4: The full program

Save this as weather_app.py and run it with python weather_app.py while your virtual environment is active.

"""Kuza Weather: live weather for East African cities from Open-Meteo."""
import requests

FORECAST_URL = "https://api.open-meteo.com/v1/forecast"
GEOCODING_URL = "https://geocoding-api.open-meteo.com/v1/search"

CITIES = {
    "1": ("Nairobi", -1.29, 36.82),
    "2": ("Mombasa", -4.04, 39.67),
    "3": ("Kisumu", -0.09, 34.77),
    "4": ("Kampala", 0.35, 32.58),
    "5": ("Dar es Salaam", -6.79, 39.21),
    "6": ("Kigali", -1.95, 30.06),
}

WEATHER_CODES = {
    0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
    45: "Fog", 48: "Depositing rime fog",
    51: "Light drizzle", 53: "Drizzle", 55: "Heavy drizzle",
    61: "Light rain", 63: "Rain", 65: "Heavy rain",
    80: "Light showers", 81: "Showers", 82: "Violent showers",
    95: "Thunderstorm", 96: "Thunderstorm with hail", 99: "Thunderstorm with heavy hail",
}


def get_json(url, params):
    """Call a web API. Return the decoded JSON, or None if anything fails."""
    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()          # turn 4xx/5xx replies into errors
        return response.json()
    except requests.exceptions.Timeout:
        print("The weather service took too long to reply. Please try again.")
    except requests.exceptions.ConnectionError:
        print("Could not connect. Check your internet connection.")
    except requests.exceptions.HTTPError as error:
        print(f"The service returned an error: {error}")
    except requests.exceptions.JSONDecodeError:
        print("The service sent back data that could not be read.")
    except requests.exceptions.RequestException as error:
        print(f"Something went wrong with the request: {error}")
    return None


def find_place(name):
    """Look up a place name. Return (label, latitude, longitude) or None."""
    params = {"name": name, "count": 1, "language": "en", "format": "json"}
    data = get_json(GEOCODING_URL, params)
    if data is None:
        return None                          # get_json has already explained why
    results = data.get("results")
    if not results:
        print(f"Sorry, no place called '{name}' was found.")
        return None
    place = results[0]
    label = place["name"]
    if place.get("country"):
        label += f", {place['country']}"
    return label, place["latitude"], place["longitude"]


def get_weather(latitude, longitude):
    """Return a dictionary describing the current weather, or None."""
    params = {
        "latitude": latitude,
        "longitude": longitude,
        "current": "temperature_2m,relative_humidity_2m,wind_speed_10m,weather_code",
        "timezone": "auto",
    }
    data = get_json(FORECAST_URL, params)
    if data is None:
        return None
    try:
        current = data["current"]
        units = data["current_units"]
        code = current["weather_code"]
        return {
            "time": current["time"].replace("T", " "),
            "conditions": WEATHER_CODES.get(code, f"Unknown conditions (code {code})"),
            "temperature": f"{current['temperature_2m']}{units['temperature_2m']}",
            "humidity": f"{current['relative_humidity_2m']}{units['relative_humidity_2m']}",
            "wind": f"{current['wind_speed_10m']} {units['wind_speed_10m']}",
        }
    except KeyError as error:
        print(f"The weather data was missing a field: {error}")
        return None


def show_weather(label, latitude, longitude):
    print(f"\nFetching weather for {label}...")
    report = get_weather(latitude, longitude)
    if report is None:
        return
    print(f"Weather in {label} (local time {report['time']})")
    print(f"  Conditions:  {report['conditions']}")
    print(f"  Temperature: {report['temperature']}")
    print(f"  Humidity:    {report['humidity']}")
    print(f"  Wind:        {report['wind']}")


def main():
    print("=== Kuza Weather ===")
    while True:
        print()
        for key, (city, _, _) in CITIES.items():
            print(f"{key}) {city}")
        print("S) Search for another place")
        print("Q) Quit")
        choice = input("Choose an option: ").strip().upper()

        if choice == "Q":
            print("Kwaheri! Stay dry.")
            break
        elif choice in CITIES:
            show_weather(*CITIES[choice])
        elif choice == "S":
            name = input("Place name: ").strip()
            if name:
                place = find_place(name)
                if place:
                    show_weather(*place)
        else:
            print("Please choose one of the options shown.")


if __name__ == "__main__":
    main()

How the important parts work

  • params=: instead of gluing values into the URL yourself, pass a dictionary and requests builds a correctly encoded query string. This matters for names with spaces, such as "Dar es Salaam".
  • timeout=10: without a timeout, a request to an unresponsive server can wait indefinitely and freeze your app.
  • The order of except blocks: specific problems come first and the general RequestException (the parent of all requests errors) comes last as a safety net.
  • show_weather(*CITIES[choice]): the * unpacks the tuple ("Nairobi", -1.29, 36.82) into the three arguments.
  • WEATHER_CODES.get(code, ...): an unknown code gives a sensible message instead of a KeyError.

Step 5: Sample run

Weather changes all the time, so this is an example of the output; your readings will be different.

=== Kuza Weather === 1) Nairobi 2) Mombasa 3) Kisumu 4) Kampala 5) Dar es Salaam 6) Kigali S) Search for another place Q) Quit Choose an option: 1 Fetching weather for Nairobi... Weather in Nairobi (local time 2026-03-14 09:30) Conditions: Partly cloudy Temperature: 21.4°C Humidity: 68% Wind: 11.2 km/h 1) Nairobi 2) Mombasa 3) Kisumu 4) Kampala 5) Dar es Salaam 6) Kigali S) Search for another place Q) Quit Choose an option: s Place name: Eldoret Fetching weather for Eldoret, Kenya... Weather in Eldoret, Kenya (local time 2026-03-14 09:30) Conditions: Light drizzle Temperature: 17.9°C Humidity: 81% Wind: 8.6 km/h 1) Nairobi 2) Mombasa 3) Kisumu 4) Kampala 5) Dar es Salaam 6) Kigali S) Search for another place Q) Quit Choose an option: s Place name: Atlantisxyz Sorry, no place called 'Atlantisxyz' was found. 1) Nairobi 2) Mombasa 3) Kisumu 4) Kampala 5) Dar es Salaam 6) Kigali S) Search for another place Q) Quit Choose an option: q Kwaheri! Stay dry.

If you switch off your Wi-Fi and choose Nairobi, the app stays running and explains the problem:

Fetching weather for Nairobi... Could not connect. Check your internet connection.
Common mistake

Calling response.json() without checking the status first. An error page from a server might not be JSON at all, or might be JSON describing the error. Always call response.raise_for_status() (or check response.status_code) before using the data.

Warning

Be a good API citizen. Free services like Open-Meteo have fair-use limits, so don't call them in a tight loop. If you later use an API that needs a key, never paste the key directly into code you share; load it from an environment variable instead.

Extend it

  1. Add a forecast: request "daily": "temperature_2m_max,temperature_2m_min,precipitation_probability_max" and print a three-day forecast table. Open-Meteo's documentation lists every available variable.
  2. Remember favourites: save places the user searched for to a JSON file and add them to the menu next time (see CSV & JSON).
  3. Give advice: use the weather code and temperature to print tips such as "Carry an umbrella" or "Good day to dry clothes", and use a class such as WeatherReport to hold the data.

Key points

  • requests.get(url, params=..., timeout=...) calls a web API; response.json() decodes the reply.
  • Always use a timeout and raise_for_status(), and catch requests exceptions.
  • Validate the JSON you receive: fields can be missing and searches can return nothing.
  • Live data varies, so test with care and label example output as an example.
Up next · Projects & PracticePython Interview QuestionsCommon questions and model answers.
→

Tip: use the ← and → keys to move between pages.