FastAPI & Python Web Frameworks

How routing and middleware look in Python, using FastAPI, a modern async, type-driven framework.

What is it?

Routing, middleware, and the request/response lifecycle aren't specific to Node.js or Express. They're how backend frameworks work in general. In Python, Flask and Django are the older, synchronous-first options. FastAPI is a newer framework built around type hints and async/await.

FastAPI's key feature: ordinary type hints do double duty. A Pydantic model describing a request body validates incoming data (rejecting mismatches with a clear error) and generates interactive API docs. You don't write either by hand.

Explain like I'm 10

It's the same directory board from routing, installed in a different building. The idea (map a method and path to a function) is identical. Only the syntax and a few conveniences differ.

Examples

A route with a path parameter and a request body

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.get("/items/{item_id}")
async def get_item(item_id: int):
    return {"item_id": item_id}

@app.post("/items")
async def create_item(item: Item):
    return {"created": item.name, "price": item.price}

Declaring item_id: int makes FastAPI convert and validate it. The Item Pydantic model does the same for the whole body, rejecting requests missing name or price with a 422 error before your function runs.

Dependencies — FastAPI's take on shared, cross-cutting logic

from fastapi import Depends, FastAPI, HTTPException

app = FastAPI()

def get_current_user(token: str):
    if token != "valid-token":
        raise HTTPException(status_code=401, detail="Invalid token")
    return {"user": "alice"}

@app.get("/profile")
async def profile(user: dict = Depends(get_current_user)):
    return user

Depends() is FastAPI's answer to Express middleware for things like auth checks. Instead of running before the handler in a chain, it's declared as a parameter the handler needs, and FastAPI resolves it before calling the route.

Real middleware — running for every request, unconditionally

import time
from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def add_timing_header(request: Request, call_next):
    start = time.time()
    response = await call_next(request)
    duration = time.time() - start
    response.headers["X-Process-Time"] = str(duration)
    return response

This is FastAPI's real middleware, closer to Express's (req, res, next) chain than Depends() is. It runs for every request, whichever route matches. call_next(request) works like next() in Express: it passes control on and lets you act again once the response comes back.

How it works

FastAPI is built on Starlette for the async web layer (an ASGI application, run by a server like Uvicorn) and Pydantic for data validation.

When a request arrives, FastAPI matches the path to a decorated function. It uses the function's type hints and Pydantic models to validate and parse path parameters, query strings, and the body before calling your function. Then it serializes whatever you return to JSON. The same type hints generate an OpenAPI schema, which powers the interactive docs at /docs.

Why does it exist?

Flask and Django predate widespread async support in Python, and you write validation by hand. FastAPI brings Node-style non-blocking I/O to Python. It uses type hints, which Python developers already write, to remove most of the boilerplate for validating requests and documenting an API.

When to use it

FastAPI is a strong choice for teams already using Python (common alongside data or ML work) that want async performance, strict request validation, and free interactive API docs without extra tooling.

When not to use it

If the team and its libraries are committed to Node, or the app is a simple, mostly synchronous CRUD site where Flask or Django's simpler, batteries-included conventions are enough, FastAPI's async model and Pydantic layer add needless complexity.

Common mistakes

  • Calling a blocking library (like an old synchronous database driver) inside an async def route instead of awaiting an async-compatible alternative. It stalls the whole event loop for every other concurrent request.

  • Skipping Pydantic models and accepting a raw, untyped body, which loses both automatic validation and the generated docs.

  • Treating Depends() as identical to Express middleware. It's closer to an injectable parameter the handler asks for than a step that always runs before the handler in a fixed chain.

Practice exercises

  1. Easy:

    Write the FastAPI equivalent of an Express route: GET /ping returning {"status": "ok"}.

  2. Medium:

    Define a Pydantic model CreateUser with a name (str) and age (int), and a POST /users route that accepts it and returns the values.

  3. Hard:

    Explain why a blocking, synchronous database call inside an async def route can slow down every other concurrent request in FastAPI, not just the one making the call.

Interview questions

What is FastAPI built on?

Starlette (an ASGI framework) for the async web layer, and Pydantic for data validation and serialization.

How does FastAPI generate interactive API documentation automatically?

It builds an OpenAPI schema from the same type hints and Pydantic models it uses for validation, and serves an interactive UI from that schema at /docs.

What's the risk of a blocking call inside an async route handler?

It holds the single event loop thread and delays every other concurrent request, just as a CPU-heavy synchronous operation blocks Node.js.

What's the difference between Flask/Django and FastAPI in terms of built-in async support?

Flask and Django came before async/await was standard in Python and are synchronous-first. FastAPI was built around ASGI and async/await from the start, so async request handling is native, not an add-on.

What is ASGI, and how does it differ from WSGI, which Flask and Django traditionally use?

WSGI is a synchronous interface between Python web apps and servers, handling one request at a time per worker. ASGI adds async/await and long-lived connections like WebSockets, so one worker can handle many concurrent requests without blocking on I/O.

What does declaring a path parameter as `item_id: int` actually cause FastAPI to do, beyond documentation?

FastAPI converts the incoming string segment to a Python int before calling the route, and returns a 422 error if it can't. The type hint is enforced, not just a comment.

What is a Pydantic model, and what two things does defining one for a request body give you at once?

A Python class declaring expected fields and types. As a request body parameter, it validates and parses incoming JSON against that shape (rejecting mismatches with a 422), and the same declaration feeds the generated OpenAPI docs.

What's the difference between `Depends()` and Express-style middleware, conceptually?

Express middleware runs in a fixed chain before every matching route, whatever that route needs. Depends() is a parameter a specific route asks for, and FastAPI resolves only the dependencies that route declares. It's closer to dependency injection than a universal pipeline stage.

How does FastAPI's real `@app.middleware("http")` differ from `Depends()`?

It runs for every request regardless of route, and wraps the next stage via call_next(request), so it can act before and after the response. That's much closer to Express's (req, res, next) chain. Depends() only applies to routes that declare it.

What does declaring a route function `async def` do if the code inside never actually uses `await`?

Nothing useful by itself. It doesn't make the route non-blocking. Any synchronous, blocking work inside still ties up the event loop as if it weren't async.

Why can a single blocking, non-async database call inside an `async def` route stall other, unrelated concurrent requests in FastAPI?

Each worker runs one event loop that switches between requests only at await points. A blocking call has no await point and runs to completion on that thread, so the loop can't serve any other request until it finishes.

What's one way to run a genuinely blocking library inside a FastAPI route without stalling the event loop?

Run it in a thread pool with something like run_in_threadpool or asyncio.to_thread. The blocking call runs off the event loop thread, and the route awaits its result without freezing other requests.

What HTTP status code does FastAPI return by default when a request body fails Pydantic validation, and why that code specifically?

422 Unprocessable Entity. The request is valid HTTP/JSON (so not a malformed 400), but its content breaks the endpoint's rules, which is exactly what 422 means.

How would you raise a custom error response, like a 404, from inside a FastAPI route function?

Raise HTTPException(status_code=404, detail="..."). FastAPI catches this exception type and turns it into the matching HTTP response, with no central middleware needed.

Why might a dependency declared with `Depends()` be reused across multiple different routes?

It's a regular Python callable, so one function like get_current_user can be declared by any number of routes without duplicating it. FastAPI resolves it separately for each route that asks for it.

What's a benefit of typing a query parameter, e.g. `q: str | None = None`, rather than manually reading `request.query_params`?

FastAPI parses, validates, and converts it by type, applies the default when it's missing, and includes it in the docs. Reading request.query_params means writing that conversion, default handling, and validation yourself.

What's the relationship between a FastAPI `APIRouter` and the main `app`, when a project splits routes into separate files?

An APIRouter defines a group of related routes in a separate module, which you attach to the main app with app.include_router(...). It's like mounting a sub-router in Express, and keeps every route out of the main app file.

Why might a team choose Flask or Django over FastAPI for a simple, mostly synchronous CRUD app?

Their simpler, batteries-included, synchronous conventions are enough. FastAPI's async model and Pydantic validation layer would add complexity with no matching benefit if the app never needs high concurrency or that kind of request validation.