Skip to content
Index Ai Academy
Phase 8 · Building APIs

A web framework, from the inside

Decorators, middleware and error handling: how Flask and FastAPI work.

About 40 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers8

First principles

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.

  1. Starting point

    A request enters with no trace identifier

  2. What changes

    Middleware sets an ID before calling the router

  3. Result

    The same ID can appear in the response and logs

Compare all three steps
  1. Starting point

    A request enters with no trace identifier

  2. What changes

    Middleware sets an ID before calling the router

  3. Result

    The same ID can appear in the response and logs

Complete and reverse the trace

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.

Compare with the worked step

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.

Check one starting point

A request enters with no trace identifier. Check that your implementation produces the result shown above.

Try it on a new case

Where would you add timing for successful responses and handler failures?

Show worked reasoning

Time the downstream call in middleware and record elapsed time when it finishes or raises. This applies the same measurement across routes.

Run, change, and build

Check this when debugging. Thinking decorators change how a function works internally (they replace or register it).

Trace the cause · HTTP request, job, and result
  1. Identify the request, response, and any durable state. Predict the status or stored result before following the trace.
  2. Change one request property and keep the client contract visible. Compare the response and job state to explain the observed behavior.
  3. Try the same reasoning on this case. Where would you add timing for successful responses and handler failures?

Why it matters

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.

What you'll be able to do

  • Write decorators, including ones that take arguments like @app.get("/path")
  • Read a handler's signature to pass in path values, converting them by their type hints
  • Wrap an app in middleware for logging, timing and other cross-cutting work
  • Turn every error into a clean JSON response without leaking internals
  • Add a request id and timing in FastAPI middleware
Quick check
Frameworks register routes with decorators. A guess: what does this print?
routes = {}

def route(path):
    def register(fn):
        routes[path] = fn
        return fn
    return register

@route("/hello")
def hello():
    return "hi"

print(routes["/hello"]())
  1. /hello
  2. hi
  3. hello
  4. An error: route returns nothing
Show the answer

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.

The idea: layers around one function

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.

Try it now

Logging is outside auth, so it records the rejected request too.

In your own words
What does middleware do that a decorator doesn't, and why does the order of layers matter?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: decorators, signatures and middleware

Decorators, again

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]))
It runs right here in your browser, with nothing to install.

@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")]())
Quick check
From the lesson on building a server: a placeholder such as {id} captures one segment of the path. What does this print?
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"),
)
  1. {'id': 'cmp_1'} {'id': '7'}
  2. None None
  3. {'id': 'pause'} None
  4. {'id': 'cmp_1'} None
Show the answer

{'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.

Quick check
What does @cache above def price(sku): do, in plain Python terms?
  1. It calls cache every time price runs, inside price's body
  2. It only works inside classes
  3. It renames price to cache
  4. It runs price = cache(price) right after the function is defined
Show the answer

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.

Drill

A decorator that counts

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__)
In the lesson, your code is checked as you write it.

Parameters from the signature

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.

Quick check
Frameworks read parameter names from the handler's signature. What does this print?
import inspect

def list_campaigns(status: str = "active", limit: int = 20):
    pass

print(list(inspect.signature(list_campaigns).parameters))
  1. ['str', 'int']
  2. ['status', 'limit']
  3. []
  4. ['active', 20]
Show the answer

['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.

Worked example

Worked example: from URL text to a typed call

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"})
)
In the lesson you can change this and run it.

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.

Middleware you can step through

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.

Quick check
Middlewares are added in the order [timing, auth]. A request with a bad key arrives. What happens?
  1. The handler runs first, and auth checks the key afterward, before the response is sent
  2. Timing starts, auth rejects with 401 without calling the handler, and timing records the 401
  3. The request is timed only if it succeeds, so the 401 isn't recorded
  4. Auth runs before timing, since checks always run before anything else
Show the answer

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.

Quick check
The logging middleware sits inside the authentication middleware. A stranger tries 50 bad passwords. What do the logs show?
  1. Only the last attempt, with its error
  2. Nothing: they never reach the logging layer
  3. All 50 attempts, one line each
  4. Each attempt twice, once per layer
Show the answer

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.

Errors become responses

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.

  1. Expected errors are the ones your code raises on purpose, like "campaign not found". Frameworks give you an exception for this: HTTPException(404, ...) in FastAPI, abort(404) in Flask. The framework turns it into a response with that status and a JSON error body.
  2. Unexpected errors are bugs, or a crashed database. These become 500 Internal Server Error with a generic message. Log the full traceback on the server, but never send it to the client. Tracebacks reveal file paths, library versions and sometimes secrets, which is a gift to attackers.

So you can write handlers for the normal case, and raise for the expected problems.

Drill

Turn errors into responses

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))
In the lesson, your code is checked as you write it.
In your own words
What should a client see when a handler raises, and where do the details go?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML systems: the same layers in FastAPI

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.

Worked example

A request id and a log line in FastAPI middleware

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())
In the lesson you can change this and run it.

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.

The frameworks you'll meet

frameworkstylenotes
FastAPIASGI, asynctype hints drive conversion, validation and docs; the common choice for new Python APIs
FlaskWSGIsmall and flexible; decorators and an app object, very much like this lesson
DjangoWSGI or ASGI"batteries included": database layer, admin pages, auth, templates
ExpressNode.jsthe JavaScript equivalent of Flask, built around middleware

Where this shows up in an engineer's week

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.

In your own words
Why does the order of middleware change what your logs show?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 7 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

Why does @app.get("/path") need a function that returns a function?

  1. app.get("/path") runs first and must return the decorator that then receives the handler
  2. Because Python doesn't allow decorators without arguments, so each one has to be called at least once
  3. To make the handler run twice: once when it's defined, to check it, and once for each request
  4. It doesn't: that's a FastAPI-only feature, and any other function can be used directly as a decorator

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 8 · about 23 hours of study

APIs

Design, build, secure and scale web APIs from first principles 27 lessons 1 free
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
  22. A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
  27. Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Part of a free course 127 lessons

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.

Part of a free course 20 lessons

Build and Operate HTTP APIs

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