Part 09 / Topic 2 of 7
FastAPI basics
FastAPI turns that contract into code with type-checked requests and responses โ and everything below actually runs, via its test client, in one file:
# examples/01_a_small_api_for_the_customer.py
import hmac
from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel
API_KEYS = {"dispatch-team": "key-123"}
SHIPMENTS = {"S-2001": {"id": "S-2001", "status": "delivered"}}
def require_key(x_api_key: str = Header(default="")): # missing key -> 401, not 422
if not any(hmac.compare_digest(x_api_key, k) for k in API_KEYS.values()):
raise HTTPException(status_code=401, detail="invalid API key")
app = FastAPI(dependencies=[Depends(require_key)])
class StatusUpdate(BaseModel):
status: str
@app.get("/shipments/{shipment_id}")
def get_shipment(shipment_id: str):
if shipment_id not in SHIPMENTS:
raise HTTPException(status_code=404, detail=f"shipment {shipment_id} not found")
return SHIPMENTS[shipment_id]
@app.patch("/shipments/{shipment_id}")
def update(shipment_id: str, body: StatusUpdate):
get_shipment(shipment_id)["status"] = body.status
return SHIPMENTS[shipment_id]
c = TestClient(app)
print(c.get("/shipments/S-2001", headers={"x-api-key": "key-123"}).json())
print(c.get("/shipments/S-2001", headers={"x-api-key": "nope"}).status_code)
print(c.get("/shipments/S-2001").status_code, "(no key at all)")
print(c.get("/shipments/S-9999", headers={"x-api-key": "key-123"}).json())
print(c.patch("/shipments/S-2001", headers={"x-api-key": "key-123"}, json={}).status_code)
# {'id': 'S-2001', 'status': 'delivered'}
# 401
# 401 (no key at all)
# {'detail': 'shipment S-9999 not found'}
# 422
Five lines of output, five contract behaviours proven: a good read, two auth rejections, a clean 404, and a 422 for an invalid body. The route functions declare their shapes (StatusUpdate), and FastAPI enforces them before your code runs.
๐งช Quick quiz โ answer from memory, then check.
- A request with a valid key asks for a shipment that does not exist. What status should the API return?
Show the answer
404 with a clear message โ the example returns 404 {'detail': 'shipment S-9999 not found'}. (verified against the example output above)
Done here? The practice set for Part 9 โ 4 exercises with solutions โ is on the part page.