Thuta Learning
Python
ProjectsProgrammingBeginner

Weather App (Enhanced)

PythonLesson 6635 min

What you'll walk away with

  • Read an API key from an environment variable instead of hard-coding it
  • Call a JSON API with requests using params=, a timeout and the HTTP status code
  • Turn each failure (empty input, 404, 401, 429, timeout, bad JSON shape) into one WeatherError
  • Separate fetching, parsing into a dataclass and formatting so each part can be tested offline

Explain it simply

Explain it simply

A weather app looks simple: type a city, see the temperature. Behind that one line, your program asks a server on the internet for data, waits for the answer, and turns a block of JSON into a sentence a person can read.

The first version most people write works on a good day. This enhanced version is about the bad days: the city is misspelled, the Wi-Fi drops, the key expires, or the service says you asked too often. A good app answers each of those with a calm, specific message instead of a crash or a blank screen.

Problem → Why → Solution

The problem: a script written for good days only

Here is the version many tutorials start with. It runs, and with a valid key it even prints the weather. But read it as if you were the user on a bad day.

The key sits in the source file, so it ends up in Git and in every screenshot. The URL is plain http, so the key also travels unencrypted. The city is pasted straight into the URL, so "New York" or "A&B" builds a broken query. requests.get() has no timeout, so a stalled server freezes the app forever. And every problem, from a typo to a KeyError, collapses into one vague message.

weather_draft.py
import requests

API_KEY = "a1b2c3d4e5"  # a real key, now committed to Git
URL = "http://api.openweathermap.org/data/2.5/weather"

def get_weather(city):
    url = f"{URL}?q={city}&appid={API_KEY}&units=metric"
    try:
        data = requests.get(url).json()   # no timeout, status never checked
        return f"{data['main']['temp']} C"
    except Exception as e:
        return f"Error: {e}"              # a 404 shows up as: Error: 'main'

Why does this let users down?

The code mixes four jobs in one function: configuration, transport, parsing and display. Because nothing is separated, nothing can be checked on its own, and every failure looks the same. Error: 'main' tells the user nothing; it is really a 404 or a 401 in disguise. Splitting the jobs lets each failure get its own honest message.

Core concept: small layers and an error map

A dependable API client is built from small layers that each do one job. The layers hand plain Python values to each other, so you can test any one of them without the others. This project has five steps, and the main example implements all of them in about sixty lines.

1. Configuration: the key comes from the environment

The API key is read from os.environ, never from the source file. Locally you set it in your shell or in a .env file that Git ignores; in production the hosting platform injects it. If the variable is missing, the app should stop at startup with a clear message rather than fail later on the first request.

2. Transport: params, https and a timeout

fetch_weather() calls session.get() with params=, so requests URL-encodes the city for you. It uses https and timeout=5, so a dead connection raises requests.Timeout after five seconds instead of hanging. The session arrives as an argument: the real app passes requests.Session(), the demo passes a fake.

3. Status first, body second

Check resp.status_code before touching the JSON. A 404 body has no main key at all, so reading data["main"] first is exactly how the draft above turned a missing city into a confusing KeyError.

4. Parse into a domain model

The raw JSON is nested and full of fields you do not need. Copy the four you use into a Weather dataclass. If any key is missing or has the wrong type, raise one WeatherError, so the rest of the program only ever sees a complete, valid Weather.

5. Keep display separate

format_weather() turns a Weather into text. It never makes a request, so rewording a message or adding Fahrenheit can never break the network code.

SituationHow you detect itMessage for the user
Empty inputcity.strip() is ""Please type a city name
Unknown citystatus 404City not found
Bad or expired keystatus 401API key rejected
Too many callsstatus 429Wait a minute
Server stallsrequests.TimeoutService is too slow
Missing fieldsKeyError / IndexErrorUnexpected data shape
Mental model: a line of checkpoints
  1. Clean and check the user's input
  2. Send it with params and a timeout
  3. Check the status code first
  4. Copy JSON fields into a dataclass
  5. Format the result for display

Any checkpoint can stop the line with one WeatherError, so the caller needs exactly one except clause.

General pattern

python
def fetch(query, session, api_key):
    try:
        resp = session.get(URL, params={"q": query, "key": api_key}, timeout=5)
    except requests.RequestException:
        raise AppError("network problem")
    if resp.status_code != 200:
        raise AppError(f"service answered {resp.status_code}")
    data = resp.json()
    return Model(field=data["field"])

Inject the session, send params with a timeout, translate network errors into the app's own exception, check the status, and only then copy the JSON into a model.

The enhanced weather client, tested offline

The file below is the whole app minus the input() prompt. FakeSession stands in for requests.Session(): it has the same get() method but answers from a dictionary, so the demo runs without a key or a network.

Six cities drive six different paths through fetch_weather(): one success and five kinds of failure. Before looking at the output, predict what each city will print.

weather_app.py
import os
from dataclasses import dataclass

import requests

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


class WeatherError(Exception):
    """A problem we can explain to the user in one friendly sentence."""


@dataclass
class Weather:
    city: str
    temp_c: float
    description: str
    humidity: int


def fetch_weather(city, session, api_key):
    city = city.strip()
    if not city:
        raise WeatherError("Please type a city name.")
    params = {"q": city, "appid": api_key, "units": "metric"}
    try:
        resp = session.get(API_URL, params=params, timeout=5)
    except requests.Timeout:
        raise WeatherError("The weather service is too slow, try again soon.")
    except requests.ConnectionError:
        raise WeatherError("No connection to the weather service.")

    if resp.status_code == 404:
        raise WeatherError(f"City not found: {city}")
    if resp.status_code == 401:
        raise WeatherError("API key rejected, check OPENWEATHER_API_KEY.")
    if resp.status_code == 429:
        raise WeatherError("Too many requests, wait a minute.")
    if resp.status_code != 200:
        raise WeatherError(f"Weather service error ({resp.status_code}).")

    data = resp.json()
    try:
        return Weather(
            city=data["name"],
            temp_c=float(data["main"]["temp"]),
            description=data["weather"][0]["description"],
            humidity=int(data["main"]["humidity"]),
        )
    except (KeyError, IndexError, TypeError, ValueError):
        raise WeatherError("The service sent data in an unexpected shape.")


def format_weather(w):
    return f"{w.city}: {w.temp_c:.1f} C, {w.description}, humidity {w.humidity}%"


# ---- Offline stand-ins for requests.Session (no network needed) ----
class FakeResponse:
    def __init__(self, status_code, payload):
        self.status_code = status_code
        self._payload = payload

    def json(self):
        return self._payload


class FakeSession:
    def __init__(self, outcomes):
        self.outcomes = outcomes  # city -> FakeResponse or an exception

    def get(self, url, params=None, timeout=None):
        outcome = self.outcomes[params["q"]]
        if isinstance(outcome, Exception):
            raise outcome
        return outcome


yangon = {"name": "Yangon", "main": {"temp": 31.46, "humidity": 74},
          "weather": [{"description": "scattered clouds"}]}
session = FakeSession({
    "Yangon": FakeResponse(200, yangon),
    "Atlantis": FakeResponse(404, {"message": "city not found"}),
    "Mandalay": FakeResponse(200, {"name": "Mandalay", "weather": []}),
    "Bago": requests.Timeout(),
    "Paris": FakeResponse(429, {"message": "rate limit"}),
})
# Real app: api_key = os.environ["OPENWEATHER_API_KEY"]; session = requests.Session()
api_key = os.environ.get("OPENWEATHER_API_KEY", "demo-key")

for city in ["Yangon", "   ", "Atlantis", "Mandalay", "Bago", "Paris"]:
    try:
        print(format_weather(fetch_weather(city, session, api_key)))
    except WeatherError as err:
        print(f"[{city.strip() or '?'}] {err}")

Code breakdown

  1. Secret from the environmentapi_key = os.environ.get("OPENWEATHER_API_KEY", "demo-key")

    The fallback only lets anyone run the demo. A real app writes os.environ["OPENWEATHER_API_KEY"], which raises KeyError at startup when the variable is missing.

  2. params= and timeout=resp = session.get(API_URL, params=params, timeout=5)

    requests encodes the params dictionary as ?q=...&appid=... for you, and timeout=5 raises requests.Timeout when the server takes longer than five seconds.

  3. Status before bodyif resp.status_code == 404:

    Each status code gets its own message, and resp.json() is read only after the status is known to be 200.

  4. Parse or rejectexcept (KeyError, IndexError, TypeError, ValueError):

    Mandalay's fake payload has no main key, so data["main"] raises KeyError and this line catches it, producing a polite message instead of a traceback.

  5. A fake that raisesif isinstance(outcome, Exception):

    For Bago the dictionary holds a requests.Timeout() object, so the fake raises it, simulating a stalled server without waiting five real seconds.

  6. One except for the callerexcept WeatherError as err:

    All five failures arrive as WeatherError, so the loop needs one except. Programming bugs such as a NameError are not caught here, so they still surface immediately.

You should see
Yangon: 31.5 C, scattered clouds, humidity 74%
[?] Please type a city name.
[Atlantis] City not found: Atlantis
[Mandalay] The service sent data in an unexpected shape.
[Bago] The weather service is too slow, try again soon.
[Paris] Too many requests, wait a minute.

Testing the client without a network

Accepting the session as a parameter (dependency injection) is the most important decision in this project. Tests no longer depend on the internet, so they are fast and give the same result every time. You can also stage cases that are hard to trigger on the real service, such as a truncated JSON body or a 429.

If you would rather not write a fake class, the standard library's unittest.mock does the job. A Mock accepts any attribute, returns whatever you configure, and records the arguments it was called with, so a test can even assert that a timeout was passed.

mock_session.py
from unittest import mock

response = mock.Mock(status_code=404)
response.json.return_value = {"message": "city not found"}
session = mock.Mock()
session.get.return_value = response

resp = session.get("https://api.example.com/weather",
                   params={"q": "Atlantis"}, timeout=5)
print(resp.status_code, resp.json())
print("sent params:", session.get.call_args.kwargs["params"])
print("timeout used:", session.get.call_args.kwargs["timeout"])

In real projects

In real projects

Production weather features, such as a delivery app's rain warning, a farming dashboard or a smart-home thermostat, use exactly these layers plus two more concerns. The first is cost and quotas: free API plans limit calls per minute and per day, so apps cache each city's reading for a few minutes and share it between users instead of calling the API on every page view. The second is honesty about time: a cached or fallback reading should say how old it is, and timestamps from the API should be shown in the city's local time, not the server's.

Teams also keep the key out of the browser entirely. The mobile or web front end calls the team's own backend, and only the backend holds OPENWEATHER_API_KEY; otherwise anyone could open the developer tools and copy the key.

Common mistakes

Common mistakes

Wrapping everything in except Exception

except Exception catches network failures, but it also hides your own bugs, such as a NameError from a typo, behind an "Error: ..." message. Catch only what you expect: requests.Timeout, requests.ConnectionError and the parsing errors.

Calling requests without a timeout

requests has no default timeout. If a server accepts the connection and never answers, the call can wait indefinitely and the whole app freezes. Pass timeout= on every request.

Reading the JSON before checking the status

Error responses have a different body shape. Reading data["main"] first gives you KeyError: 'main' instead of "city not found". Always check status_code first.

Logging the full request URL

The query string contains appid=..., so printing or logging the full URL leaks the key. Log the city and the status code instead.

Best practices

Best practices

  • Use one requests.Session() inside a with block when a program makes many calls, so connections are reused
  • Always state the temperature unit (metric or imperial) in the output
  • Keep one fake response and one test for every failure path
  • Never put the key in code, so it can be rotated without a release

Mini challenge

Add a cache with a freshness label

Free API plans limit how often you can call. Write a WeatherCache class that remembers each city's reading for ttl_seconds and, when the service fails, returns the old reading labelled as stale instead of an error.

  • get(city) returns (reading, label), where label is "fresh" or "stale, N min old"
  • Treat " yangon " and "Yangon" as the same city
  • Within ttl_seconds, return the saved reading without calling fetch
  • If fetch raises WeatherError and an old reading exists, return it as stale; otherwise re-raise
  • Take the clock as a parameter so tests can move time without sleeping
weather_cache.py
class WeatherError(Exception):
    pass


class WeatherCache:
    def __init__(self, fetch, clock, ttl_seconds=600):
        # TODO: store fetch, clock and the ttl; start with an empty dict
        ...

    def get(self, city):
        # TODO: turn the city into a cache key (strip + lower)
        # TODO: saved reading younger than the ttl -> return (reading, "fresh")
        # TODO: otherwise call fetch(city) and save (now, reading)
        # TODO: on WeatherError return the old reading as "stale, N min old",
        #       or re-raise when nothing was saved
        ...


# TODO: test with a fake clock (a list you change) and a fake fetch function

Expected: The first call fetches once, the second (two minutes later) returns fresh without fetching, after fifteen minutes with the service down you get "stale, 15 min old", and Bago, never cached, still raises.

Show hint

Store each entry as a (saved_at, reading) tuple; it is fresh when now - saved_at < ttl. Use int((now - saved_at) // 60) for minutes. For a fake clock, keep fake_time = [0] and pass clock=lambda: fake_time[0].

Show solution
weather_cache.py
class WeatherError(Exception):
    pass


class WeatherCache:
    def __init__(self, fetch, clock, ttl_seconds=600):
        self.fetch = fetch          # function: city -> reading (may raise)
        self.clock = clock          # function: () -> current time in seconds
        self.ttl = ttl_seconds
        self.entries = {}           # city key -> (saved_at, reading)

    def get(self, city):
        key = city.strip().lower()
        now = self.clock()
        if key in self.entries:
            saved_at, reading = self.entries[key]
            if now - saved_at < self.ttl:
                return reading, "fresh"
        try:
            reading = self.fetch(city)
        except WeatherError:
            if key in self.entries:
                saved_at, reading = self.entries[key]
                minutes = int((now - saved_at) // 60)
                return reading, f"stale, {minutes} min old"
            raise
        self.entries[key] = (now, reading)
        return reading, "fresh"


# ---- test doubles: a fake clock and a fake fetch function ----
fake_time = [0]
calls = []
service_up = [True]


def fake_fetch(city):
    calls.append(city)
    if not service_up[0]:
        raise WeatherError("service down")
    return f"{city.strip()} 31 C"


cache = WeatherCache(fake_fetch, clock=lambda: fake_time[0], ttl_seconds=600)

print(cache.get("Yangon"), "calls:", len(calls))
fake_time[0] = 120
print(cache.get(" yangon "), "calls:", len(calls))
fake_time[0] = 900
service_up[0] = False
print(cache.get("Yangon"), "calls:", len(calls))
try:
    cache.get("Bago")
except WeatherError as err:
    print("Bago:", err)

Quick quiz 1 / 3

In the main example, what does the loop print for the Mandalay entry, whose JSON has no "main" key?

Quick quiz 2 / 3

Why does fetch_weather() send the city through params= instead of an f-string URL?

Quick quiz 3 / 3

A teammate writes requests.get(url) with no timeout. What happens if the server accepts the connection but never answers?

What to remember

  • Read the API key from os.environ and keep it out of code, logs and printed URLs
  • Use params=, https and timeout= on every request
  • Check the status code first, then parse the JSON into a dataclass
  • Convert every failure into one app exception with a specific message
  • Injecting the session lets you test every failure path without a network

Requests — User Guide — Requests

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Weather App (Enhanced) | Thuta Learning