Course map
Stage 1: Foundations
Stage 2: Data Integration
Stage 3: Building & Shipping
Stage 4: Customer Engagement
Stage 5: Specialization

Part 09 / Stage 3

Services and APIs

Goal: Expose what you built to the customer's people and systems: a small, well-mannered API with auth, validation, health checks, and tests their platform team will respect. Time: ~3.5 hours · Needs: Python 3.14+, the course venv (FastAPI is installed)

What you will learn

  • Designing a small API: resources, methods, status codes, error format
  • FastAPI basics: routes, request and response models
  • Authentication: API keys and tokens, comparing secrets safely
  • Validation and errors: clear 4xx messages, no leaked internals in 5xx
  • Health and readiness checks: what platform teams expect
  • Testing services: TestClient and contract tests
  • Quick internal UIs for customer teams

Topics in this part

Practice

Work in the course venv. Check each answer by running it; compare with solutions/ only after trying.

Exercise 1: Add listing with a filter

Extend the lesson's API with GET /shipments?status=delayed returning all matching shipments. Prove with TestClient: filtered list, full list, and 401 without a key.

Show the solution to Exercise 1
# Exercise 1: list shipments, filterable by status
import hmac
from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient

API_KEY = "key-123"
SHIPMENTS = {"S-2001": {"id": "S-2001", "status": "delivered"},
             "S-2002": {"id": "S-2002", "status": "delayed"},
             "S-2003": {"id": "S-2003", "status": "delayed"}}

def require_key(x_api_key: str = Header(default="")):
    if not hmac.compare_digest(x_api_key, API_KEY):
        raise HTTPException(status_code=401, detail="invalid API key")

app = FastAPI(dependencies=[Depends(require_key)])

@app.get("/shipments")
def list_shipments(status: str | None = None):
    rows = list(SHIPMENTS.values())
    if status:
        rows = [r for r in rows if r["status"] == status]
    return {"data": rows, "count": len(rows)}

c = TestClient(app)
print(c.get("/shipments", params={"status": "delayed"}, headers={"x-api-key": API_KEY}).json())
print(c.get("/shipments", headers={"x-api-key": API_KEY}).json()["count"], "total")
print(c.get("/shipments").status_code, "(no key)")

Exercise 2: Opaque 5xx

Add a route that raises an unexpected exception, and an exception handler that returns {"detail": "internal error", "error_id": "..."} with status 500 while printing the real traceback type to stdout (your "log"). Show the response body contains no internals.

Show the solution to Exercise 2
# Exercise 2: 5xx bodies stay opaque; details go to the log
import uuid
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/explode")
def explode():
    raise RuntimeError("database password is hunter2")   # must never reach the caller

@app.exception_handler(Exception)
async def unhandled(request: Request, exc: Exception):
    error_id = uuid.uuid4().hex[:8]
    print(f"log: error {error_id}: {type(exc).__name__}")   # the real detail goes to logs
    return JSONResponse(status_code=500, content={"detail": "internal error", "error_id": error_id})

c = TestClient(app, raise_server_exceptions=False)
r = c.get("/explode")
body = r.json()
print(r.status_code, {"detail": body["detail"], "error_id": "<random>"})
assert "hunter2" not in r.text and "RuntimeError" not in r.text
print("no internals leaked: True")

Exercise 3: Readiness that is honest but calm

Build /readyz over deps = {"database": ..., "acme_api": ...} where only database is required for readiness; acme_api down must keep readyz 200 but appear in a "degraded" list. Show both states.

Show the solution to Exercise 3
# Exercise 3: required vs degraded dependencies in readiness
from fastapi import FastAPI, Response
from fastapi.testclient import TestClient

app = FastAPI()
deps = {"database": True, "acme_api": False}
REQUIRED = {"database"}

@app.get("/readyz")
def readyz(response: Response):
    failing_required = [n for n in REQUIRED if not deps[n]]
    degraded = [n for n, ok in deps.items() if not ok and n not in REQUIRED]
    if failing_required:
        response.status_code = 503
    return {"ready": not failing_required, "failing": failing_required, "degraded": degraded}

c = TestClient(app)
r = c.get("/readyz")
print("vendor down:  ", r.status_code, r.json())
deps["database"] = False
r = c.get("/readyz")
print("database down:", r.status_code, r.json())

Exercise 4: A contract test file

Write the four-assert contract test (200, 401, 404, 422) as a real pytest file run from the script (Part 3 pattern). All four must pass.


Show the solution to Exercise 4
# Exercise 4: the contract, as a pytest file
import pathlib, re, subprocess, sys, tempfile, textwrap

code = textwrap.dedent('''
    import hmac
    from fastapi import Depends, FastAPI, Header, HTTPException
    from fastapi.testclient import TestClient
    from pydantic import BaseModel

    API_KEY = "key-123"
    SHIPMENTS = {"S-2001": {"id": "S-2001", "status": "delivered"}}

    def require_key(x_api_key: str = Header(default="")):
        if not hmac.compare_digest(x_api_key, API_KEY):
            raise HTTPException(status_code=401, detail="invalid API key")

    app = FastAPI(dependencies=[Depends(require_key)])

    class StatusUpdate(BaseModel):
        status: str

    @app.get("/shipments/{sid}")
    def get_shipment(sid: str):
        if sid not in SHIPMENTS:
            raise HTTPException(status_code=404, detail=f"shipment {sid} not found")
        return SHIPMENTS[sid]

    @app.patch("/shipments/{sid}")
    def update(sid: str, body: StatusUpdate):
        get_shipment(sid)["status"] = body.status
        return SHIPMENTS[sid]

    c = TestClient(app)
    KEY = {"x-api-key": API_KEY}

    def test_read_ok():
        assert c.get("/shipments/S-2001", headers=KEY).status_code == 200

    def test_needs_key():
        assert c.get("/shipments/S-2001").status_code == 401

    def test_missing_resource():
        assert c.get("/shipments/NOPE", headers=KEY).status_code == 404

    def test_invalid_body():
        assert c.patch("/shipments/S-2001", headers=KEY, json={}).status_code == 422
''')
folder = pathlib.Path(tempfile.mkdtemp())
(folder / "test_contract.py").write_text(code)
r = subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", str(folder)],
                   capture_output=True, text=True)
print(re.sub(r" in \d+\.\d+s", "", r.stdout.strip().splitlines()[-1]))

Mini-project: The Shipments API

Read and update endpoints over the Stage 2 pipeline's data (seed a dict from fdelab._API_SHIPMENTS or your sqlite table), with API-key auth, validation, /healthz + /readyz, and a TestClient suite proving the contract.

A solution is in solutions/mini_shipments_api.py.

Stretch: add pagination and status filtering, and export the OpenAPI description (app.openapi()) the customer can share internally.

Common mistakes

Mistake Why it hurts Fix
Action-shaped URLs (/getShipment) Every consumer learns a bespoke dialect Resources + methods
== on secrets Timing side-channel hmac.compare_digest, always
Stack traces in 5xx bodies Leaks internals to systems you don't control Opaque 5xx + an error id; trace to logs
One /health doing both jobs Restarts when it should just unroute (and vice versa) Separate liveness and readiness
Failing readiness on any dependency A vendor outage takes your whole service down Fail only on truly required deps; circuit-break the rest
Testing handlers, not the contract Refactors silently break consumers TestClient asserts on status codes and shapes

Quick recap

  • A good API contract is boring: resources, standard methods, known status codes, and one error shape.
  • FastAPI and Pydantic validate requests before your code runs, so the 422 response comes free.
  • Issue one API key per team, compare keys in constant time, and answer a missing key with a 401.
  • Make 4xx errors precise and 5xx errors opaque.
  • healthz says the process is alive and readyz says it can serve right now; fail readiness sparingly.
  • TestClient contract tests are the API's promise in executable form.

Checklist

  • I ran the API example and matched all five output lines to contract behaviours.
  • I can explain why the auth header defaults to "".
  • I know what goes in a 4xx body and what must not go in a 5xx body.
  • I can state the healthz/readyz split and the readiness judgment call.
  • I wrote four contract asserts with TestClient.

Read more: FastAPI tutorial · FastAPI testing

Search the guide