APIs with FastAPI · Chapter 19 of 26
Middleware and logging
By the end of this chapter you can write a middleware that runs around every request, say in which order middleware runs and why, give every request an id, log every request as one line of JSON, and set up CORS for a web page while saying exactly what CORS does not protect. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Production
- 4 tasks
- FastAPI
- In the all labs plan
The first 2 chapters of APIs with FastAPI are free. This one comes with the all labs plan.
Why you need this
The festive rush is coming, and DakiyaGo's API now has real traffic. A merchant writes to Imran: "your API gave us an error at 3:12 this afternoon." Which of the day's forty thousand requests was it? Aman wants to know which routes are slow before merchants notice. And the new merchant dashboard, a web page at its own address, calls the API from JavaScript and gets nothing but a red error in the browser console.
None of these belongs in a route. Every route would need the same lines, and the next route someone writes would forget them. They belong in one place that every request passes through: middleware.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
request_id.py: a request id on every response
Make an app with a middleware that puts an X-Request-ID header on every response. If the request sent an X-Request-ID of 8 to 64 letters, digits and hyphens, use it as it is; otherwise make a new one with uuid.uuid4().hex. One route: GET /parcels/{awb} answers {"awb": ..., "status": ..., "request_id": ...} for an AWB in /workspace/data/parcels.json, with the same id as the header, and 404 for an unknown AWB.
The check sends good and bad ids, and asks for an unknown AWB and a path no route has: every response needs the header.
- Task 2
access_log.py: a JSON access log
The starter's routes are done. Add a middleware that logs one line per request to the logger named dakiyago.access at level INFO, whose message is a JSON object with method, path (without the query string), status (what the client got) and duration_ms (milliseconds, a number). A request whose route crashes (GET /boom) is logged with status 500 and still answers 500. The API key, sent in an X-Api-Key header or the query string, never appears in a line.
Set the logger's level to INFO and give it a handler that prints the message. The check makes five requests, including GET /slow (0.2 seconds) and GET /boom, and reads every line.
- Task 3
cors.py: CORS for the merchant dashboard
The starter's routes are done. Add CORS so that only https://dashboard.dakiyago.in may call the API from a browser, with only the methods GET and POST and only the headers X-Api-Key and Content-Type, and the browser may keep a preflight's answer for 3600 seconds.
The check sends preflights from the dashboard and from https://evil.example, for POST and DELETE, and ordinary requests with an Origin header.
- Task 4 · interview question
Interview: cors_auth.py, is CORS a security feature?
Make an app with CORS as in task 3 and one route: POST /pickups needs an X-Api-Key header holding a merchant's api_key from /workspace/data/merchants.json, answering 201 {"pickup": "booked", "merchant_id": ...} with one and 401 without a good one, from any caller: curl with no Origin, the dashboard, or another origin. The browser's preflight, which never carries the key, still passes, and a 401 to the dashboard still carries Access-Control-Allow-Origin so the dashboard's code can read it.
The interviewer will ask: is CORS a security feature? Whom does it protect, and from what?
What you will learn
- Middleware: code around every request, and the order it runs in.
- Request ids: one id per request, on the response and in the logs.
- Structured logs: one JSON line per request, with its timing.
- CORS: what a browser asks before a page reads your API, and what it does not protect.
More in Production
Build "Middleware and logging" yourself
DakiyaGo, a Jaipur courier startup, takes bookings on WhatsApp. Merchants want an API, and you build it. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of APIs with FastAPI are free. This one comes with the all labs plan.