Free Python developer course
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Decorators, middleware and error handling: how Flask and FastAPI work.
Where should a rule live if it applies to every route?
Middleware wraps route dispatch. It may inspect the request first and shape the response afterwards, while handlers can focus on the route's work.
A request enters with no trace identifier
Middleware sets an ID before calling the router
The same ID can appear in the response and logs
A request enters with no trace identifier
Middleware sets an ID before calling the router
The same ID can appear in the response and logs
Given A request enters with no trace identifier and The same ID can appear in the response and logs, write down the missing step that connects them.
Middleware sets an ID before calling the router
Now take Middleware sets an ID before calling the router and the result above. Write an input and an implementation that could produce this trace.
A request enters with no trace identifier. Check that your implementation produces the result shown above.
Where would you add timing for successful responses and handler failures?
Time the downstream call in middleware and record elapsed time when it finishes or raises. This applies the same measurement across routes.
Check this when debugging. Thinking decorators change how a function works internally (they replace or register it).
FastAPI, Flask and Express are the tools you'll actually ship with. They can look like magic: you write a function, add one line above it, and it answers web requests, with typed parameters and automatic error pages. This lesson builds that magic from parts you already have. After that, a framework's docs read as a menu of features you understand, and its errors become clues instead of mysteries.
routes = {}
def route(path):
def register(fn):
routes[path] = fn
return fn
return register
@route("/hello")
def hello():
return "hi"
print(routes["/hello"]())hi
@route("/hello") stores the function in the routes table under its path, then hands it back unchanged. Looking up the path and calling it returns hi. That's the heart of how @app.get works.
This rests on Closures and decorators, where a decorator took a function and handed back a function, and on Build an API server from scratch, where a router chose a handler. A framework is those two ideas with conveniences. A decorator such as @app.get("/campaigns") records your function in the route table, and gives it back unchanged. Middleware goes the other way: it wraps the whole app, so jobs every route needs, like logging, timing, checking a key and catching crashes, live in one place. A middleware receives the request and a call_next function that means "pass it further in". It can work before, after, or both, and it can answer by itself without calling call_next, as a guard does when your badge is wrong.
Layers nest like an onion. A request goes in through each layer, reaches the handler, and the response comes back out through the same layers, so the first layer added is the outermost and sees every request and every response, including the ones an inner layer turned away. The picture runs one app with logging outside authentication, with a good key and a bad one.
Logging is outside auth, so it records the rejected request too.
Write a sentence or two, then compare it with a good answer in the lesson.
Think of gift wrap. The present inside stays the same, but what you hand over now has something around it. A decorator does that to a function. It takes a function and returns a function, usually the same one with something wrapped around it.
The @ line is shorthand. @timed above def report() means report = timed(report).
In plain words: a decorator is a function that receives your function, and decides what the name should point to from now on.
Here, timed wraps a function so that it reports how long each call took. *args, **kwargs means "accept whatever arguments you're given and pass them along":
import functools, time def timed(fn): @functools.wraps(fn) # keep fn's name and docstring on the wrapper def wrapper(*args, **kwargs): start = time.perf_counter() result = fn(*args, **kwargs) print(f"{fn.__name__} took {(time.perf_counter() - start) * 1000:.2f} ms") return result return wrapper @timed def total(prices): return sum(prices) print(total([4, 9, 12]))
@app.get("/campaigns") has an argument, so it needs one more layer. app.get("/campaigns") runs first, and returns the real decorator.
A framework's route decorators usually don't wrap the function at all. Picture adding a name to a staff directory: the person doesn't change, but now people can find them. The decorator records the function in the route table, and hands it back unchanged:
ROUTES = {}
def get(path): # called with the path...
def register(fn): # ...returns the decorator, called with the function
ROUTES[("GET", path)] = fn
return fn
return register
@get("/health")
def health():
return {"ok": True}
print(ROUTES)
print(ROUTES[("GET", "/health")]())
def match(pattern, path): params = {} for want, got in zip(pattern.split("/"), path.split("/")): if want.startswith("{"): params[want[1:-1]] = got elif want != got: return None return params print( match("/campaigns/{id}/pause", "/campaigns/cmp_1/pause"), match("/campaigns/{id}", "/orders/7"), )
{'id': 'cmp_1'} None
The fixed segments have to be equal, and the placeholder takes whatever sits in its position. The second path starts with orders, not campaigns, so it doesn't match. A framework keeps a table of patterns like these, and the decorator in this lesson is a tidy way to add a row to it.
@cache above def price(sku): do, in plain Python terms?It runs price = cache(price) right after the function is defined
A decorator line is shorthand for passing the new function to the decorator and keeping what it returns under the same name.
Write a decorator counted(fn): it returns a wrapper that calls fn with the same arguments and returns its result, and keeps a count of calls in wrapper.calls, starting at 0. Use functools.wraps so the wrapper keeps fn's name.
import functools def counted(fn): return fn @counted def price(sku, qty=1): return {"TENT-2P": 189}[sku] * qty print(price("TENT-2P"), price("TENT-2P", qty=2), price.calls, price.__name__)
Picture a clerk handed a form with labeled boxes. The labels say what goes where, and what kind of answer each box wants. FastAPI treats your function the same way. You write a handler like this:
@app.get("/campaigns/{campaign_id}") def get_campaign(campaign_id: int, include_stats: bool = False): ...
How does it know that campaign_id comes from the path and include_stats from the query string, and that "42" should become the number 42? It reads the labels. A function's signature is its list of parameter names, type hints and defaults, and Python's inspect module can read it, using the same type hints you met in Phase 7:
import inspect def get_campaign(campaign_id: int, include_stats: bool = False): return campaign_id, include_stats sig = inspect.signature(get_campaign) for name, param in sig.parameters.items(): default = None if param.default is inspect.Parameter.empty else param.default print(name, "->", param.annotation.__name__, "default:", default) raw = {"campaign_id": "42"} # everything in a URL arrives as text kwargs = {name: sig.parameters[name].annotation(value) for name, value in raw.items()} print(get_campaign(**kwargs))
Everything in a URL arrives as text, so the type hint is used to convert it. int is itself a function, and int("42") gives 42. If conversion fails, the framework answers 422 Unprocessable Content with a message naming the parameter, before your code runs.
The same signature also drives the automatic API docs in APIs with FastAPI. So one function definition does routing, conversion, checking and documentation.
import inspect def list_campaigns(status: str = "active", limit: int = 20): pass print(list(inspect.signature(list_campaigns).parameters))
['status', 'limit']
inspect.signature exposes each parameter's name, type hint and default, so the list of names is ['status', 'limit']. That's how a framework maps ?limit=5 to the limit argument.
Everything in a URL arrives as text. Here's the step a framework runs before your handler: read the handler's signature, convert each value by its type hint, and answer 422 with every problem if anything doesn't convert.
import inspect def get_campaign(campaign_id: int, include_stats: bool = False): return {"id": campaign_id, "stats": include_stats} def to_bool(text): if text in ("true", "1"): return True if text in ("false", "0"): return False raise ValueError(f"not a boolean: {text!r}") CONVERT = {int: int, bool: to_bool, str: str} def call_with_text(handler, raw): """Convert text by the handler's type hints and call it, as a framework does.""" sig = inspect.signature(handler) kwargs, problems = {}, [] for name, text in raw.items(): param = sig.parameters.get(name) if param is None: problems.append(f"{name}: unexpected") continue try: kwargs[name] = CONVERT[param.annotation](text) except ValueError: problems.append(f"{name}: must be {param.annotation.__name__}") if problems: return 422, {"errors": problems} return 200, handler(**kwargs) print(call_with_text(get_campaign, {"campaign_id": "42"})) print(call_with_text(get_campaign, {"campaign_id": "42", "include_stats": "true"})) print( call_with_text(get_campaign, {"campaign_id": "forty-two", "include_stats": "yes"}) )
The handler's signature says campaign_id is an int and include_stats a bool, so call_with_text converts each value with the matching function before calling it.
Two details are worth seeing. bool("false") is True in Python, because any non-empty string is truthy, so a boolean needs its own converter that reads "true" and "false"; frameworks do the same. And the bad request collects every problem before answering 422, so the client can fix both in one go. The handler never runs on bad input: it only ever sees an int and a bool.
Picture an office building. Everyone passes the same guard at the door and signs the same visitor book, whichever office they're going to. You wouldn't hire a separate guard for each room.
Some jobs in an API are like that. Logging, timing, checking an API key, adding headers and catching crashes apply to every request. Copying them into every handler is the duplication you learned to avoid. Middleware wraps the whole app instead.
A middleware is a function that receives the request and a call_next function, which means "pass it further in". It can work before passing the request on, after the response comes back, or both. It can even answer by itself without calling call_next, as a guard does when your badge is wrong.
Several middlewares stack like the layers of an onion. A request goes in through each layer, reaches the handler, and the response comes back out through the same layers. The first one added is the outermost.
def handler(request): print(" handler runs") return {"status": 200, "body": "ok"} def logging_mw(request, call_next): print(f"log: {request['path']} starting") response = call_next(request) print(f"log: {request['path']} -> {response['status']}") return response def auth_mw(request, call_next): print(" auth: checking key") if request.get("key") != "secret": # answer early; handler never runs return {"status": 401, "body": "bad key"} return call_next(request) def build(handler, middlewares): app = handler for mw in reversed(middlewares): # wrap from the inside out app = (lambda mw, inner: lambda req: mw(req, inner))(mw, app) return app app = build(handler, [logging_mw, auth_mw]) print(app({"path": "/report", "key": "secret"})) print(app({"path": "/report", "key": "wrong"}))
Order matters. Put logging outside auth and you log rejected requests too. Put it inside and you only log the ones that got through.
Timing starts, auth rejects with 401 without calling the handler, and timing records the 401
The first middleware is the outermost layer, so it sees every request and every response, including early rejections.
Nothing: they never reach the logging layer
Requests pass through the outer layer first. Rejected at authentication, they never get as far as the logging inside it, so the attack leaves no trace.
Two kinds of failure reach the framework. Think of a restaurant: "we're out of the fish" is a normal thing to tell a customer, while a fire in the kitchen is not, and you don't describe the fire to them.
HTTPException(404, ...) in FastAPI, abort(404) in Flask. The framework turns it into a response with that status and a JSON error body.So you can write handlers for the normal case, and raise for the expected problems.
Write the error-handling middleware errors(request, call_next): return call_next(request) when it works. If it raises HTTPError, return {"status": e.status, "body": {"error": e.message}}. Any other exception becomes {"status": 500, "body": {"error": "Internal server error"}}, never the exception's own text, which can leak details.
class HTTPError(Exception): def __init__(self, status, message): super().__init__(message) self.status, self.message = status, message def errors(request, call_next): return call_next(request) def handler(request): if request["path"] == "/missing": raise HTTPError(404, "No such campaign") return {"status": 200, "body": {"ok": True}} print(errors({"path": "/missing"}, handler))
Write a sentence or two, then compare it with a good answer in the lesson.
FastAPI is built on the same ideas, and its middleware is the call_next function you just wrote, made async. In a service that calls a model the layers earn their keep: a request id goes on every reply and into every log line, timing shows how long the model call took, and an error layer turns a model API's failure into your own clean 502. The cell adds one middleware that reuses a request id from upstream or makes one, and logs one line per request.
Reuse the request id from upstream, or make one, add it to the reply and write one record per request.
import asyncio import time import uuid import httpx from fastapi import FastAPI, Request api = FastAPI() LOG = [] @api.middleware("http") async def stamp(request: Request, call_next): rid = request.headers.get("x-request-id") or uuid.uuid4().hex[:8] start = time.perf_counter() response = await call_next(request) slow = (time.perf_counter() - start) > 1.0 response.headers["X-Request-Id"] = rid path, status = request.url.path, response.status_code LOG.append({"id": rid, "path": path, "status": status, "slow": slow}) return response @api.get("/ping") def ping(): return {"ok": True} async def main(): transport = httpx.ASGITransport(app=api) async with httpx.AsyncClient(transport=transport, base_url="http://t") as c: r = await c.get("/ping", headers={"x-request-id": "edge-7f3a"}) print(r.status_code, r.headers["x-request-id"]) r = await c.get("/missing") print(r.status_code, len(r.headers["x-request-id"])) print(LOG[0], len(LOG)) asyncio.run(main())
The first request brought its own id, edge-7f3a, which the middleware kept, so the trail continues across services. The second had none, so a new 8-character id was made, and even the 404 the router answered passed through the layer.
The same layer is where a model call is timed: wrap the call, record its duration and token counts in the log line, and the slow ones show up in one search. FastAPI's other tool for shared work is Depends, which APIs with FastAPI introduced: use a dependency for something a route asks for, such as the current user, and middleware for something every request gets, such as the id.
| framework | style | notes |
|---|---|---|
| FastAPI | ASGI, async | type hints drive conversion, validation and docs; the common choice for new Python APIs |
| Flask | WSGI | small and flexible; decorators and an app object, very much like this lesson |
| Django | WSGI or ASGI | "batteries included": database layer, admin pages, auth, templates |
| Express | Node.js | the JavaScript equivalent of Flask, built around middleware |
Middleware order is where the quiet bugs live. Logging inside auth means a stranger's 50 bad passwords leave no trace. Rate limiting outside auth means you can't limit per user, only per address. A missing error layer means one unexpected exception sends a traceback to the client. Each is a one-line change in the order of the list, so it is worth reading the order in every code review. Goes deeper in: Running APIs in production adds CORS and request ids to this layer, Project: a FastAPI service with accounts builds a service with dependencies, and Metrics, dashboards and alert rules follows one id across services.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
Why does @app.get("/path") need a function that returns a function?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write