Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 17: Databases and web APIs

Objectives: LO-17.1, LO-17.2, LO-17.3
Prerequisites: the Module 17 reading and Lab 16
Time: about 2 hours

In this lab you predict what a transaction keeps, build and query a table of rain readings, break a query with SQL injection and then fix it, fetch JSON from a web API with retries, and test the API code without a working server. Each exercise ends with a check cell that prints passed or says what is wrong.

Setup

Run the next cell first. It starts a small weather API, like the reading’s, on a free port of this computer, in a thread of its own, so it answers while the rest of the notebook runs. BASE is its address. It knows the stations Harbor, Hilltop, Mill Lane, and Broken, whose data is damaged, so the server answers 500. /flaky/<name> answers 503 twice for each name, then 200. ?delay= makes it wait before answering, and requests_seen lists the path of every request it gets.

The cell also sets the environment variable LAB17_KEY to the API’s key, as you would in a terminal before starting a program. The databases in this lab live in memory, so the lab writes no files.

1. What a transaction keeps

Read this code, but don’t run it yet. quantity >= 0 is a constraint, so no row may hold a negative quantity. quantity - 1 in an UPDATE uses each row’s own value.

db = sqlite3.connect(":memory:")
db.execute(
    "CREATE TABLE stock (item TEXT PRIMARY KEY, quantity INTEGER NOT NULL CHECK (quantity >= 0))"
)
with db:
    db.executemany("INSERT INTO stock VALUES (?, ?)", [("pens", 12), ("pads", 3), ("tape", 0)])
with db:
    changed = db.execute(
        "UPDATE stock SET quantity = quantity - 1 WHERE quantity > ?", (2,)
    ).rowcount
try:
    with db:
        db.execute("UPDATE stock SET quantity = quantity + 10 WHERE item = ?", ("tape",))
        db.execute("UPDATE stock SET quantity = quantity - 5 WHERE item = ?", ("pads",))
except sqlite3.IntegrityError:
    pass
final = db.execute("SELECT item, quantity FROM stock ORDER BY item").fetchall()
glue = db.execute("SELECT quantity FROM stock WHERE item = ?", ("glue",)).fetchone()
db.close()

Exercise L17.1 (LO-17.1, ★, about 10 minutes)

Predict the value of each name: p1 for changed, p2 for final, and p3 for glue.

2. A table of readings

Exercise L17.2 (LO-17.1, ★★, about 20 minutes)

Write two functions:

  1. create_readings(connection) creates a table named readings with an id that SQLite fills in, and three columns that must all have a value: station, text; day, text, such as "2026-11-02"; and rain_mm, a float (REAL in SQLite) that can’t be negative. Add the line UNIQUE (station, day) after the columns, which refuses a second reading for the same station on the same day.

  2. add_readings(connection, rows) adds the readings in rows, an iterable of (station, day, rain_mm) tuples, in one transaction: either every reading is saved, or, if any is refused, none is, and the exception reaches the caller.

3. Questions and corrections

SUM(rain_mm) adds up a column over the rows in each group, as COUNT(*) counts them, and a WHERE condition can join two conditions with AND.

Exercise L17.3 (LO-17.1, ★★, about 20 minutes)

Write two functions, using your readings table:

  1. rain_by_station(connection) returns a dictionary that maps each station to its total rainfall, rounded to one decimal place, in alphabetical order of station. Let the database do the adding up, with GROUP BY.

  2. correct_reading(connection, station, day, rain_mm) changes one reading’s rain_mm, and saves the change. If no reading matches the station and the day, it raises LookupError with a message that names both.

4. SQL injection

This cell makes a table of readings of its own, and a function that builds its query with an f-string. Don’t copy the function.

Exercise L17.4 (LO-17.1, ★★, about 15 minutes)

  1. Set attack to a station name that makes readings_for_unsafe return every reading in the table. Write the query the f-string builds with your name on paper first.

  2. Write readings_for(connection, station), which returns the same results for an honest name, but uses a placeholder, so that attack finds no readings and "St. Mary's" finds its own.

5. Fetching JSON

A program reads its API key from the environment, never from its own code:

Exercise L17.5 (LO-17.2, ★★, about 15 minutes)

Write two functions for the lab’s API:

  1. get_json(url, key, timeout=2.0) requests url with the headers Accept: application/json and X-API-Key: <key>, waits at most timeout seconds, and returns the body’s JSON. It lets every exception from urlopen reach the caller.

  2. fetch_station(base_url, name, key) returns the JSON for {base_url}/stations/<name>, with the name quoted for the URL. It returns None for a 404, raises PermissionError with a message about the key for a 401, and lets every other error reach the caller.

6. Trying again

A 429 (Too Many Requests) or a 503 (Service Unavailable), a refused connection, and a timeout can all go away if the program waits and tries again. Waiting longer after each failure, which is called backoff, gives a struggling service room to recover. Every other error will be the same next time.

Exercise L17.6 (LO-17.2, ★★★, about 20 minutes)

Write get_with_retries(url, key, attempts=3, wait=1.0, timeout=2.0), which calls your get_json up to attempts times:

  • It returns the JSON as soon as an attempt succeeds.

  • After an HTTPError with the status 429 or 503, a URLError, or a TimeoutError, it calls time.sleep and tries again: wait seconds after the first failure, twice as long after the second, and so on. After the last attempt, it raises that attempt’s exception, without sleeping first.

  • Any other HTTPError it raises at once, without trying again.

Remember that HTTPError is a subclass of URLError.

7. Testing without the service

describe_station turns your fetch_station’s answers into a sentence for a person:

Exercise L17.7 (LO-17.3, ★★, about 15 minutes)

  1. Write api_key(), which returns the value of the environment variable LAB17_KEY, and raises RuntimeError with a message that names the variable if it is missing or empty.

  2. Write two test functions, with names that start with test_, that check what describe_station says when the service can’t be reached: one in which urlopen raises URLError, and one in which it raises TimeoutError. Use patch. In a notebook, the names you define live in a module named __main__, so get_json looks up urlopen as "__main__.urlopen".

The check runs your tests on describe_station, where they must pass, and on two broken versions of it, where at least one must fail.

Summary

  • A with connection: block saved all of its changes or none: the stock that failed its check took the update before it down too.

  • Constraints in CREATE TABLE, including UNIQUE, made the database refuse bad readings on its own, whichever program sent them.

  • GROUP BY with SUM let the database add up each station’s rain, and rowcount told correct_reading whether anything matched.

  • An f-string let a station name rewrite the query; a placeholder made the same name harmless.

  • get_json and fetch_station handled each HTTP status as it deserves, and get_with_retries tried again only after errors that can go away, waiting longer each time.

  • patch stood in for a service that was down or slow, so the tests could check what a person sees in those cases without waiting for them to happen.