Skip to content

FastAPI Fundamentals: ASGI, Routes, Path & Query Parameters, Status Codes, OpenAPI Docs ​

"When you declare a path operation function with normal def instead of async def, it is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server)." — FastAPI documentation, "Concurrency and async / await", fastapi.tiangolo.com/async

Summary: FastAPI is a Starlette application (an ASGI app) that turns ordinary type-annotated Python functions into HTTP endpoints: the decorator (@app.get, @app.post …) registers a path operation, the function signature declares path and query parameters, Pydantic converts and validates them (or answers 422), the return value is filtered by the response model and sent with the decorator's status_code, and the same route table produces the OpenAPI schema behind /docs and /redoc. Uvicorn is the server that owns the socket and the event loop and calls the app. Focus: ASGI (scope, receive, send), Starlette and Uvicorn, FastAPI() and its parameters, path operations and HTTP methods, route order, path parameters and type conversion, Enum path params, query parameters (required, Optional, default values, lists), Annotated with Query() and Path(), validation errors (422, RequestValidationError, the detail list), status_code and the status module, response_model and the JSON response, HTTPException and 404, 405 and Allow, async def vs def and the thread pool, StaticFiles and mounts, OpenAPI 3.1, Swagger UI and ReDoc, operation metadata (tags, summary, description, operationId, deprecated, include_in_schema), lifespan, middleware position, uvicorn --reload, workers, Gunicorn with Uvicorn workers, curl, httpx and TestClient, performance, and a first look at project layout. Learning goal: Write a FastAPI service whose every input is typed and validated by its signature, whose every outcome has the right status code, whose blocking calls never freeze the event loop, whose OpenAPI docs are accurate enough to generate a client from, and run it with Uvicorn the right way for development and for production.

This page owns the first contact with FastAPI: the server/framework split, routes, parameters that live in the URL, status codes and the generated docs. It does not re-teach its neighbours: Python's type hints and Pydantic models in depth are in Typing & Pydantic v2; the event loop, await and thread pools as a language topic are in Async Python; request bodies, query/body models, cookies, headers and custom validators are in Request Validation; Depends is in Dependency Injection; APIRouter, prefixes and project structure are in APIRouter & Project Structure; custom exception handlers, Problem Details, StreamingResponse and SSE are in Exceptions & Responses; Uvicorn/Gunicorn tuning, logging and Docker images are in FastAPI in Production; fixtures and dependency overrides are in Testing FastAPI. The ORM layer (SQLAlchemy 2, SQLModel, Alembic) starts in SQLAlchemy 2 & SQLModel. Resource and status-code design is in REST API Design, the protocol in HTTP Evolution, and the Go twin of this chapter is net/http: Server, Client, 1.22 Routing.

Facts below were checked against the FastAPI documentation (tutorial, advanced guide, reference for FastAPI and status, release notes up to 0.165.0 of 2026-11-18), the ASGI specification 3.0, the Starlette docs and release notes (1.10.0), the Uvicorn settings and deployment pages, the uvicorn-worker README, the OpenAPI 3.1.0 specification, the ReDoc docs, RFC 9110 and the Pydantic validation-error reference. The page is written for Python 3.12+ and current FastAPI. The snippets, however, were run on the only interpreter on the build machine, CPython 3.9.6, so the snippet project pins the newest releases that still install there: FastAPI 0.128.8 (0.129.0 dropped Python 3.9), Starlette 0.49.3, Pydantic 2.13.5, Uvicorn 0.39.0, httpx 0.28.1, pytest 8.4.2, plus eval-type-backport so Pydantic can evaluate str | None on 3.9; all of them are pinned in the snippet's pyproject.toml, and the full resolved set of the verified install is in the saved requirements.lock. Every status code, error body, timing and log line quoted as "real" below is what that run printed. Features newer than 0.128.8 (Rust-side JSON serialisation in 0.130.0, strict_content_type in 0.132.0, max_body_size in 0.164.0) are described from the release notes and marked as such.

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why a typed framework on top of ASGIWhy it exists
Versions: ASGI 3.0 to FastAPI 0.165Where it comes from
A before/after servicePython
ASGI, Starlette, Uvicorn: who does whatASGI, Starlette and Uvicorn
FastAPI() parametersThe application object
@app.get, @app.post, HTTP methodsPath operations and decorators
Which route wins, 404 vs 405Route order
/{item_id}, int conversion, :pathPath parameters
Fixed values in the URLEnum path params
?skip=0&limit=10, required vs optionalQuery parameters
Annotated[int, Query(le=100)]Annotated, Query() and Path()
422, detail, loc, msg, typeValidation errors
201, 204, status.HTTP_404_NOT_FOUNDstatus_code and the status module
Filtering output, JSON serialisationJSON response and response_model
raise HTTPException(404)HTTPException and 404
async def or def?async def vs def routes
/static/logo.pngStatic files
/docs, /redoc, /openapi.jsonOpenAPI, Swagger UI, ReDoc
tags, summary, operationId, deprecatedOperation metadata
Open a pool at startup, close at shutdownLifespan
Where middleware sitsMiddleware position
uvicorn --reload, --workers, GunicornRunning it
curl, httpx, TestClientCalling and testing
Performance (pydantic-core, orjson, async I/O)Performance
main.py today, packages tomorrowProject layout preview
Request lifecycle step by step, exact error textsMechanics
The common bugs and their fixesSolving the classic problems
FastAPI vs Django, Flask, GoChoosing
Monolith to distributed systemIn architecture
Reproduce it on your machineLab
Laravel routes and abort(404)For PHP/Laravel developers
The same API in Go net/httpThe Go angle

Everything in one minute ​

The stack in one table. Each row is unpacked in the concept catalogue.

PieceWhat it isPlain wordsWhere it lives
ASGIInterface: async app(scope, receive, send)"The plug between server and framework"asgi.readthedocs.io, spec 3.0
UvicornASGI server"Owns the socket, parses HTTP, runs the event loop"uvicorn package
StarletteASGI toolkit: routing, requests, responses, middleware, StaticFiles, TestClient"The web layer FastAPI inherits"starlette package
FastAPIclass FastAPI(Starlette) + parameter extraction, validation, OpenAPI"Type hints become an API"fastapi package
PydanticValidation and serialisation (core written in Rust: pydantic-core)"Checks and converts every value"pydantic package
Path operationPath + HTTP method + function"One endpoint"@app.get("/items/{id}")
OpenAPIMachine-readable description of the API"The contract /docs renders"/openapi.json
Swagger UI / ReDocTwo HTML renderers of that schema"Try it out" / "read it"/docs / /redoc
LifespanAsync context manager around the app's life"Startup before yield, shutdown after"FastAPI(lifespan=...)

Where a parameter comes from. FastAPI decides from the signature; order of the arguments does not matter.

DeclarationRead fromRequired?Example requestValue in the function
item_id: int and {item_id} in the pathPathAlways/items/4242 (int)
q: str (not in the path)QueryYes/items?q=x"x"
skip: int = 0QueryNo, default/items0
q: str | None = NoneQueryNo/itemsNone
short: bool = FalseQueryNo?short=yesTrue
tag: Annotated[list[str] | None, Query()] = NoneQuery, repeatedNo?tag=a&tag=b["a", "b"]
model: ModelName (an Enum)PathAlways/models/alexnetModelName.alexnet
body: ProductIn (a Pydantic model)JSON bodyYesPOST with JSONProductIn(...)
request: RequestThe raw Starlette requestn/aanyRequest object

What the client gets back. All of these were produced by the snippet app in the Lab.

SituationStatusBodyProduced by
Normal return200 (or the decorator's status_code)JSON of the return valuepath operation
status_code=201 on @app.post201Created resourcedecorator
status_code=204204emptydecorator
No route matches the path404{"detail": "Not Found"}Starlette router
Path matches, method does not405{"detail": "Method Not Allowed"} + AllowStarlette router
Parameter or body invalid422{"detail": [{"type", "loc", "msg", "input", "ctx"}]}RequestValidationError
raise HTTPException(404, "Product not found")404{"detail": "Product not found"}your code
Unhandled exception500Internal Server Error (plain text)ServerErrorMiddleware
/products/ when only /products exists307redirect to /productsredirect_slashes=True

The URLs every FastAPI app has by default.

URLWhatTurn off with
/openapi.jsonOpenAPI 3.1.0 schemaFastAPI(openapi_url=None) (also disables both UIs)
/docsSwagger UIFastAPI(docs_url=None)
/docs/oauth2-redirectSwagger UI OAuth2 helperswagger_ui_oauth2_redirect_url=None
/redocReDocFastAPI(redoc_url=None)

Why it exists ​

A Python web API has always needed two things: a server that speaks HTTP and a framework that maps requests to code. WSGI (PEP 3333) standardised the plug between them for synchronous code: one callable, one request in, one response out. That shape cannot hold a WebSocket open or wait on a thousand slow upstream calls without a thread each. ASGI replaced it with an asynchronous interface ("ASGI is a spiritual successor to WSGI, the long-standing Python standard for compatibility between web servers, frameworks, and applications"), Uvicorn implemented the server side and Starlette the toolkit side. FastAPI adds the part API authors write by hand in every other framework: reading parameters, converting strings to types, validating, producing error responses, serialising the result and documenting all of it. It does that from the function signature, so the code, the validation and the docs cannot drift apart.

Hand-written routing (Flask style, or Starlette alone)FastAPI
request.args.get("limit") returns a string or Nonelimit: int = 10 arrives as an int
Validation code per endpoint, error format per teamPydantic validates; one 422 format everywhere
Docs written separately and outdated after a monthOpenAPI generated from the routes on every start
Response shape is whatever the dict containsresponse_model filters and documents the output
Sync by default; async is an add-onASGI native; async def and def both supported
Errors returned as valuesraise HTTPException(...) from any depth

An everyday picture. A restaurant. Uvicorn is the front door and the host who seats guests and carries plates (the socket, HTTP parsing, keep-alive). The event loop is a single very fast waiter who never stands still: he takes an order, hands it to the kitchen and serves the next table while the dish cooks (await). The menu is the route table; each dish is a path operation, and the printed menu on the wall is the OpenAPI schema, generated from the same recipes the kitchen uses, so it is never out of date. The order form with boxes ("table number: digits only", "spice level: mild, medium, hot") is the function signature: a waiter who gets "table: banana" sends the form back at once with every wrong box circled (422). A cook who has to stand at the stove stirring for ten minutes (a blocking call) must not be the waiter; that job goes to one of the 40 kitchen helpers (the thread pool for def routes). Opening the kitchen before the doors open and cleaning it after closing is the lifespan.

Three common misunderstandings, up front ​

  1. "async def makes a route fast." It makes it non-blocking only if everything inside awaits. A time.sleep, a requests.get or a sync database driver inside async def freezes the event loop for every request (measured: five 200 ms requests took 1.05 s instead of 0.21 s). If the libraries you call are blocking, write def and FastAPI runs the function in the thread pool.
  2. "FastAPI is the server." FastAPI is the application; Uvicorn (or another ASGI server such as Hypercorn or Daphne) is the server. fastapi dev and fastapi run are a CLI that starts Uvicorn for you.
  3. "422 means my code crashed." 422 is FastAPI saying "the request did not match the signature" before your function ran. Your function never saw the bad value. A crash in your code is a 500.

Where it comes from ​

The ASGI specification reached its current single-callable form in version 3.0 ("3.0 (2019-03-04): Changed to single-callable application style"); version 2.0 (2017-11-28) was the "Initial non-channel-layer based ASGI spec". Tom Christie, creator of Django REST Framework, wrote both Uvicorn and Starlette; the FastAPI docs credit him as "The same creator of Starlette and Uvicorn, on which FastAPI is based." FastAPI itself is Sebastián Ramírez's project; the oldest entry on its release-notes page is 0.1.19 (2019-02-01). FastAPI is still on 0.x: every minor version may contain breaking changes, which is why projects pin it.

The milestones that change how you write code today come from the release notes. 0.93.0 (2023-03-07) added lifespan context managers, "superseding startup and shutdown events". 0.95.0 (2023-03-18) "adds support for dependencies and parameters using Annotated and recommends its usage". 0.100.0 (2023-07-07) added Pydantic v2 support, and 0.126.0 (2025-12-20) dropped Pydantic v1. 0.111.0 (2024-05-03) added the fastapi command (fastapi dev, fastapi run). 0.129.0 (2026-02-12) dropped Python 3.9, and 0.162.6 (2026-11-13) dropped Python 3.10, so current FastAPI needs 3.11+. 0.130.0 (2026-02-22) made FastAPI "Serialize JSON response with Pydantic (in Rust), when there's a Pydantic return type or response model", which "results in 2x (or more) performance increase for JSON responses"; 0.131.0 deprecated ORJSONResponse and UJSONResponse as a consequence. 0.132.0 (2026-02-23) made JSON parsing check Content-Type by default (strict_content_type=True). On the Starlette side, 1.0.0 shipped on 22 March 2026 ("After nearly eight years since its creation, Starlette has reached its first stable release") and removed the on_startup/on_shutdown parameters from Starlette's own constructor; FastAPI 0.133.0 added support for Starlette 1.0.

1  2017-11  ASGI 2.0: first non-channel-layer ASGI spec
2  2019-02  FastAPI 0.1.19, the oldest entry on the release-notes page
3  2019-03  ASGI 3.0: single async callable app(scope, receive, send)
4  2023-03  FastAPI 0.93 lifespan=; 0.95 Annotated recommended
5  2023-07  FastAPI 0.100: Pydantic v2 (Rust core: pydantic-core)
6  2024-05  FastAPI 0.111: fastapi dev / fastapi run (fastapi-cli)
7  2025-12  FastAPI 0.125 drops Python 3.8; 0.126 drops Pydantic v1
8  2026-02  0.129 drops 3.9; 0.130 Rust JSON serialisation; 0.131 ORJSONResponse deprecated; 0.132 strict_content_type
9  2026-03  Starlette 1.0.0; FastAPI 0.135 Server-Sent Events
10 2026-11  FastAPI 0.162.6 drops 3.10; 0.164 max_body_size; 0.165 form_limits

Python ​

Before ​

A catalog API that works on a quiet day. Every parameter is read by hand from request.query_params and request.path_params, so nothing is converted, validated or documented; errors are returned as {"error": ...} with status 200; creation answers 200 without a Location; /users/{user_id} is registered before /users/me; a report endpoint calls time.sleep inside async def; startup work sits in the deprecated @app.on_event hook.

py
"""Before: a catalog API that works on a quiet day but fights FastAPI instead of using it.

Design problems (none is a syntax error; every one is a real bug report waiting):
- parameters read by hand from request.query_params / path strings, so no type
  conversion, no validation, no OpenAPI description of the inputs;
- every response is 200, errors included ({"error": ...} with status 200);
- /users/{user_id} is registered before /users/me, so /users/me never matches;
- a blocking time.sleep inside `async def` freezes the event loop for everyone;
- startup work lives in the deprecated @app.on_event hooks.
"""

from __future__ import annotations

import time

from fastapi import FastAPI, Request

app = FastAPI()
PRODUCTS = {1: {"id": 1, "name": "Chess Set", "price_cents": 3000}}
USERS = {"7": {"id": "7", "name": "Ada"}}


@app.on_event("startup")
async def load_products() -> None:  # deprecated: use lifespan=
    PRODUCTS.setdefault(2, {"id": 2, "name": "Go Board", "price_cents": 6500})


@app.get("/products")
async def list_products(request: Request):
    limit = int(request.query_params.get("limit", "10"))  # "abc" -> ValueError -> 500
    return list(PRODUCTS.values())[:limit]


@app.get("/products/{product_id}")
async def get_product(request: Request):
    product_id = request.path_params["product_id"]  # always a str
    product = PRODUCTS.get(int(product_id)) if product_id.isdigit() else None
    if product is None:
        return {"error": "not found"}  # status 200: clients and caches think it worked
    return product


@app.post("/products")
async def create_product(request: Request):
    data = await request.json()  # no schema: any JSON is accepted, a missing name is a KeyError
    new_id = max(PRODUCTS) + 1
    PRODUCTS[new_id] = {"id": new_id, "name": data["name"], "price_cents": data.get("price_cents", 0)}
    return PRODUCTS[new_id]  # 200, not 201, and no Location header


@app.get("/users/{user_id}")
async def get_user(user_id: str):
    return USERS.get(user_id, {"error": "not found"})


@app.get("/users/me")  # unreachable: /users/{user_id} above already matches "me"
async def get_me():
    return {"id": "me"}


@app.get("/report")
async def slow_report():
    time.sleep(0.2)  # blocking call in async def: the whole event loop stops for 200 ms
    return {"rows": 0}

The test pins each bug down: a missing product is a 200, ?limit=abc is a 500 instead of a 422, any JSON shape is accepted, /users/me is answered by the parameter route, and /openapi.json shows no parameters at all.

py
"""Before: each test pins down one design bug of app/before.py."""

from __future__ import annotations

import warnings

from fastapi.testclient import TestClient

with warnings.catch_warnings():
    warnings.simplefilter("ignore", DeprecationWarning)  # on_event is deprecated
    from app.before import app

client = TestClient(app, raise_server_exceptions=False)


def test_missing_product_answers_200_with_an_error_body() -> None:
    r = client.get("/products/999")
    assert r.status_code == 200 and r.json() == {"error": "not found"}


def test_bad_query_value_is_a_500_not_a_422() -> None:
    r = client.get("/products", params={"limit": "abc"})
    assert r.status_code == 500
    assert r.text == "Internal Server Error"  # ServerErrorMiddleware, text/plain


def test_create_answers_200_and_accepts_any_shape() -> None:
    r = client.post("/products", json={"name": "Catan", "colour": "red"})
    assert r.status_code == 200  # should be 201 + Location
    assert client.post("/products", json={"title": "no name"}).status_code == 500  # KeyError


def test_users_me_is_shadowed_by_the_parameter_route() -> None:
    assert client.get("/users/me").json() == {"error": "not found"}


def test_no_input_is_described_in_openapi() -> None:
    op = client.get("/openapi.json").json()["paths"]["/products"]["get"]
    assert "parameters" not in op  # limit is invisible to clients and to /docs

After ​

The same API built with FastAPI instead of against it. The SQL lives in a small SQLite layer (a blocking driver, so the routes that use it are def):

py
"""A tiny SQLite catalog: the SQL each route runs, behind plain functions.

sqlite3 is a blocking driver, so the routes that call these functions are declared
with `def` and FastAPI runs them in its thread pool. The ORM version of this layer
(SQLAlchemy 2 / SQLModel) is the subject of its own chapter.
"""

from __future__ import annotations

import sqlite3
import threading
from typing import Any

SCHEMA = """
CREATE TABLE IF NOT EXISTS products (
    id          INTEGER PRIMARY KEY,
    name        TEXT    NOT NULL,
    category    TEXT    NOT NULL CHECK (category IN ('books', 'games', 'music')),
    price_cents INTEGER NOT NULL CHECK (price_cents >= 0),
    featured    INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS products_category_price ON products (category, price_cents);
"""

SEED = [
    ("The Pragmatic Programmer", "books", 4200, 1),
    ("Designing Data-Intensive Applications", "books", 5500, 1),
    ("Chess Set", "games", 3000, 0),
    ("Go Board", "games", 6500, 0),
    ("Kind of Blue (vinyl)", "music", 2800, 1),
]

# The query behind GET /products: every value is a bound parameter, never string formatting.
LIST_SQL = """
SELECT id, name, category, price_cents
FROM products
WHERE (:category IS NULL OR category = :category)
  AND price_cents <= :max_price
ORDER BY id
LIMIT :limit OFFSET :offset
"""


class Catalog:
    """One shared connection guarded by a lock (sync routes run on several threads)."""

    def __init__(self, path: str = ":memory:") -> None:
        self._conn = sqlite3.connect(path, check_same_thread=False)
        self._conn.row_factory = sqlite3.Row
        self._lock = threading.Lock()
        with self._lock:
            self._conn.executescript(SCHEMA)
            if self._conn.execute("SELECT count(*) FROM products").fetchone()[0] == 0:
                self._conn.executemany(
                    "INSERT INTO products (name, category, price_cents, featured) VALUES (?, ?, ?, ?)",
                    SEED,
                )
                self._conn.commit()

    def list(self, category: str | None, max_price: int, limit: int, offset: int) -> list[dict[str, Any]]:
        params = {"category": category, "max_price": max_price, "limit": limit, "offset": offset}
        with self._lock:
            return [dict(r) for r in self._conn.execute(LIST_SQL, params)]

    def featured(self) -> list[dict[str, Any]]:
        sql = "SELECT id, name, category, price_cents FROM products WHERE featured = 1 ORDER BY id"
        with self._lock:
            return [dict(r) for r in self._conn.execute(sql)]

    def get(self, product_id: int) -> dict[str, Any] | None:
        sql = "SELECT id, name, category, price_cents FROM products WHERE id = ?"
        with self._lock:
            row = self._conn.execute(sql, (product_id,)).fetchone()
        return dict(row) if row else None

    def insert(self, name: str, category: str, price_cents: int) -> dict[str, Any]:
        sql = "INSERT INTO products (name, category, price_cents) VALUES (?, ?, ?)"
        with self._lock:
            cur = self._conn.execute(sql, (name, category, price_cents))
            self._conn.commit()
            new_id = cur.lastrowid
        return {"id": new_id, "name": name, "category": category, "price_cents": price_cents}

    def delete(self, product_id: int) -> bool:
        with self._lock:
            cur = self._conn.execute("DELETE FROM products WHERE id = ?", (product_id,))
            self._conn.commit()
        return cur.rowcount == 1

    def close(self) -> None:
        with self._lock:
            self._conn.close()

The application: an Enum for categories, Pydantic models for input and output, Annotated constraints on path and query parameters, explicit status_code values from the status module, HTTPException for 404, response_model on every read, the fixed path /products/featured declared before /products/{product_id}, tags with descriptions, function names as operationId, a deprecated legacy route, a hidden health check, a timing middleware, a StaticFiles mount and a lifespan that opens and closes the database.

py
"""After: the catalog API with typed routes, explicit status codes and real OpenAPI docs.

Run it:  uvicorn app.main:app --reload        (development, one process)
         fastapi dev                           (same, via fastapi-cli and [tool.fastapi])
Docs:    /docs (Swagger UI), /redoc (ReDoc), /openapi.json (the schema both render)
"""

from __future__ import annotations

import os
import time
from contextlib import asynccontextmanager
from enum import Enum
from pathlib import Path as FsPath
from typing import Annotated, AsyncIterator

from fastapi import FastAPI, HTTPException, Path, Query, Request, Response, status
from fastapi.routing import APIRoute
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field

from app.db import Catalog


class Category(str, Enum):
    """Allowed path/query values. On Python 3.11+ write `class Category(StrEnum)`."""

    books = "books"
    games = "games"
    music = "music"


class ProductIn(BaseModel):
    name: str = Field(min_length=1, max_length=120)
    category: Category
    price_cents: int = Field(ge=0)


class ProductOut(BaseModel):
    id: int
    name: str
    category: Category
    price_cents: int


TAGS = [
    {"name": "products", "description": "Browse and manage the catalog."},
    {"name": "categories", "description": "Fixed product categories (an Enum path parameter)."},
    {"name": "legacy", "description": "Old endpoints kept for existing clients."},
]


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    # Startup: runs once, before the first request is accepted.
    app.state.catalog = Catalog(os.environ.get("CATALOG_DB", ":memory:"))
    yield
    # Shutdown: runs once, after the server stops accepting requests.
    app.state.catalog.close()
    del app.state.catalog


def operation_id_from_name(route: APIRoute) -> str:
    # operationId = function name, so generated clients get `list_products()`, not `list_products_products_get()`.
    return route.name


app = FastAPI(
    title="Catalog API",
    version="1.0.0",
    summary="The pilot app of the FastAPI Fundamentals chapter.",
    openapi_tags=TAGS,
    lifespan=lifespan,
    generate_unique_id_function=operation_id_from_name,
)


@app.middleware("http")
async def process_time(request: Request, call_next):
    # Wraps every request, including 404s, 422s and static files.
    start = time.perf_counter()
    response = await call_next(request)
    response.headers["X-Process-Time-Ms"] = f"{(time.perf_counter() - start) * 1000:.2f}"
    return response


# A mounted, independent ASGI app: not in /openapi.json, handles every path under /static.
app.mount("/static", StaticFiles(directory=FsPath(__file__).parent / "static"), name="static")


def catalog(request: Request) -> Catalog:
    return request.app.state.catalog


@app.get("/health", include_in_schema=False)
async def health() -> dict[str, str]:
    return {"status": "ok"}


@app.get("/products", tags=["products"], summary="List products", response_model=list[ProductOut])
def list_products(
    request: Request,
    category: Category | None = None,
    max_price: Annotated[int, Query(ge=0, description="Upper bound in cents")] = 1_000_000,
    limit: Annotated[int, Query(ge=1, le=100)] = 20,
    offset: Annotated[int, Query(ge=0)] = 0,
):
    """Filter by category and price; offset pagination (cursor pagination has its own chapter).

    A plain `def`: sqlite3 blocks, so FastAPI runs this function in its thread pool.
    """
    value = category.value if category else None
    return catalog(request).list(value, max_price, limit, offset)


# Declared BEFORE /products/{product_id}: routes are matched in registration order.
@app.get("/products/featured", tags=["products"], response_model=list[ProductOut])
def featured_products(request: Request):
    return catalog(request).featured()


@app.get(
    "/products/{product_id}",
    tags=["products"],
    response_model=ProductOut,
    responses={404: {"description": "No product with this id"}},
)
def get_product(request: Request, product_id: Annotated[int, Path(ge=1, title="Product id")]):
    product = catalog(request).get(product_id)
    if product is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Product not found")
    return product


@app.post("/products", tags=["products"], status_code=status.HTTP_201_CREATED, response_model=ProductOut)
def create_product(request: Request, body: ProductIn, response: Response):
    created = catalog(request).insert(body.name, body.category.value, body.price_cents)
    response.headers["Location"] = f"/products/{created['id']}"
    return created


@app.delete("/products/{product_id}", tags=["products"], status_code=status.HTTP_204_NO_CONTENT)
def delete_product(request: Request, product_id: Annotated[int, Path(ge=1)]) -> None:
    if not catalog(request).delete(product_id):
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Product not found")


@app.get("/categories/{category}", tags=["categories"])
async def describe_category(category: Category) -> dict[str, str]:
    # `category` is an Enum member; compare with members, return `.value` or the member itself.
    if category is Category.books:
        return {"category": category.value, "hint": "sorted by author"}
    return {"category": category.value, "hint": "sorted by name"}


@app.get("/v1/products/{product_id}", tags=["legacy"], deprecated=True, response_model=ProductOut)
def get_product_v1(request: Request, product_id: Annotated[int, Path(ge=1)]):
    """Old path; Swagger UI shows it struck through. Use `GET /products/{product_id}`."""
    return get_product(request, product_id)

The tests walk the status codes (200, 201, 204, 307, 404, 405, 422), the 422 bodies, route order, static files and the rule that TestClient runs the lifespan only inside with:

py
from __future__ import annotations

from typing import Iterator

import pytest
from fastapi.testclient import TestClient

from app.main import app


@pytest.fixture()
def client() -> Iterator[TestClient]:
    # `with` runs the lifespan (startup before the block, shutdown after it).
    with TestClient(app) as c:
        yield c
py
"""After: status codes, conversion, validation errors, route order, static files, lifespan."""

from __future__ import annotations

from fastapi.testclient import TestClient

from app.main import app


def test_list_runs_the_sql_with_converted_query_params(client: TestClient) -> None:
    r = client.get("/products", params={"category": "books", "max_price": "5000", "limit": "1"})
    assert r.status_code == 200
    assert r.json() == [{"id": 1, "name": "The Pragmatic Programmer", "category": "books", "price_cents": 4200}]
    assert "X-Process-Time-Ms" in r.headers  # the middleware wrapped the route


def test_defaults_apply_when_query_params_are_absent(client: TestClient) -> None:
    assert len(client.get("/products").json()) == 5


def test_enum_query_value_outside_the_enum_is_422(client: TestClient) -> None:
    r = client.get("/products", params={"category": "toys"})
    assert r.status_code == 422
    err = r.json()["detail"][0]
    assert err["type"] == "enum" and err["loc"] == ["query", "category"]


def test_query_constraint_violation_is_422_with_loc(client: TestClient) -> None:
    r = client.get("/products", params={"limit": "500"})
    assert r.status_code == 422
    err = r.json()["detail"][0]
    assert err["type"] == "less_than_equal"
    assert err["loc"] == ["query", "limit"]
    assert err["ctx"] == {"le": 100}
    assert "X-Process-Time-Ms" in r.headers  # and 422 responses


def test_path_param_is_converted_and_validated(client: TestClient) -> None:
    assert client.get("/products/3").json()["name"] == "Chess Set"
    bad = client.get("/products/abc")
    assert bad.status_code == 422
    assert bad.json()["detail"][0]["type"] == "int_parsing"
    assert client.get("/products/0").json()["detail"][0]["type"] == "greater_than_equal"


def test_missing_product_is_404_from_httpexception(client: TestClient) -> None:
    r = client.get("/products/999")
    assert r.status_code == 404
    assert r.json() == {"detail": "Product not found"}
    assert "X-Process-Time-Ms" in r.headers  # middleware wraps HTTPException responses too


def test_fixed_path_declared_first_wins_over_the_parameter(client: TestClient) -> None:
    r = client.get("/products/featured")
    assert r.status_code == 200
    assert [p["id"] for p in r.json()] == [1, 2, 5]


def test_create_is_201_with_location_and_filtered_body(client: TestClient) -> None:
    r = client.post("/products", json={"name": "Catan", "category": "games", "price_cents": 4500})
    assert r.status_code == 201
    assert r.headers["location"] == f"/products/{r.json()['id']}"
    assert set(r.json()) == {"id", "name", "category", "price_cents"}


def test_invalid_body_is_422_listing_every_error(client: TestClient) -> None:
    r = client.post("/products", json={"name": "", "category": "toys", "price_cents": -1})
    assert r.status_code == 422
    assert [e["loc"] for e in r.json()["detail"]] == [
        ["body", "name"],
        ["body", "category"],
        ["body", "price_cents"],
    ]


def test_delete_is_204_with_no_body_then_404(client: TestClient) -> None:
    r = client.delete("/products/4")
    assert r.status_code == 204 and r.content == b""
    assert client.delete("/products/4").status_code == 404


def test_wrong_method_is_405_and_allow_names_only_the_first_partial_match(client: TestClient) -> None:
    r = client.put("/products/1", json={})
    assert r.status_code == 405
    # Starlette stops at the first route whose path matches (GET /products/{product_id});
    # DELETE /products/{product_id} exists but is not listed.
    assert r.headers["allow"] == "GET"


def test_head_is_not_added_to_get_routes(client: TestClient) -> None:
    assert client.get("/health").status_code == 200
    assert client.head("/health").status_code == 405  # APIRoute does not add HEAD for GET


def test_enum_path_parameter(client: TestClient) -> None:
    assert client.get("/categories/books").json() == {"category": "books", "hint": "sorted by author"}
    assert client.get("/categories/toys").status_code == 422


def test_trailing_slash_redirects_with_307(client: TestClient) -> None:
    r = client.get("/products/", follow_redirects=False)
    assert r.status_code == 307
    assert r.headers["location"] == "http://testserver/products"


def test_static_files_are_served_by_the_mount(client: TestClient) -> None:
    r = client.get("/static/hello.txt")
    assert r.status_code == 200 and r.text == "Hello from StaticFiles.\n"
    assert "X-Process-Time-Ms" in r.headers  # and the mounted StaticFiles app
    assert client.get("/static/missing.txt").status_code == 404


def test_lifespan_runs_only_inside_the_context_manager() -> None:
    bare = TestClient(app, raise_server_exceptions=True)
    try:
        bare.get("/products")
    except AttributeError as exc:  # app.state.catalog was never created: no startup ran
        assert "catalog" in str(exc)
    else:  # pragma: no cover
        raise AssertionError("expected the lifespan not to run without `with`")
    with TestClient(app) as c:
        assert c.get("/products").status_code == 200

and check what the decorators put into the OpenAPI schema:

py
"""The OpenAPI schema is generated from the routes: check what the decorators put there."""

from __future__ import annotations

from fastapi.testclient import TestClient


def test_schema_metadata_tags_and_version(client: TestClient) -> None:
    schema = client.get("/openapi.json").json()
    assert schema["openapi"] == "3.1.0"
    assert schema["info"]["title"] == "Catalog API" and schema["info"]["version"] == "1.0.0"
    assert [t["name"] for t in schema["tags"]] == ["products", "categories", "legacy"]


def test_operation_ids_summary_description_and_status_codes(client: TestClient) -> None:
    paths = client.get("/openapi.json").json()["paths"]
    listing = paths["/products"]["get"]
    assert listing["operationId"] == "list_products"
    assert listing["summary"] == "List products"
    assert listing["description"].startswith("Filter by category and price")
    assert listing["parameters"][1]["schema"]["minimum"] == 0  # max_price ge=0
    assert "201" in paths["/products"]["post"]["responses"]
    assert "422" in paths["/products"]["post"]["responses"]  # added automatically
    assert "404" in paths["/products/{product_id}"]["get"]["responses"]
    assert "204" in paths["/products/{product_id}"]["delete"]["responses"]


def test_deprecated_and_hidden_routes(client: TestClient) -> None:
    paths = client.get("/openapi.json").json()["paths"]
    assert paths["/v1/products/{product_id}"]["get"]["deprecated"] is True
    assert "/health" not in paths  # include_in_schema=False
    assert not any(p.startswith("/static") for p in paths)  # mounts are not documented
    assert client.get("/health").json() == {"status": "ok"}


def test_enum_becomes_a_schema_with_its_values(client: TestClient) -> None:
    schemas = client.get("/openapi.json").json()["components"]["schemas"]
    assert schemas["Category"]["enum"] == ["books", "games", "music"]


def test_swagger_ui_and_redoc_pages(client: TestClient) -> None:
    docs = client.get("/docs")
    redoc = client.get("/redoc")
    assert docs.status_code == 200 and "swagger-ui" in docs.text
    assert redoc.status_code == 200 and "redoc" in redoc.text.lower()
    assert "/openapi.json" in docs.text and "/openapi.json" in redoc.text

The project file pins the stack (see the version note at the top of the page):

toml
[project]
name = "fastapi-fundamentals-routing"
version = "0.1.0"
description = "Snippets for the FastAPI Fundamentals chapter: routes, path and query parameters, status codes, OpenAPI docs, lifespan"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine. On 3.12+ you can move to the latest releases.
requires-python = ">=3.9"
dependencies = [
    "fastapi==0.128.8",
    # Pinned explicitly: the versions every "real run" on the page used.
    "starlette==0.49.3",
    "pydantic==2.13.5",
    "uvicorn[standard]==0.39.0",
    # Lets Pydantic evaluate `str | None` annotations on Python 3.9; not needed on 3.10+.
    "eval-type-backport==0.4.0; python_version < '3.10'",
]

[project.optional-dependencies]
test = [
    "httpx==0.28.1",
    "pytest==8.4.2",
]
# `fastapi dev` / `fastapi run` come from fastapi-cli, which fastapi[standard] pulls in.
dev = [
    "fastapi[standard]==0.128.8",
]
# Process manager for production on a VM: gunicorn -k uvicorn_worker.UvicornWorker
prod = [
    "gunicorn==23.0.0",
    "uvicorn-worker==0.4.0",
]

[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"

[tool.setuptools]
packages = ["app"]

[tool.fastapi]
# Used by `fastapi dev` / `fastapi run` (fastapi-cli) to find the app object.
entrypoint = "app.main:app"

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q -p no:cacheprovider"
pythonpath = ["."]

The Python angle ​

FastAPI leans on three Python features more than any other framework does. Type hints at runtime: FastAPI calls inspect.signature on every path operation function at import time and reads the annotations (that is why from __future__ import annotations works: Pydantic evaluates the strings later, and on 3.9 needs eval-type-backport for X | None). typing.Annotated (PEP 593, Python 3.9): Annotated[int, Query(le=100)] keeps the real type int for your editor and mypy while carrying FastAPI's metadata alongside it. Coroutines: an async def function is awaited on the event loop; a plain def function is handed to anyio.to_thread.run_sync. Everything else is ordinary Python: the app is a module-level object, decorators register functions in a list, exceptions propagate, and Enum, pathlib, contextlib.asynccontextmanager and sqlite3 are standard library. Python 3.11+ adds enum.StrEnum, which the current FastAPI tutorial uses (class ModelName(StrEnum)); the snippets use class Category(str, Enum), which behaves the same and also runs on 3.9.

The concept catalogue ​

Who does what: Uvicorn, ASGI, Starlette, FastAPI, PydanticClientcurl, browser, httpxUvicorn (ASGI server)socket, TCP, keep-aliveHTTP parsing: h11 / httptoolsevent loop: asyncio / uvloopawait app(scope, receive, send)app = FastAPI() (a Starlette subclass)ServerErrorMiddleware: unhandled exception to 500your middleware (last added = outermost)ExceptionMiddleware: HTTPException, 422 handlersRouter: routes in order, mounts (/static)APIRoute: read path, query, header, bodyPydantic (pydantic-core) validates or 422call: async def on loop, def in thread poolresponse_model filters, serialises to JSON/openapi.json, /docs, /redoc are routes toogenerated from the same route tableOne HTTP request as ASGI messagesscope: type=http, method, path, query_string, headers, client, root_pathreceive() -> http.request (body, more_body)send(http.response.start: status, headers)send(http.response.body: body)

ASGI, Starlette and Uvicorn Must-know ​

In plain words: Uvicorn is the program you start; it listens on a port, reads HTTP off the socket and runs an event loop. For each request it calls your app, a single async function, with a dictionary describing the request and two functions to read the body and write the response. Starlette is a library that turns that low-level call into requests, routes and responses; FastAPI is Starlette plus type-driven parameters, validation and docs.

Common misunderstanding: "Uvicorn is part of FastAPI." It is a separate package and a separate role. pip install fastapi does not install it; pip install "fastapi[standard]" does (with fastapi-cli, httpx, jinja2, python-multipart and others, according to the package metadata). Any ASGI server can run a FastAPI app, and the FastAPI docs list Uvicorn, Hypercorn, Daphne and Granian.

Definition: The ASGI spec: "ASGI is structured as a single, asynchronous callable. It takes a scope, which is a dict containing details about the specific connection, send, an asynchronous callable, that lets the application send event messages to the client, and receive, an asynchronous callable which lets the application receive event messages from the client." For HTTP, "the connection scope lasts just one request". FastAPI's docs: "FastAPI is a class that inherits directly from Starlette. You can use all the Starlette functionality with FastAPI too."

     Uvicorn (server)                         FastAPI app (ASGI callable)
1    accept TCP connection, parse request
2    scope = {type: "http", method: "GET", path: "/products", query_string: b"limit=1", headers: [...]}
3    await app(scope, receive, send) ───────▶ middleware stack, router, path operation
4                                    ◀─────── await receive()   -> {"type": "http.request", "body": b"", "more_body": False}
5                                    ◀─────── await send({"type": "http.response.start", "status": 200, "headers": [...]})
6                                    ◀─────── await send({"type": "http.response.body", "body": b"[...]"})
7    write bytes, keep-alive or close

Real scenario: a team swaps Uvicorn for Hypercorn to get HTTP/2 without touching the app; a test suite drives the app with httpx.ASGITransport and no server at all; a Starlette middleware written for another project (CORS, GZip, sessions) is added to a FastAPI app unchanged; a pure ASGI app (a metrics exporter) is mounted under /metrics.

LayerPackageOwnsYou configure it with
ServerUvicorn (or Hypercorn, Daphne, Granian)Socket, TCP backlog, HTTP/1.1 parsing (h11 or httptools), WebSockets, event loop (asyncio or uvloop), process workers, graceful shutdownCLI flags: --host, --port, --workers, --reload, --timeout-keep-alive, --timeout-graceful-shutdown
ToolkitStarletteRequest, Response classes, Router, Mount, middleware, StaticFiles, TestClient, exception middlewareStarlette classes, app.add_middleware
FrameworkFastAPISignature analysis, parameter extraction, Depends, Pydantic validation, response_model, OpenAPI, Swagger UI, ReDocFastAPI(...), decorator parameters
DataPydantic (core in Rust, pydantic-core)Type conversion, constraints, error list, JSON serialisationModels, Field, Annotated metadata

Fix / how to use it: install the stack explicitly (the snippet's pyproject.toml pins fastapi and uvicorn[standard]; the standard extra pulls uvloop and httptools where they are supported), start it with an import string (uvicorn app.main:app), and remember the boundary: server settings go on the command line, application settings go into FastAPI(...).

The FastAPI() application object Must-know ​

In plain words: app = FastAPI() creates the object that holds the route table, the middleware stack, the exception handlers, the OpenAPI metadata and the lifespan. Every decorator you use (@app.get) adds to it; Uvicorn calls it.

Common misunderstanding: "Settings like the title are cosmetic." title, version, summary, description and openapi_tags go into the OpenAPI document that client generators read; openapi_url=None turns off /openapi.json and both docs UIs; generate_unique_id_function changes every operationId and therefore every generated client method name.

Definition: The reference signature (current FastAPI) is keyword-only. The defaults that matter in a first app: debug=False, title="FastAPI", version="0.1.0", openapi_url="/openapi.json", docs_url="/docs", redoc_url="/redoc", redirect_slashes=True, lifespan=None, default_response_class=Default(JSONResponse), generate_unique_id_function=Default(generate_unique_id), separate_input_output_schemas=True, and in releases after the snippet pin strict_content_type=True (0.132.0), max_body_size=None (0.164.0) and form_limits=None (0.165.0). The reference describes redirect_slashes: a client going to /items for a route /items/ is "automatically redirected with an HTTP status code of 307".

     import time (module load)                   runtime
1    app = FastAPI(title=..., lifespan=...)
2    @app.get("/products") registers APIRoute #1  (signature analysed now)
3    @app.get("/products/{id}") registers #2
4    app.mount("/static", StaticFiles(...))
5                                                Uvicorn: lifespan startup -> lifespan() runs to yield
6                                                first GET /openapi.json: schema built once, then cached
7                                                requests ...
8                                                SIGINT/SIGTERM: lifespan shutdown -> code after yield

Real scenario: an internal admin API with docs_url=None in production and docs on in staging; a public API whose servers list points the Swagger "Try it out" button at the real host; a gateway that serves the app under /api/v1, configured with Uvicorn's --root-path /api/v1 (the root_path constructor parameter is deprecated since 0.146.0 in favour of the server option); an SDK team that needs stable operationIds.

ParameterDefaultEffectWhen to change
title, version, summary, description"FastAPI", "0.1.0", None, ""OpenAPI info blockAlways: clients and docs show them
openapi_tagsNoneTag order and descriptions in docsWhen you use tags (you should)
openapi_url"/openapi.json"Schema URL; None disables schema and UIsPrivate services, or move under a prefix
docs_url / redoc_url"/docs" / "/redoc"UI URLs; None disables oneHide in production, or keep one UI
lifespanNoneStartup/shutdown context managerAny shared resource (pools, clients, models)
redirect_slashesTrue/x/ ↔ /x mismatch answers 307Rarely; turn off if a proxy normalises
generate_unique_id_functiongenerate_unique_id (name_path_method, e.g. u_u_get)Every operationIdGenerated clients: use the function name
debugFalseTracebacks in 500 responsesNever in production
strict_content_type (0.132.0+)TrueJSON bodies without a JSON Content-Type are not parsed as JSONOld clients that omit the header

Fix / how to use it: create one app per process in one module, give it a title and version, pass lifespan=, and make every other configuration explicit there (the After snippet's FastAPI(...) call is the template).

Path operations, decorators and HTTP methods Must-know ​

In plain words: A path operation is FastAPI's name for "this URL path with this HTTP method is handled by this function". You declare it with a decorator named after the method: @app.get("/products"), @app.post("/products"), @app.delete("/products/{product_id}").

Common misunderstanding: "@app.get also answers HEAD, like most servers." Not in FastAPI's APIRoute: in the snippet tests, HEAD /health on the GET-only health route returns 405 (test_head_is_not_added_to_get_routes). (Starlette's own Route adds HEAD for GET; Go's ServeMux does too.) If a monitor or CDN sends HEAD, register it: @app.api_route("/health", methods=["GET", "HEAD"]).

Definition: The FastAPI tutorial defines the word: an operation "refers to one of the HTTP" methods, and the decorator "tells FastAPI that the function below corresponds to the path / with an operation get". The decorators are get, post, put, patch, delete, options, head, trace, plus api_route(path, methods=[...]) for several methods on one function. Decorator parameters configure the response and the docs (status_code, response_model, tags, summary, description, responses, deprecated, operation_id, include_in_schema, response_class, dependencies); function parameters configure the request.

     decorator (response + docs side)                function signature (request side)
1    @app.post(                                      def create_product(
2        "/products",                                    body: ProductIn,          -> JSON body, validated
3        status_code=status.HTTP_201_CREATED,            response: Response,       -> set headers (Location)
4        response_model=ProductOut,                      request: Request,         -> raw request, app.state
5        tags=["products"],                          ):
6    )                                                   return created            -> filtered by ProductOut

Real scenario: a CRUD resource (GET list, GET one, POST, PUT/PATCH, DELETE); a search endpoint that is GET with query parameters so it can be cached and bookmarked; a command endpoint (POST /orders/{id}/cancel) where POST signals "not idempotent"; GraphQL, where the FastAPI tutorial notes "you normally perform all the actions using only POST operations".

MethodDecoratorBody?Safe / idempotent (RFC 9110)Typical status
GET@app.getNoSafe, idempotent200
HEAD@app.head or api_route(methods=["GET","HEAD"])No (headers only)Safe, idempotent200
POST@app.postYesNeither201 (create), 200, 202
PUT@app.putYesIdempotent200, 204
PATCH@app.patchYesNeither by default200
DELETE@app.deleteUsually noIdempotent204
OPTIONS@app.optionsNoSafe200 (CORS preflight is answered by CORSMiddleware)

Fix / how to use it: one function per method and path, the method decorator rather than api_route unless you really need two methods, and the response-side settings on the decorator so they reach the docs. Method semantics in depth: REST API Design.

Route order and matching Must-know ​

In plain words: FastAPI (through Starlette) checks routes from top to bottom in the order you registered them and uses the first one whose path and method match. So a fixed path like /users/me must be declared before a parameter path like /users/{user_id}, or "me" is read as a user id.

Common misunderstanding: "The most specific route wins, like in Go 1.22 or Laravel's constraints." There is no specificity ranking: order is the only rule. Registering the same path and method twice is not an error either; the FastAPI docs say "The first one will always be used since the path matches first", and the snippet probe confirmed it (/dup returned the first function's value).

Definition: From the tutorial: "Because path operations are evaluated in order, you need to make sure that the path for /users/me is declared before the one for /users/{user_id}". For each route Starlette computes a match: full (path and method), partial (path only) or none. The first full match handles the request; if there was no full match but a partial one, the answer is 405 Method Not Allowed with an Allow header listing the methods of that first partially matching route only; with neither, 404 Not Found.

     Routes in registration order          Request PUT /products/1
1    GET    /products                      path differs            -> skip
2    GET    /products/featured             path differs            -> skip
3    GET    /products/{product_id}         path matches, method not -> remember as partial, continue
4    POST   /products                      path differs            -> skip
5    DELETE /products/{product_id}         path matches, method not -> already have a partial
6    Mount  /static                        no
7    result: 405, Allow: GET               (DELETE exists but is not listed; real run in tests/test_main.py)

Real scenario: /users/me silently answered by /users/{user_id} with "user me not found" (the Before bug); /files/{name} registered above /files/upload turning uploads into 405s; an API version router included before a catch-all /{path:path} used for an SPA; a monitoring check that gets 405 for HEAD.

RouterRuleDuplicate registration405 Allow lists
FastAPI / StarletteFirst match in registration orderSilently allowed; first winsMethods of the first partial match
Go 1.22+ http.ServeMux"the most specific pattern takes precedence"; order irrelevantConflicting patterns panic at registrationEvery method registered for the path (w.Header().Set("Allow", ...) in server.go)
Laravel routerFirst match in definition order; where/whereNumber constraints narrow parameters ("If the incoming request does not match the route pattern constraints, a 404 HTTP response will be returned")not checked herenot checked here

Fix / how to use it: group routes by resource and inside each group put literal paths first (/products/featured before /products/{product_id}, as in After); constrain parameters with types so a wrong match fails as 422 instead of returning wrong data; add a test per literal path; and keep catch-all routes last. When routes are split across APIRouters, include_router order is registration order (APIRouter & Project Structure).

Path parameters and type conversion Must-know ​

In plain words: A name in braces in the path (/products/{product_id}) becomes a function argument of the same name. Its type annotation tells FastAPI how to convert the string from the URL: product_id: int gives you an int, and /products/abc never reaches your code.

Common misunderstanding: "product_id: int | None = None makes a path parameter optional." A path parameter is part of the URL, so it is always required. The docs: "A path parameter is always required because it has to be part of the URL path. Adding None to its type does not make it optional." If the value can be absent, you need a second route (/products) or a query parameter.

Definition: FastAPI matches the name in the path template with the function parameter, then lets Pydantic convert and validate the string. Supported types are anything Pydantic can parse from a string: int, float, bool, str, UUID, date, datetime, Decimal, Enum subclasses, constrained types. A value that cannot be converted gives a 422 with "type": "int_parsing" and "loc": ["path", "item_id"] (real run below). For a parameter that must contain slashes, use Starlette's path convertor: @app.get("/files/{file_path:path}"); in the probe, /files/a/b/c.txt arrived as "a/b/c.txt".

     GET /products/abc                              GET /products/3
1    route /products/{product_id} matches           matches
2    raw value "abc"                                raw value "3"
3    Pydantic int: "abc" -> error int_parsing       "3" -> 3, check ge=1 ok
4    422 {"detail":[{"type":"int_parsing",          get_product(product_id=3) runs
        "loc":["path","product_id"], ...}]}         SELECT ... WHERE id = ? with (3,)

Real scenario: numeric ids (/orders/{order_id}), UUID ids (/payments/{payment_id}: UUID) that should reject garbage before the database sees it; dates in the path (/reports/{day}: date → 2026-11-29); file keys with slashes (/files/{key:path} for object-store keys); slugs (/posts/{slug} as str with a pattern).

Annotation/x/42/x/abc/x/4.5Notes
str"42""abc""4.5"No conversion
int42422 int_parsing422 int_parsing
float42.0422 float_parsing4.5
UUID422 uuid_parsing422422Needs a real UUID
Annotated[int, Path(ge=1)]42422422/x/0 → 422 greater_than_equal (real run)
{name:path} with str"42""abc""4.5"Also matches a/b/c

Fix / how to use it: always annotate path parameters with the narrowest type, add bounds with Path(ge=1) through Annotated, and let the database query receive an already-typed value (the SQL below never sees a non-integer id):

sql
-- app/db.py: the queries behind GET /products and GET /products/{product_id}
CREATE INDEX IF NOT EXISTS products_category_price ON products (category, price_cents);

SELECT id, name, category, price_cents
FROM products
WHERE (:category IS NULL OR category = :category)   -- category: Category | None = None
  AND price_cents <= :max_price                     -- max_price: Annotated[int, Query(ge=0)]
ORDER BY id
LIMIT :limit OFFSET :offset;                        -- limit: Query(ge=1, le=100), offset: Query(ge=0)

SELECT id, name, category, price_cents FROM products WHERE id = ?;   -- product_id: Path(ge=1)

Bound parameters (?, :name) are what keeps typed values typed all the way down; f-strings into SQL are an injection bug no matter how well FastAPI validated the input. Index choice and the optional-filter pattern are discussed in Query Planning.

Enum path params Important ​

In plain words: When a path segment can only be one of a few words (books, games, music), declare an Enum and use it as the type. FastAPI accepts only those values, lists them in the docs as a dropdown and gives your function an enum member.

Common misunderstanding: "The function receives the string." It receives the member (Category.books). Compare with members (category is Category.books) and use .value when you need the string; because the class also subclasses str, Category.books == "books" is True too, which is exactly why the docs recommend a string enum.

Definition: The tutorial: "If you have a path operation that receives a path parameter, but you want the possible valid path parameter values to be predefined, you can use a standard Python Enum", and "StrEnum members are also strings, so the API docs will know that the values must be of type string". The OpenAPI schema gets a reusable component with "enum": [...] (the snippet test asserts components.schemas.Category.enum == ["books", "games", "music"]). An unknown value gives 422 with "type": "enum". The same enum works for query parameters.

1    class Category(str, Enum): books = "books"; games = "games"; music = "music"   # 3.11+: StrEnum
2    GET /categories/books  -> describe_category(category=Category.books) -> 200
3    GET /categories/toys   -> 422 {"type": "enum", "loc": ["path","category"],
4                              "msg": "Input should be 'books', 'games' or 'music'", ...}
5    /openapi.json          -> "Category": {"type": "string", "enum": ["books","games","music"]}

Real scenario: report kinds (/reports/{kind} with daily|weekly|monthly), currency codes from a fixed list, ML model names (the tutorial's alexnet|resnet|lenet), sort fields in a query parameter (?sort=price), tags stored in an Enum so every route uses the same tag name.

OptionValidationDocsCode gets
strnonefree textstr
Literal["books", "games"]yesenum list, inlinestr
class Category(str, Enum)yesreusable Category schemaCategory member (also a str)
class Category(StrEnum) (3.11+)yesreusable schemamember; str() gives the value
Enum without stryestype may be wrong in docsmember; not equal to the string

Fix / how to use it: a string enum at module level, reused for path, query and body fields, so the allowed values live in one place and the database CHECK constraint (see the snippet schema) mirrors it.

Query parameters: required, Optional, default values Must-know ​

In plain words: Any function parameter that is not in the path (and is a simple type) is a query parameter: ?category=books&limit=1. No default means required; a default means optional with that value; a default of None means "optional, and I want to know whether it was sent".

Common misunderstanding: "Optional[str] makes a parameter optional." In FastAPI, the default value makes it optional; the type only says what values are allowed. q: Optional[str] (or q: str | None) with no default is still required (and accepts no value other than a string, because a query string cannot carry a real null). Write q: str | None = None.

Definition: The tutorial: "When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as" query parameters, and "when you want to make a query parameter required, you can just not declare any default value". Values are converted like path values. For bool, 1, true, on, yes (any case) become True, 0, false, off, no become False, and the docs add that "An empty value (?short=) or an unrecognized value (for example, ?short=maybe) produces a 422 validation error"; the snippet probe confirmed both ("type": "bool_parsing"). Repeated keys need a list type wrapped in Query(): tag: Annotated[list[str] | None, Query()] = None turns ?tag=a&tag=b into ["a", "b"] (probe result). Without Query(), a list[str] parameter would be read as a body.

     GET /products?category=books&max_price=5000&limit=1
1    category  "books"  -> Category.books              (Enum, optional: default None)
2    max_price "5000"   -> 5000, check ge=0           (default 1_000_000)
3    limit     "1"      -> 1, check 1 <= x <= 100      (default 20)
4    offset    absent   -> 0                           (default)
5    SQL params {category: "books", max_price: 5000, limit: 1, offset: 0}
6    200 [{"id":1,"name":"The Pragmatic Programmer","category":"books","price_cents":4200}]   (real run)

Real scenario: pagination (?limit=20&offset=40, cursor pagination in Pagination); filters (?status=paid&from=2026-11-01); feature switches (?include=lines); search (?q=go+board); multi-select filters (?tag=a&tag=b).

Each row sends requests that include the parameter it shows (verified with TestClient against the pinned stack; script and output in the sources runs/t4_query_table.py):

DeclarationParameter absentEmpty valueValid valueInvalid value
q: str422 missing?q= → ""?q=x → "x"(any string is valid)
q: str = "all""all"?q= → ""?q=x → "x"—
q: str | None = NoneNone?q= → ""?q=x → "x"—
q: Optional[str] = None (3.9 style)None?q= → ""?q=x → "x"—
q: str | None (no default)422 missing?q= → ""?q=x → "x"—
short: bool = FalseFalse?short= → 422 bool_parsing?short=yes → True, ?short=off → False?short=maybe → 422 bool_parsing
limit: Annotated[int, Query(ge=1, le=100)] = 2020?limit= → 422 int_parsing?limit=50 → 50?limit=0 → 422 greater_than_equal; ?limit=500 → 422 less_than_equal; ?limit=abc → 422 int_parsing
tag: Annotated[list[str] | None, Query()] = NoneNone?tag= → [""]?tag=a&tag=b → ["a", "b"]—

Fix / how to use it: every query parameter gets a type, a default (or is deliberately required) and bounds through Query(); booleans are bool, not str; sets of allowed values are an Enum. When the list of filters grows past four or five, group them in a Pydantic model with Annotated[FilterParams, Query()], which is the subject of Request Validation.

Annotated, Query() and Path() Must-know ​

In plain words: Annotated[int, Query(le=100)] says two things at once: to Python and your editor, "this is an int"; to FastAPI, "read it from the query string and refuse anything above 100". Path() does the same for path parameters, and both add the constraint to the OpenAPI docs.

Common misunderstanding: "Query(default=..., ...) as the default value is the way to do it." That was the only way before 0.95.0 and you will see it in older code, but the docs now say: "For new code and whenever possible, use Annotated as explained above. There are multiple advantages (explained below) and no disadvantages." With Annotated the real default stays a normal Python default, so the function can also be called directly in tests.

Definition: typing.Annotated (PEP 593, Python 3.9) attaches metadata to a type. FastAPI looks for its parameter classes in that metadata: Query, Path, Header, Cookie, Body, Form, File, Depends. Common arguments: numeric gt, ge, lt, le, multiple_of; string min_length, max_length, pattern; documentation title, description, examples, deprecated, include_in_schema; and alias (Query(alias="item-query") reads ?item-query=, a name that is not a valid Python identifier). A path parameter with Path "cannot have a default value".

python
from typing import Annotated
from fastapi import FastAPI, Path, Query

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(
    item_id: Annotated[int, Path(ge=1, title="Item id")],
    q: Annotated[str | None, Query(min_length=3, max_length=50, pattern=r"^[a-z ]+$")] = None,
    page_size: Annotated[int, Query(alias="page-size", ge=1, le=100)] = 20,
    legacy_flag: Annotated[bool, Query(deprecated=True, include_in_schema=True)] = False,
):
    return {"item_id": item_id, "q": q, "page_size": page_size}

Real scenario: a limit capped at 100 so nobody downloads the table in one call; a search box that rejects one-letter queries; a header-style parameter name with a dash via alias; a parameter kept for old clients but marked deprecated in the docs; a shared type alias Limit = Annotated[int, Query(ge=1, le=100)] used by every list endpoint.

ConstraintApplies to422 type when violated (Pydantic)OpenAPI keyword
ge=1 / gt=0numbersgreater_than_equal / greater_thanminimum / exclusiveMinimum
le=100 / lt=100numbersless_than_equal / less_thanmaximum / exclusiveMaximum
multiple_of=5numbersmultiple_ofmultipleOf
min_length=3strings, listsstring_too_short / too_shortminLength / minItems
max_length=50strings, listsstring_too_long / too_longmaxLength / maxItems
pattern=r"^[a-z]+$"stringsstring_pattern_mismatchpattern
alias="item-query"name on the wire(missing/invalid as usual)parameter name
deprecated=Truedocs onlynonedeprecated: true

Fix / how to use it: use Annotated everywhere (the snippet does), define reusable aliases for repeated constraints, and keep business rules that need the database (does this category exist?) out of Query(): those are 404/409 decisions inside the function or a dependency (Dependency Injection).

Validation errors: 422 Unprocessable Entity and RequestValidationError Must-know ​

In plain words: If any parameter or the body fails conversion or a constraint, FastAPI does not call your function. It raises RequestValidationError and its default handler answers 422 with a JSON list that says, for each problem, where it was (loc), what kind of problem (type), a human message (msg), the value received (input) and the limits involved (ctx).

Common misunderstanding: "FastAPI stops at the first error." It collects all of them: the snippet's invalid body returned three errors at once (name, category, price_cents). A second one: "422 is for bad JSON syntax only." Malformed JSON is also a 422 in FastAPI ("type": "json_invalid"), not a 400.

Definition: The docs: "When a request contains invalid data, FastAPI internally raises a RequestValidationError." RFC 9110 calls the code 422 "Unprocessable Content": the server "understands the content type of the request content ... and the syntax of the request content is correct, but it was unable to process the contained instructions." The older name "Unprocessable Entity" (RFC 4918) is what Uvicorn still logs ("GET /products?limit=500 HTTP/1.1" 422 Unprocessable Entity, real log) and what status.HTTP_422_UNPROCESSABLE_ENTITY was called; in the pinned Starlette that constant emits DeprecationWarning: 'HTTP_422_UNPROCESSABLE_ENTITY' is deprecated. Use 'HTTP_422_UNPROCESSABLE_CONTENT' instead. (real output). The type strings are Pydantic v2 error codes (missing, int_parsing, bool_parsing, enum, less_than_equal, string_too_short, json_invalid …); the FastAPI page still shows a Pydantic v1 sample ("type": "type_error.integer"), which is not what current versions return.

     POST /products  {"name": "", "category": "toys", "price_cents": -1}
1    body parsed as JSON
2    ProductIn validation: name too short, category not in enum, price below 0
3    RequestValidationError(errors=[3 items])      -> your function is NOT called
4    default handler -> 422
     {"detail":[
       {"type":"string_too_short","loc":["body","name"],"msg":"String should have at least 1 character","input":"","ctx":{"min_length":1}},
       {"type":"enum","loc":["body","category"],"msg":"Input should be 'books', 'games' or 'music'","input":"toys","ctx":{"expected":"'books', 'games' or 'music'"}},
       {"type":"greater_than_equal","loc":["body","price_cents"],"msg":"Input should be greater than or equal to 0","input":-1,"ctx":{"ge":0}}]}

Real scenario: a mobile client sends limit=500 and gets a precise error instead of a silent cap; a front-end maps loc to form fields and highlights them; an API gateway logs the type codes to find the most common client mistakes; a partner integration that sends "price": "12,50" learns the format in the first test call.

loc[0]MeaningExample
"path"Path parameter["path", "product_id"]
"query"Query parameter["query", "limit"]
"header"Header["header", "x-request-id"]
"cookie"Cookie["cookie", "session"]
"body"Body field (nested path follows)["body", "lines", 0, "qty"]
"body", <int>JSON syntax error at that character["body", 11] with json_invalid (real)

Fix / how to use it: keep the default 422 format unless every client of the API expects something else; if you must change it (Problem Details, RFC 9457), override the handler with @app.exception_handler(RequestValidationError), which Exceptions & Responses covers. Do not catch validation yourself with try/except inside the function: by then FastAPI has already answered.

status_code and the status module Must-know ​

In plain words: The status_code= argument on the decorator is the status of a successful response. Name it with the constants in fastapi.status (status.HTTP_201_CREATED) instead of bare numbers, so the code reads like the docs.

Common misunderstanding: "status_code is a parameter of my function." The docs are explicit: status_code is a parameter of the decorator method, "Not of your path operation function". Errors are not set there either: they come from HTTPException or exception handlers.

Definition: status_code "receives a number with the HTTP status code" and "can alternatively also receive an IntEnum, such as Python's http.HTTPStatus". It sets the response status and documents it in OpenAPI; for codes that forbid a body FastAPI "will produce OpenAPI docs that state there is no response body". fastapi.status re-exports Starlette's constants. To choose the status at runtime, take a response: Response parameter and set response.status_code, or return a JSONResponse yourself.

     @app.post("/products", status_code=status.HTTP_201_CREATED)
1    request valid -> create_product(...) returns dict
2    response_model ProductOut filters the dict
3    HTTP/1.1 201 Created
4    location: /products/6                  (set through the Response parameter)
5    {"id":6,"name":"Catan","category":"games","price_cents":4500}   (real curl output)

Real scenario: 201 + Location after a create; 204 for delete; 202 for "accepted, processing in the background"; 200 for an update that returns the new state; 304 for conditional GETs (usually a proxy or StaticFiles concern).

CodeConstant (fastapi.status)When in this chapter
200HTTP_200_OKDefault for every path operation
201HTTP_201_CREATEDPOST /products
202HTTP_202_ACCEPTEDWork queued, result later
204HTTP_204_NO_CONTENTDELETE /products/{id}: empty body
307HTTP_307_TEMPORARY_REDIRECTTrailing-slash redirect
400HTTP_400_BAD_REQUESTGeneric client error you raise yourself
404HTTP_404_NOT_FOUNDNo route, or HTTPException for a missing resource
405HTTP_405_METHOD_NOT_ALLOWEDPath exists, method does not
409HTTP_409_CONFLICTDuplicate unique key
413HTTP_413_CONTENT_TOO_LARGEBody too large (0.164.0+ max_body_size, or the proxy)
422HTTP_422_UNPROCESSABLE_CONTENTValidation failed (older alias ..._ENTITY deprecated)
500HTTP_500_INTERNAL_SERVER_ERRORUnhandled exception
503HTTP_503_SERVICE_UNAVAILABLEUvicorn --limit-concurrency exceeded

Fix / how to use it: one success status per operation on the decorator; constants from status; errors via HTTPException. Choosing codes for a resource design is in REST API Design.

JSON response and response_model Must-know ​

In plain words: Whatever you return (a dict, a list, a Pydantic model, a dataclass) is converted to JSON. If you declare a return type or response_model, FastAPI first validates the value against it and drops every field that is not in the model, then documents that shape in OpenAPI.

Common misunderstanding: "If I return a dict with a password key and the model has no password, it will error." It silently filters the key out (probe: {"name":"a","password":"x"} came back as {"name":"a"}). That is the security feature: the docs say it "will limit and filter the output data to what is defined in the return type. This is particularly important for security".

Definition: FastAPI "will use this return type to: Validate the returned data", add "a JSON Schema for the response, in the OpenAPI path operation", and limit the output. Use response_model= on the decorator when the function returns something that is not literally the declared type (a dict or ORM row); the return annotation otherwise. Without a model, the value goes through jsonable_encoder and JSONResponse. Since 0.130.0, when a Pydantic return type or response model exists, FastAPI serialises "with Pydantic (in Rust)", and the docs' advice is: "if you want the maximum performance, use a Response Model and don't declare a response_class in the path operation decorator". A path operation can also return any Starlette Response (JSONResponse, PlainTextResponse, RedirectResponse, FileResponse) to bypass all of this.

1    get_product returns {"id":3,"name":"Chess Set","category":"games","price_cents":3000,"featured":0}
     (suppose the SELECT had used SELECT *, so the internal column "featured" came along)
2    response_model=ProductOut validates id:int, name:str, category:Category, price_cents:int
3    extra key "featured" is dropped, nothing is raised
4    serialised to bytes, content-type: application/json, content-length set
5    client sees {"id":3,"name":"Chess Set","category":"games","price_cents":3000}

Real scenario: a user endpoint that must never leak password_hash; an internal row with audit columns shown publicly as a slim model; a list endpoint typed list[ProductOut]; generated TypeScript clients that rely on the response schema.

You returnWith response_model / return typeWithout
dict with extra keysValidated, extras droppedSent as is
Pydantic modelRe-validated as the response model, extras droppedmodel_dump then JSON
ORM-style object with attributesValidated from its attributes, extras dropped (a probe with a plain class worked on 0.128.8 without extra config)jsonable_encoder tries to convert it
JSONResponse(...)Model ignored (you built the response)Sent as is
None with status_code=204Empty bodyEmpty body

Fix / how to use it: a separate output model per resource (ProductOut) distinct from the input model (ProductIn), declared on every read and create; never return ORM objects without one. Models, model_config and serialisation options in depth: Typing & Pydantic v2.

HTTPException and 404 Must-know ​

In plain words: To answer with an error, raise HTTPException(status_code=404, detail="Product not found"). The request stops right there, even from a helper function three calls deep, and the client gets {"detail": "Product not found"} with status 404.

Common misunderstanding: "I can return HTTPException(...)." Returning it serialises the exception object as data with status 200 (probe: 200 {"status_code":404,"detail":"x","headers":null}). The docs: "Because it's a Python exception, you don't return it, you raise it."

Definition: fastapi.HTTPException(status_code, detail=None, headers=None) subclasses Starlette's HTTPException. detail may be "any value that can be converted to JSON ... not only str"; headers adds response headers (for example WWW-Authenticate on a 401). Starlette's ExceptionMiddleware renders it. The router's own 404 for an unknown path uses the same handler, which is why both look like {"detail": "Not Found"} vs {"detail": "Product not found"}. Custom handlers (@app.exception_handler(StarletteHTTPException)) and Problem Details are in Exceptions & Responses.

     GET /products/999
1    route matches, 999 passes ge=1
2    get_product: catalog.get(999) -> None
3    raise HTTPException(404, "Product not found")
4    ExceptionMiddleware -> 404 {"detail":"Product not found"}
5    timing middleware still adds X-Process-Time-Ms (it wraps the handler)

Real scenario: a missing resource (404); a duplicate email (409 with detail={"field": "email", "reason": "taken"}); an expired token (401 with WWW-Authenticate: Bearer); an order that cannot be cancelled anymore (409 or 422, a design decision).

SituationRaiseBody
Row not foundHTTPException(404, "Product not found"){"detail":"Product not found"}
Unknown URL(router){"detail":"Not Found"}
ConflictHTTPException(409, detail={...}){"detail":{...}}
Auth missingHTTPException(401, headers={"WWW-Authenticate": "Bearer"}){"detail":...}
Bug in your code(nothing; an exception escapes)500 Internal Server Error

Fix / how to use it: raise HTTPException for expected outcomes, let real bugs become 500s (and get logged), and raise domain exceptions in non-HTTP code that one handler maps to statuses once the app grows.

async def vs def routes: the threadpool for sync routes Must-know ​

5 requests x 200 ms of waiting (measured in the lab)async def + time.sleep (blocks the loop): 1.05 sreq 1req 2req 3req 4req 5event-loop thread: nothing else runs, not even /healthdef + time.sleep (thread pool): 0.21 s5 worker threads ("AnyIO worker thread")anyio.to_thread.run_sync, default limiter 40 tokensshared with sync dependencies, FileResponse, UploadFilethe loop stays free; the 41st blocking call waitsasync def + await asyncio.sleep (yields): 0.21 sone thread, five coroutines suspended at awaitneeds an async driver: httpx.AsyncClient, asyncpg, aiosqlite0 s0.2 s0.6 s1.0 s

In plain words: One event loop thread serves every request in a Uvicorn process. An async def route runs on that thread, so it must only wait with await. A plain def route is sent to a pool of worker threads, so it may block. Pick by what the function calls, not by taste.

Common misunderstanding: "def routes are the slow legacy option." They are the correct option for blocking libraries (sqlite3, psycopg in sync mode, requests, most SDKs, file I/O, CPU work that releases the GIL). The mistake is the other way round: a blocking call inside async def. The docs: "If you just don't know, use normal def." For trivial compute-only functions they add the opposite note: "it's better to use async def unless your path operation functions use code that performs blocking I/O" (a thread hop costs more than the ~100 ns saved).

Definition: "When you declare a path operation function with normal def instead of async def, it is run in an external threadpool that is then awaited". Starlette's docs: it "uses anyio.to_thread.run_sync to run the synchronous code", and "The default thread pool size is only 40 tokens. This means that only 40 threads can run at the same time. This limit is shared with other libraries: for example FastAPI also uses anyio to run sync dependencies". The same pool serves FileResponse, UploadFile and sync background tasks. The snippet's app/concurrency.py measures it with five concurrent requests per route on one event loop (httpx.ASGITransport):

py
"""async def vs def: what each kind of route does to the event loop.

Three routes do the same 200 ms of "I/O":
- /blocking-async: time.sleep inside async def  -> blocks the event loop (bug)
- /sync:           time.sleep inside def        -> runs in the thread pool (fine)
- /async:          await asyncio.sleep in async  -> yields to the loop (best)
"""

from __future__ import annotations

import asyncio
import threading
import time

from fastapi import FastAPI

app = FastAPI()
DELAY = 0.2


@app.get("/blocking-async")
async def blocking_async() -> dict[str, str]:
    time.sleep(DELAY)
    return {"thread": threading.current_thread().name}


@app.get("/sync")
def sync_route() -> dict[str, str]:
    time.sleep(DELAY)
    return {"thread": threading.current_thread().name}


@app.get("/async")
async def async_route() -> dict[str, str]:
    await asyncio.sleep(DELAY)
    return {"thread": threading.current_thread().name}
py
"""Five concurrent requests against each route, on one event loop (httpx.ASGITransport)."""

from __future__ import annotations

import asyncio
import threading
import time

import httpx

from app.concurrency import DELAY, app

N = 5


async def _fire(path: str) -> tuple[float, set[str]]:
    transport = httpx.ASGITransport(app=app)
    async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
        start = time.perf_counter()
        responses = await asyncio.gather(*(client.get(path) for _ in range(N)))
        elapsed = time.perf_counter() - start
    return elapsed, {r.json()["thread"] for r in responses}


def test_blocking_call_in_async_def_serialises_requests() -> None:
    elapsed, threads = asyncio.run(_fire("/blocking-async"))
    print(f"/blocking-async: {N} requests in {elapsed:.2f}s on {threads}")
    assert elapsed >= N * DELAY * 0.95  # one after another
    assert threads == {threading.main_thread().name}  # ran on the event-loop thread


def test_def_route_runs_in_the_thread_pool() -> None:
    elapsed, threads = asyncio.run(_fire("/sync"))
    print(f"/sync: {N} requests in {elapsed:.2f}s on {threads}")
    assert elapsed < N * DELAY * 0.6  # overlapped
    assert threading.main_thread().name not in threads


def test_awaiting_async_io_overlaps_on_one_thread() -> None:
    elapsed, threads = asyncio.run(_fire("/async"))
    print(f"/async: {N} requests in {elapsed:.2f}s on {threads}")
    assert elapsed < N * DELAY * 0.6
    assert threads == {threading.main_thread().name}
     5 concurrent requests, each waits 200 ms                       real run (tests/test_concurrency.py -s)
1    /blocking-async  async def + time.sleep      -> 1.05 s on {'MainThread'}            serialised
2    /sync            def + time.sleep            -> 0.21 s on {'AnyIO worker thread'}   thread pool
3    /async           async def + asyncio.sleep   -> 0.21 s on {'MainThread'}            one thread, overlapped

Real scenario: a sync ORM session inside async def that makes p99 latency equal the slowest query of any concurrent request; a PDF renderer that pins the loop for seconds (move it to def, or a process pool, or a job queue); an async route calling httpx.AsyncClient to three upstreams with asyncio.gather; a pool of 40 threads exhausted by slow sync database calls, so the 41st sync request waits even though CPU is idle.

FunctionCallsRuns onVerdict
async defonly await-able I/O (httpx.AsyncClient, asyncpg, SQLAlchemy AsyncSession, aiosqlite)event loopBest throughput
async defblocking I/O (requests, time.sleep, sync DB driver)event loop, blocking itBug: every request waits
defblocking I/OAnyIO thread pool (40 tokens by default)Correct
defnothing blocking (pure compute, tiny)thread poolWorks; async def is cheaper
async defheavy CPU (image resize, big JSON)event loopBug: use a process pool or a worker
async defa blocking call wrapped in await anyio.to_thread.run_sync(fn) / run_in_threadpoolthread pool for that callCorrect escape hatch

Fix / how to use it: decide per route: all-async stack → async def; any blocking library → def; mixed → async def with the blocking piece wrapped in run_in_threadpool. The pool size is changed through anyio.to_thread.current_default_thread_limiter().total_tokens (inside the running loop, for example in the lifespan; the probe read the default value 40); raise it only with a matching database pool size. The event loop, tasks and blocking calls as a Python topic: Async Python.

Static files: StaticFiles and mounts Important ​

In plain words: app.mount("/static", StaticFiles(directory="static"), name="static") serves files from a folder under a URL prefix. A mount is a separate little app glued onto a path: everything under /static goes to it, and it is invisible in your API docs.

Common misunderstanding: "A mount behaves like a route group." It does not: the docs say "a mounted application is completely independent. The OpenAPI and docs from your main application won't include anything from the mounted application", and lifespan events "will only be executed for the main application, not for Sub Applications - Mounts". Grouping API routes is APIRouter's job.

Definition: StaticFiles(directory=..., packages=None, html=False, check_dir=True, follow_symlink=False) comes from Starlette (fastapi.staticfiles re-exports it). It answers "404 Not found" or "405 Method not allowed" for requests that do not match; with html=True it serves index.html for directories and a 404.html if present. File reads use the thread pool. Starlette 1.1.0 added "Reject absolute paths in StaticFiles.lookup_path". name="static" lets templates call url_for("static", path="logo.png").

1    GET /static/hello.txt   -> Mount("/static") matches before the API routes are tried further
2    StaticFiles looks up app/static/hello.txt, stat(), ETag/Last-Modified
3    200 "Hello from StaticFiles.\n"                       (real test)
4    GET /static/missing.txt -> 404                        (real test)
5    /openapi.json has no /static paths                    (real test)

Real scenario: a small admin UI's CSS and JS; downloadable sample CSVs for an import API; a single-page app built into dist/ and served with html=True next to /api; user uploads (better from object storage or a CDN; see CDNs).

OptionWhere static files come fromGood for
StaticFiles mountThe app processDev, small internal tools
Nginx in frontDisk on the proxy hostOne VM, many files; Uvicorn docs: Nginx "can deal with serving your static media and buffering slow requests"
CDN / object storageEdge cachesPublic assets, uploads, anything large
FileResponse in a routeThe app, with auth checks firstPrivate downloads

Fix / how to use it: mount static files once in the app module with an absolute directory (Path(__file__).parent / "static", as the snippet does, so the working directory does not matter), keep API routes under their own prefix, and move public assets to a CDN when traffic grows. FileResponse, streaming and SSE: Exceptions & Responses.

OpenAPI, Swagger UI and ReDoc: /docs, /redoc, /openapi.json Must-know ​

In plain words: FastAPI writes a complete machine-readable description of your API (OpenAPI) and serves it at /openapi.json. Two web pages read that file: Swagger UI at /docs, where you can try requests, and ReDoc at /redoc, which is a clean three-panel reference.

Common misunderstanding: "The docs are a separate artefact I maintain." They are generated from the same route table and signatures your requests use, on every start; if they are wrong, the code is wrong. A second one: "Turning off /docs hides the API." Only openapi_url=None stops the schema being served; and hiding a schema is not access control.

Definition: The OpenAPI Specification "defines a standard, programming language-agnostic interface description for HTTP APIs, which allows both humans and computers to discover and understand the capabilities of a service without requiring access to source code, additional documentation, or inspection of network traffic." FastAPI's output declares "openapi": "3.1.0" (real test), which aligns its data schemas with JSON Schema; the FastAPI docs say the schema describes the data "sent and received by your API using JSON Schema". Swagger UI and ReDoc are loaded from a CDN by default (the HTML pages reference external JS and CSS), which matters for offline or air-gapped deployments. OAS 3.2.0 exists (swagger.io shows "Version 3.2.0"); FastAPI emits 3.1.0.

1    app start: routes registered, nothing generated yet
2    GET /openapi.json  -> app.openapi(): walk routes, build paths + components, cache in app.openapi_schema
3    GET /docs          -> small HTML page that loads Swagger UI and points it at /openapi.json
4    browser            -> fetches /openapi.json, renders operations grouped by tag, "Try it out"
5    GET /redoc         -> HTML page that loads ReDoc with the same /openapi.json
6    openapi-generator / openapi-typescript -> client code from the same file

Real scenario: front-end developers generating a typed TypeScript client from /openapi.json on every build; contract tests that diff the schema in CI to catch breaking changes; an API gateway (Kong, AWS API Gateway) importing the schema; partner documentation published with ReDoc; Postman importing the schema to build a collection.

Swagger UI (/docs)ReDoc (/redoc)
PurposeExplore and call the API ("Try it out")Read the reference
LayoutOperations grouped by tag, expandableThree panels: navigation, docs, request/response examples
AuthAuthorize button, OAuth2 redirect at /docs/oauth2-redirectDisplay only
Configureswagger_ui_parameters={...}, swagger_ui_init_oauthCustom HTML via get_redoc_html
Disabledocs_url=Noneredoc_url=None

Fix / how to use it: keep /openapi.json in CI as an artefact and diff it; give the app a title, version and tags; for production decide per audience whether the UIs are public, internal-only or off (docs_url=None, redoc_url=None while keeping openapi_url for clients, or everything off for private services behind a gateway).

Path operation metadata: tags, summary, description, operationId, deprecated, include_in_schema Important ​

In plain words: Decorator arguments that do not change behaviour but shape the docs and generated clients: which group the endpoint belongs to (tags), a one-line title (summary), a longer text (description, or the function's docstring), a stable identifier (operation_id), a "do not use" flag (deprecated=True) and a switch to hide it (include_in_schema=False).

Common misunderstanding: "deprecated=True turns the endpoint off." It still works; the docs strike it through. And "include_in_schema=False protects the route." It only removes it from the schema; anyone who knows the URL can call it.

Definition: "You can add tags to your path operation, pass the parameter tags with a list of str"; "you can declare the path operation description in the function docstring and FastAPI will read it from there" (Markdown allowed). OpenAPI defines operationId as a "Unique string used to identify the operation. The id MUST be unique among all operations described in the API." FastAPI's default is generate_unique_id(route): the function name, the path and the method joined (u_u_get in the probe, list_products_products_get for the snippet's list route); the FastAPI docs show passing a custom generate_unique_id_function to use function names, and warn "you have to make sure each one of your path operation functions has a unique name". deprecated "Declares this operation to be deprecated" in OpenAPI terms. responses={404: {...}} documents extra statuses.

     @app.get("/products", tags=["products"], summary="List products", response_model=list[ProductOut])
     def list_products(...):  """Filter by category and price; ..."""
1    operationId   "list_products"          (generate_unique_id_function=operation_id_from_name)
2    tags          ["products"]             (order + description from openapi_tags)
3    summary       "List products"
4    description   docstring, Markdown
5    parameters    category (enum), max_price (minimum 0), limit (1..100), offset (minimum 0)
6    responses     200 (array of ProductOut), 422 (HTTPValidationError, added automatically)   (real test)

Real scenario: an SDK team that needs client.list_products(), not client.list_products_products_get(); a v1 endpoint marked deprecated for a quarter before removal; health and metrics routes hidden from partner docs; tags per bounded context (orders, payments) so a 200-route API stays navigable.

ArgumentWhere it appearsDefault
tags=["products"]Grouping in both UIs; tags in the operationnone (group "default")
summary="..."Operation titleFunction name, title-cased
description="..." or docstringOperation bodyDocstring
response_description="..."Text of the success response"Successful Response"
operation_id="..."operationId; client method namesgenerate_unique_id
deprecated=TrueStruck through, deprecated: trueFalse
include_in_schema=FalseNot in /openapi.json or UIsTrue
responses={404: {...}}Extra response entriesonly success + 422

Fix / how to use it: tags from an Enum or a constant list with openapi_tags descriptions, function names as operationId (unique names enforced by review or a test), docstrings as descriptions, deprecated=True with a removal date in the description, and include_in_schema=False only for operational endpoints that also have real protection.

Lifespan: startup and shutdown, the app lifecycle Must-know ​

In plain words: Code that must run once before the first request (open a database pool, create one shared HTTP client, load a model) and once after the last one (close them) goes into one async function with a yield in the middle, passed as FastAPI(lifespan=...).

Common misunderstanding: "Module-level code is the same thing." Module code runs at import, including in every test and every tool that imports the module, and has no shutdown half. A second one: "@app.on_event("startup") is fine." It is deprecated, and "If you provide a lifespan parameter, startup and shutdown event handlers will no longer be called. It's all lifespan or all events, not both." Starlette 1.0.0 removed the on_startup/on_shutdown parameters from its own Starlette and Router; FastAPI 0.128.3 re-implemented on_event itself to stay backwards compatible.

Definition: "The first part of the function, before the yield, will be executed before the application starts. And the part after the yield will be executed after the application has finished." Underneath, it is the ASGI Lifespan Protocol, which "defines events called startup and shutdown"; Uvicorn's --lifespan option chooses auto, on or off. Lifespan runs once per process: with --workers 2 each worker runs its own startup (real log below shows two "Application startup complete."). TestClient runs it only when used as a context manager (with TestClient(app) as client:); the snippet test proves that without with, app.state.catalog does not exist.

     uvicorn app.main:app  (real log)
1    INFO: Started server process [3910]
2    INFO: Waiting for application startup.        -> lifespan(): Catalog(":memory:") opened, seeded
3    INFO: Application startup complete.
4    INFO: Uvicorn running on http://127.0.0.1:18765
5    ... requests ...
6    SIGINT
7    INFO: Shutting down
8    INFO: Waiting for application shutdown.       -> code after yield: catalog.close()
9    INFO: Application shutdown complete.
10   INFO: Finished server process [3910]

Real scenario: a SQLAlchemy async engine created at startup and disposed at shutdown; one httpx.AsyncClient per upstream (connection pooling) instead of one per request; an ML model loaded once (the FastAPI docs' example) so tests that do not need it stay fast; a background consumer task started and cancelled cleanly; flushing telemetry on shutdown.

MechanismStatusRunsNotes
FastAPI(lifespan=cm)Recommended since 0.93.0Once per process, around servingState on app.state or yielded as a dict
@app.on_event("startup"/"shutdown")DeprecatedSame momentsIgnored if lifespan is set
Module-level codeNot a lifecycle hookAt importNo shutdown; runs in tests and tools
Dependency with yieldPer requestAround one requestSessions, transactions (Dependency Injection)
Mounted sub-app's lifespanNot run by the parentnever (by default)Main app only

Fix / how to use it: one lifespan per app (the After snippet), resources stored on app.state and read through request.app.state or a dependency, cleanup after yield that also runs if startup partly failed (use try/finally or AsyncExitStack when several resources are opened). Shutdown deadlines (--timeout-graceful-shutdown) and container signals are in FastAPI in Production.

Middleware position in the request lifecycle Important ​

In plain words: Middleware wraps the whole app: it sees every request before any route and every response after it, including 404s, 422s and static files. Several middlewares form layers like an onion; the last one you add is the outermost.

Common misunderstanding: "Middleware runs in the order I add it." The opposite: "each new middleware wraps the application, forming a stack. The last middleware added is the outermost, and the first is the innermost. On the request path, the outermost middleware runs first." The probe added first then second and recorded second-in, first-in, first-out, second-out.

Definition: @app.middleware("http") takes async def mw(request, call_next); app.add_middleware(Class, **options) adds an ASGI middleware class (CORS, GZip, TrustedHost). Starlette always places ServerErrorMiddleware outermost ("This is always the outermost middleware layer") and ExceptionMiddleware innermost, around the router; user middleware sits between. Consequences: an unhandled exception becomes a 500 outside your middleware (so your middleware may not add headers to it), while HTTPException and 422 responses pass through your middleware normally. Dependencies with yield finish after the middleware ("the exit code will run after the middleware") and background tasks run "after all the middleware". Starlette recommends wrapping the whole app in CORSMiddleware when CORS headers must appear even on 500 responses.

     request ─▶ ServerErrorMiddleware ─▶ second ─▶ first ─▶ ExceptionMiddleware ─▶ Router ─▶ path operation
     response ◀─ ServerErrorMiddleware ◀─ second ◀─ first ◀─ ExceptionMiddleware ◀─ Router ◀─┘
1    app.add_middleware / @app.middleware order: first, then second  -> second is outer
2    raise HTTPException(404)  -> handled by ExceptionMiddleware, passes back through first and second
3    raise RuntimeError        -> escapes first and second, ServerErrorMiddleware answers 500

Real scenario: a request-id middleware that must be outermost so every log line has the id; a timing header (the snippet's X-Process-Time-Ms: the curl run shows it on the 200 and 201, and test_main.py asserts it on the 404, the 422 and a static file); GZip that must sit outside anything that inspects the body; CORS on error responses; authentication that belongs in a dependency rather than middleware because it needs per-route rules.

ConcernMiddleware or dependency?Why
Request id, timing, access logMiddlewareEvery request, including 404/422
CORS, GZip, TrustedHostMiddleware (Starlette classes)Protocol-level, route-agnostic
Authentication / authorizationDependencyPer-route, typed, documented in OpenAPI
Database session per requestDependency with yieldScoped to routes that need it
Body size limitProxy, or max_body_size (0.164.0+)Before reading the body

Fix / how to use it: add middleware in one place in the app module in the order "innermost first", keep middleware cheap and route-agnostic, and move anything route-specific into Depends. The dependency side is in Dependency Injection; rate limiting as a design topic is in Rate Limiting.

GET /products/abc?limit=5: from route match to status code1. Router: routesin registration orderfull match2. Extract valuespath, query, header, cookie, body3. Validate (Pydantic)convert "5" to int, check le=100no path matched: 404path matched, method not:405 + Allow (first match only)invalidRequestValidationError422, detail: [type, loc, msg,input, ctx] for every errorvalid4. Call the functionasync def: awaited on the loopdef: run in the thread poolraiseHTTPException(404, detail)ExceptionMiddleware renders{"detail": "..."} with that statusreturn5. response_model / return typevalidate, filter extra fields, to JSONstatus_code from the decorator (200 default)Every path back to the client passes through your middleware in reverse order.

Running it: uvicorn --reload, workers, gunicorn with uvicorn workers Must-know ​

Processes: --reload for development, workers or replicas for productionuvicorn --reloadreloader (watchfiles)1 server processrestarted on file changeuvicorn --workers 2 or gunicorn -w 2 -k uvicorn_worker.UvicornWorkerparent: process managerworker 1 (own PID)event loop + thread poollifespan startup/shutdownown memory: own :memory: DBworker 2 (own PID)event loop + thread poollifespan startup/shutdownown memory: own :memory: DBKubernetes / containers1 Uvicorn process per podreplicas: N instead of workersthe orchestrator restarts,the Service load-balancesThe OS shares one listening socket between workers.Anything kept in process memory is per worker:caches, counters, sessions, rate limits. Shared state goesto PostgreSQL or Redis.

In plain words: In development run one process that restarts when you save a file (uvicorn app.main:app --reload or fastapi dev). In production run several processes so you use several CPU cores (uvicorn --workers 4, fastapi run --workers 4, or Gunicorn managing Uvicorn workers) — or, on Kubernetes, one process per container and more replicas.

Common misunderstanding: "--reload is harmless in production." It watches the file system and is "mutually exclusive" with --workers; the Uvicorn docs say "Run uvicorn --reload from the command line for local development." A second one: "workers share memory." Each worker is a separate process with its own event loop, thread pool, lifespan and in-memory state; the snippet's :memory: SQLite database would exist once per worker.

Definition: Uvicorn's flags (all present in uvicorn --help of 0.39.0): --reload ("Enable auto-reload"), --workers ("Defaults to the $WEB_CONCURRENCY environment variable if available, or 1. Not valid with --reload."), --loop auto|asyncio|uvloop, --http auto|h11|httptools, --lifespan auto|on|off, --proxy-headers, --forwarded-allow-ips, --root-path, --limit-concurrency ("before issuing HTTP 503 responses"), --backlog (2048 by default per the current settings page), --limit-max-requests, --timeout-keep-alive (default 5 s), --timeout-graceful-shutdown. Uvicorn's multiprocess manager "does not use pre-fork, but uses spawn", and SIGHUP restarts workers one at a time. For Gunicorn, the Uvicorn docs now say "The uvicorn.workers module is deprecated and will be removed in a future release. You should use the uvicorn-worker package instead"; its README gives gunicorn example:app -w 4 -k uvicorn_worker.UvicornWorker. fastapi dev / fastapi run (fastapi-cli, part of fastapi[standard]) start Uvicorn; fastapi run --workers 4 is the FastAPI docs' production example, and the docs add that on Kubernetes "you will probably not want to use workers and instead run a single Uvicorn process per container".

     uvicorn app.main:app --port 18766 --workers 2     (real log, abridged)
1    INFO: Started parent process [4011]
2    INFO: Started server process [4014]
3    INFO: Started server process [4015]
4    INFO: Application startup complete.               (printed twice: one lifespan per worker)
5    INFO: Application startup complete.
6    SIGINT -> INFO: Terminated child process [4014] ... Application shutdown complete. (x2)
7    INFO: Stopping parent process [4011]

Real scenario: a laptop with fastapi dev and auto-reload; a single VM with gunicorn -w 4 -k uvicorn_worker.UvicornWorker behind Nginx; a Kubernetes Deployment with one Uvicorn process per pod and an HPA scaling replicas; a CPU-heavy service where --workers equals the core count; a memory-leaking dependency contained by --limit-max-requests (newer Uvicorn releases add --limit-max-requests-jitter; 0.39.0 does not have it).

CommandProcessesUse
fastapi dev1 + reloaderDevelopment; recent fastapi-cli reads [tool.fastapi] entrypoint, older ones (0.0.22 here) try main.py, app.py, api.py, app/main.py …
uvicorn app.main:app --reload1 + reloaderDevelopment
fastapi run1Containers (one process per container)
uvicorn app.main:app --host 0.0.0.0 --port 80001Containers
uvicorn app.main:app --workers 41 manager + 4VM without another process manager
fastapi run --workers 41 manager + 4Same, via fastapi-cli
gunicorn app.main:app -w 4 -k uvicorn_worker.UvicornWorker1 Gunicorn master + 4VM, Gunicorn's process management and signals

Fix / how to use it: --reload only on laptops; in containers one process per container; on VMs workers ≈ CPU cores, with shared state in PostgreSQL or Redis, never in process memory. Worker sizing, --proxy-headers, graceful shutdown deadlines and Docker images: FastAPI in Production.

Calling and testing: curl, httpx, TestClient Must-know ​

In plain words: From a terminal you call the running server with curl. From Python you call it with httpx. In tests you do not start a server at all: TestClient(app) sends requests straight into the ASGI app and gives you an httpx-style response.

Common misunderstanding: "TestClient tests the server." It tests the app: no Uvicorn, no socket, no --workers, no proxy headers. And it runs the lifespan only inside with TestClient(app) as client:. For server-level behaviour (timeouts, keep-alive, workers) run Uvicorn, as the Lab does.

Definition: FastAPI's docs: TestClient "is based on HTTPX", so "Use the TestClient object the same way as you do with httpx"; it needs httpx installed. Test functions are plain def (TestClient runs the app's event loop for you). raise_server_exceptions=True (default) re-raises exceptions from the app into the test, which hides the 500 response; the Before test uses raise_server_exceptions=False to see it. For async tests, httpx.AsyncClient(transport=httpx.ASGITransport(app=app)) drives the app on your own loop (the concurrency test does this); note that ASGITransport does not run lifespan. Current Starlette (1.2.0+) builds TestClient on the new httpx2 package and calls plain httpx "still supported, but deprecated"; the pinned Starlette 0.49.3 uses httpx.

     $ curl -s "http://127.0.0.1:18765/products?limit=500"           (real)
1    {"detail":[{"type":"less_than_equal","loc":["query","limit"],"msg":"Input should be less than or equal to 100","input":"500","ctx":{"le":100}}]}
     >>> httpx.get("http://127.0.0.1:18765/products", params={"category": "books"}).status_code
2    200
     test: with TestClient(app) as c: c.get("/products/999")
3    404 {"detail": "Product not found"}                              (tests/test_main.py)

Real scenario: a curl one-liner in a README; an integration check in CI that starts Uvicorn and polls /health; unit-style API tests with TestClient for every status code; async tests that measure concurrency with ASGITransport; contract tests that load /openapi.json.

ToolTalks toRuns lifespanBest for
curl -iReal server over TCPyes (server's)Manual checks, scripts, headers
httpx.get / httpx.ClientReal serveryes (server's)Python scripts, other services
TestClient(app)App in-processonly with withSync tests, fast, no ports
httpx.AsyncClient(transport=ASGITransport(app))App in-processnoAsync tests, concurrency
Swagger UI "Try it out"Real server from the browseryesExploring

Fix / how to use it: a client fixture that uses with TestClient(app) (the snippet's conftest.py), one test per status code a route can return, and a small real-server smoke test in CI. Fixtures, database fixtures and dependency overrides: Testing FastAPI.

Performance (pydantic-core, orjson, async I/O) Important ​

In plain words: FastAPI is fast for Python because the slow parts are not Python: Uvicorn can use uvloop and httptools (C), validation and, since 0.130.0, JSON serialisation run in Pydantic's Rust core, and async I/O lets one process wait on thousands of sockets. Your code and your database are almost always the bottleneck, not the framework.

Common misunderstanding: "Benchmarks say FastAPI is as fast as Go." The FastAPI docs' own claim is narrower: "Independent TechEmpower benchmarks show FastAPI applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves". On the regular CPython build the GIL lets only one thread run Python bytecode at a time (FastAPI 0.136.0 added support for the free-threaded 3.14t build), so CPU-bound work scales by processes, not threads. A second one: "Install orjson and use ORJSONResponse for speed." That was the advice until 0.131.0 deprecated ORJSONResponse/UJSONResponse, because a declared response model now serialises in Rust ("2x (or more) performance increase for JSON responses", per the 0.130.0 note).

Definition: The levers, from cheapest: declare response models (validation + fast serialisation), use async def with async drivers for I/O-bound routes, keep blocking work in def routes or off the request path, use uvicorn[standard] (uvloop, httptools), run one worker per core or more replicas, put Nginx or a CDN in front for static files and slow clients, and cache. Measure with a load tool (wrk, hey, locust) against a production-like process, not against --reload.

     where 10 ms of a typical request goes (illustrative, not measured here)
1    Uvicorn parse + ASGI dispatch           small (C parsers with uvicorn[standard])
2    parameter extraction + Pydantic         small (Rust core)
3    your code                               varies
4    database round trips                    usually the largest share
5    JSON serialisation                      small with a response model (Rust, 0.130.0+)

Real scenario: an endpoint at 80 ms where 75 ms is three sequential queries (fix: one query or asyncio.gather on an async driver); a list endpoint returning 10 000 rows (fix: pagination); a route that blocks the loop with a sync SDK (fix: def); a service that saturates one core (fix: workers or replicas).

LeverGainCost
response_model / return typeValidation + Rust serialisation (0.130.0+)None; also safer
async def + async driverMany concurrent waits per processEvery library must be async
def for blocking codeEvent loop stays freeThread pool limit (40)
uvicorn[standard]Faster loop and HTTP parserNative wheels (not PyPy/Windows for uvloop)
Workers / replicasUses all coresMemory per process; no shared memory
Pagination and indexesUsually the biggest winDesign work (Pagination)
CachingRemoves workInvalidation (Caching)

Fix / how to use it: profile before tuning, fix the data access first, and treat framework micro-optimisations as the last step.

Project layout preview Good to know ​

In plain words: One main.py is fine for a chapter or a small service. Once you have several resources, split by package: an app/ package with the app factory, one module (later one APIRouter) per feature, a settings module and a tests/ folder next to it, all described by one pyproject.toml.

Common misunderstanding: "Layout is cosmetic." It decides import cycles, how tests override dependencies, and whether uvicorn app.main:app and fastapi dev can find the app. The FastAPI docs recommend declaring the entry point in pyproject.toml ([tool.fastapi] entrypoint = "main:app"), because without it "other tools might not be able to find it, for example the VS Code Extension or FastAPI Cloud".

Definition: The snippet project already has the shape the rest of this section grows into:

1    fastapi-fundamentals-routing/
2    ├── pyproject.toml          # deps, extras (test, prod), [tool.fastapi] entrypoint, pytest config
3    ├── app/
4    │   ├── __init__.py
5    │   ├── main.py             # FastAPI(), lifespan, middleware, mounts, routes (later: include_router)
6    │   ├── db.py               # data access; later SQLAlchemy models + sessions
7    │   ├── concurrency.py      # a second, separate app used by the async/def test
8    │   └── static/hello.txt    # mounted at /static
9    └── tests/
10       ├── conftest.py         # client fixture: with TestClient(app)
11       └── test_*.py

Real scenario: a monolith that splits main.py into app/products/router.py, app/orders/router.py; a team choosing "by layer" (routers/, models/, services/) vs "by feature" (products/, orders/); settings from environment variables with pydantic-settings.

SizeLayoutChapter
1 file, < 10 routesmain.pythis one
A few resourcesapp/ package, one module per resourcethis one, then routers
Many resources, teamsAPIRouter per feature, settings, dependencies moduleAPIRouter & Project Structure
Data layerSQLAlchemy models, sessions, AlembicSQLAlchemy 2 & SQLModel, Alembic
Toolinguv, Ruff, lock filesPython Project Tooling

Fix / how to use it: start with the snippet's shape, keep the app object in app/main.py, and move to routers when one module passes a few hundred lines.

Mechanics ​

The request lifecycle, step by step Important ​

The diagram above the Running it block shows the decision points; here is the full path of one request through the snippet app, with the component that does each step.

     GET /products?category=books&limit=1  (real request, Uvicorn 0.39.0, FastAPI 0.128.8)
1    Uvicorn       accept(), parse request line + headers (httptools), build scope
2    Uvicorn       await app(scope, receive, send)
3    Starlette     ServerErrorMiddleware -> process_time middleware (yours) -> ExceptionMiddleware
4    Starlette     Router: routes in order; /products GET is a full match
5    FastAPI       APIRoute handler: read query params from scope["query_string"]
6    Pydantic      category "books" -> Category.books; limit "1" -> 1 (1 <= 1 <= 100); max_price, offset defaults
7    FastAPI       list_products is `def` -> anyio.to_thread.run_sync(list_products, ...)
8    your code     Catalog.list(...) runs LIST_SQL on SQLite in a worker thread
9    FastAPI       response_model list[ProductOut]: validate, serialise -> JSON bytes
10   Starlette     JSONResponse(status 200); middleware adds x-process-time-ms: 1.41
11   Uvicorn       send http.response.start + body; access log: "GET /products?category=books&limit=1 HTTP/1.1" 200 OK

How FastAPI reads a signature Good to know ​

At decoration time FastAPI builds a "dependant" for each path operation: for every parameter it decides the source (path if the name is in the path template; body if the type is a Pydantic model or the parameter uses Body(); query for simple types and list types wrapped in Query(); special types such as Request, Response, BackgroundTasks are injected), the type, the default and the metadata from Annotated. It also creates the Pydantic validators once, so a request does no reflection. Two consequences: unusual annotations fail at import (a clear error at startup rather than at the first request), and from __future__ import annotations works because the annotation strings are resolved then (on Python 3.9 X | None needs eval-type-backport; without it the snippet run raised TypeError: Unable to evaluate type annotation 'Annotated[str | None, Query(max_length=3)]').

Parameter looks likeFastAPI reads it from
Name appears in the path templatePath
int, str, bool, float, Enum, UUID, date …Query
list[str] with Query()Query, repeated key
Pydantic modelJSON body
Annotated[..., Header()] / Cookie() / Form() / File()Header / cookie / form field / upload
Request, Response, WebSocket, BackgroundTasksInjected objects
Annotated[..., Depends(fn)]Result of fn (its own parameters are read the same way)

Exact errors, warnings and log lines Must-know ​

Every line below was printed by the snippet run (FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, Uvicorn 0.39.0, gunicorn 23.0.0, uvicorn-worker 0.4.0).

TriggerStatusExact output
GET /products/abc422{"type":"int_parsing","loc":["path","product_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"abc"}
GET /products?limit=500422{"type":"less_than_equal","loc":["query","limit"],"msg":"Input should be less than or equal to 100","input":"500","ctx":{"le":100}}
GET /products?max_price=-1422{"type":"greater_than_equal",...,"msg":"Input should be greater than or equal to 0","input":"-1","ctx":{"ge":0}}
?short=maybe on short: bool422{"type":"bool_parsing",...,"msg":"Input should be a valid boolean, unable to interpret input","input":"maybe"}
GET /categories/toys422{"type":"enum",...,"msg":"Input should be 'books', 'games' or 'music'","input":"toys","ctx":{"expected":"'books', 'games' or 'music'"}}
Required query param absent422"type":"missing"
Truncated JSON body {"name":"x"422{"type":"json_invalid","loc":["body",11],"msg":"JSON decode error","input":{},"ctx":{"error":"Expecting ',' delimiter"}}
Unknown path404{"detail":"Not Found"}
PUT /products/1405{"detail":"Method Not Allowed"}, allow: GET
HEAD /health (GET-only APIRoute)405(asserted in test_main.py)
?limit=abc in the Before app (ValueError)500Internal Server Error (text/plain, asserted in test_before.py)
GET /products/307location: http://testserver/products
status.HTTP_422_UNPROCESSABLE_ENTITY—DeprecationWarning: 'HTTP_422_UNPROCESSABLE_ENTITY' is deprecated. Use 'HTTP_422_UNPROCESSABLE_CONTENT' instead.
Uvicorn access log for a 422—INFO: 127.0.0.1:61032 - "GET /products?limit=500 HTTP/1.1" 422 Unprocessable Entity
Gunicorn with uvicorn_worker—[INFO] Using worker: uvicorn_worker.UvicornWorker
Python 3.9 + str | None without the backportimport errorTypeError: Unable to evaluate type annotation ... install the eval_type_backport package.

What the docs pages load Good to know ​

The HTML that FastAPI 0.128.8 returns for /docs references https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js and swagger-ui.css; /redoc references https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js and Google Fonts (read from the real responses). Offline or locked-down deployments therefore see blank docs pages unless they self-host those files and build the pages with get_swagger_ui_html / get_redoc_html.

Solving the classic problems ​

BugSymptomFixCost
Parameters read from request.query_params by hand?limit=abc → 500; nothing in /docsTyped parameters + Query()None
Errors returned as {"error": ...}Status 200 on failures, caches store errorsraise HTTPException(404, ...)None
POST answers 200Clients cannot tell create from updatestatus_code=status.HTTP_201_CREATED + LocationOne argument
Literal path after a parameter path/users/me → "user me not found"Declare literal paths first; test themOrdering
Blocking call in async defLatency spikes for every route; 5 × 200 ms = 1.05 sdef, or async library, or run_in_threadpoolSmall
Startup in @app.on_eventDeprecation warnings; ignored once lifespan is addedFastAPI(lifespan=...)10 lines
Module-level connectionTests open real connections at import; no cleanupOpen in lifespan, close after yield10 lines
No response modelInternal fields (hashes, flags) leak; slower serialisationresponse_model= or return typeOne model
Optional[...] without default"Optional" parameter is required (422 missing)= NoneNone
Duplicated routeSecond function never runs, silentlyOne route per method+path; a test that lists routesReview
Docs public in productionAttack surface map, accidental "Try it out" on proddocs_url=None, redoc_url=None or auth in frontConfig
--reload in productionFile watcher, single process--workers or one process per containerConfig
State in process memory with workersCounters and caches differ per workerPostgreSQL / RedisInfra

Typed inputs instead of hand parsing ​

The difference between Before and After is the whole lesson: every value that comes from the URL is declared once, with a type and bounds, and arrives converted. The SQL in app/db.py receives an int for limit and a validated enum value for category; the 422 is produced before the database is touched. When the same filter set appears on several endpoints, move it into a Pydantic query model (Request Validation).

Correct status codes for every outcome ​

Write the success code on the decorator, raise HTTPException for expected failures and let bugs be 500s. The snippet's tests enumerate them per route (200, 201, 204, 307, 404, 405, 422); a route without such a test usually has at least one wrong code. Map domain errors (not found, conflict, forbidden) to statuses in one exception handler once there are more than a handful.

Keeping the event loop free ​

Audit every async def for blocking calls: requests, time.sleep, sync database drivers, open() on network file systems, CPU-heavy loops. Either switch the route to def, switch the library to its async version (httpx.AsyncClient, asyncpg, SQLAlchemy AsyncSession), or wrap the call (await run_in_threadpool(fn, ...)). Uvicorn's --limit-concurrency gives a 503 instead of an unbounded queue when the process is saturated. Measuring it is the concurrency test.

Docs that a client generator can trust ​

Tags with descriptions, function names as operationId, response models everywhere, responses={404: ...} where a 404 is possible, deprecated routes marked, internal routes hidden. Commit or archive /openapi.json from CI and diff it on every pull request; a removed field or a changed operationId is a breaking change for generated clients.

Choosing ​

SituationUseExtra techniqueReason
Route calls only async librariesasync defasyncio.gather for parallel awaitsMany concurrent waits per process
Route calls a blocking librarydefSize the DB pool ≥ busy threadsThread pool keeps the loop free
Fixed set of path valuesEnum (string enum)Same enum in DB CHECKValidation + docs dropdown
Value may be absentQuery parameter with = NoneNot a path parameterPath params are always required
Many filtersQuery model (Annotated[Model, Query()])Request ValidationOne place for rules
Create@app.post(..., status_code=201)Location headerClients know it was created
Deletestatus_code=204, return None404 when missingNo body by definition
Not foundraise HTTPException(404, ...)Domain exception + handler laterStops at any depth
Startup/shutdown resourceslifespanapp.state + dependencyOne place, per process
Cross-cutting per requestMiddlewareKeep it cheapSees 404/422 too
Per-route policy (auth)DependencyDependsTyped and documented
Public API docs/docs + /redocTags, descriptions, examplesSelf-serve integration
Private serviceopenapi_url kept for CI, UIs offGateway authLess exposure
Developmentfastapi dev / uvicorn --reload[tool.fastapi] entrypointFast feedback
VM productiongunicorn -k uvicorn_worker.UvicornWorker or uvicorn --workersNginx in frontCores + process supervision
KubernetesOne Uvicorn process per podReplicas + HPAThe orchestrator replicates

When FastAPI vs Django/Flask/Go ​

NeedFastAPIDjango (+ DRF / Ninja)FlaskGo net/http
JSON API with typed inputs and OpenAPIBuilt inDRF serializers, drf-spectacular; Ninja is FastAPI-likeExtensionsBy hand or code generation
Admin, ORM, auth, migrations includedNo (pick SQLAlchemy/SQLModel, Alembic)Yes, batteries includedNoNo
Async I/O, WebSockets, SSENative (ASGI)ASGI support, sync ORM coreMostly sync (WSGI)Goroutines
Server-rendered HTML sitesPossible (Jinja2)StrongestGoodhtml/template
ML / data stack in PythonNatural fitPossiblePossibleSeparate service
CPU-heavy, low-latency, small memoryProcesses per coreSameSameBest of the four
Single static binary deployNoNoNoYes
Learning curve for a typed APILow if you know type hintsMedium–highLowLow–medium

FastAPI's own "Alternatives" page describes Flask as a "microframework" that "doesn't include database integrations nor many of the things that come by default in Django", and Django REST Framework as "a flexible toolkit for building Web APIs using Django underneath"; FastAPI took ideas from both. The Go column is unpacked in The Go angle.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One app = FastAPI(...) in app/main.py, run by Uvicorn, with one database pool opened in the lifespan and all routes in one route table. This chapter's snippet is that shape with SQLite; the production version swaps the database for PostgreSQL and the in-memory connection for a pool. Example: a shop backend with GET /products, GET /products/{id}, POST /cart/items, POST /checkout; static assets from Nginx; one httpx.AsyncClient to the payment provider created in the lifespan; /docs available on the internal network only.

Modular monolith and multiple databases ​

Still one process, but each module (catalog, orders, payments) owns its routes in its own APIRouter, its own tag in the docs and its own data access. Route order matters across modules (include_router order is registration order), and the OpenAPI schema becomes the module map. A second database (Redis for sessions, a search index) gets its own client in the lifespan; modules talk through Python calls, not HTTP. Mounts are for genuinely separate apps (a legacy WSGI admin wrapped as ASGI, a metrics exporter), not for modules, because a mount has its own docs and does not get the parent's lifespan.

Microservices ​

Every service is a FastAPI app with its own OpenAPI document, and the documents become contracts: a consumer generates its client from the producer's /openapi.json, and CI breaks if a field disappears. Stable operationIds and response models are what make that work. Example flow: POST /orders on the orders service → GET http://catalog/products/{id} (async httpx, 300 ms budget) → POST http://payments/charges with an Idempotency-Key header → 201 with Location. What does not survive the hop: Pydantic validation on the other side (each service validates its own inputs), the request's middleware stack, and in-process state. Status codes must be mapped deliberately: a 422 from the catalog service is your 502 or 409, not a 422 to your client. Contract and idempotency design: API Idempotency.

Distributed data: replicas, caches, sharded databases, multi-region ​

With several workers or replicas, anything kept in the Python process is per process: an in-memory cache, a rate-limit counter, an app.state dictionary, the snippet's :memory: database. The Gunicorn run above started two workers, and each ran its own lifespan and would have held its own copy. Shared state moves to PostgreSQL, Redis or a dedicated cache, reached through clients opened in the lifespan. Reads from replicas need explicit read-your-writes handling (a write followed by a GET may hit a lagging replica); responses that can be cached need Cache-Control/ETag headers you set yourself, because FastAPI sets none on JSON. Replica lag and caching patterns: Caching.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesFastAPI practice
1× (one process)Defaults seem fineTyped params, response models, correct codes, lifespan, tests with TestClient; no blocking calls in async def
10× (several workers or replicas behind a load balancer)Per-process state diverges; deploys drop requestsWorkers ≈ cores or one process per pod; shared state in Redis/PostgreSQL; --proxy-headers; graceful shutdown; pool sizes × workers ≤ database limit
100× (many services, high fan-out)Tail latency, thread-pool exhaustion, schema driftAsync drivers end to end; --limit-concurrency for load shedding; OpenAPI contracts in CI; caching and CDNs; move CPU work to job queues (Load Shedding)

Lab ​

All commands run from docs/snippets/python/fastapi-fundamentals-routing/. The outputs marked "real" were produced on CPython 3.9.6 (macOS) with the pinned versions; on Python 3.12 with the latest releases the outputs are the same apart from version numbers and the fixes noted on this page.

1. Install and run the tests (real) ​

python3 -m venv ~/venvs/ffr                      # keep the venv outside the repo: .venv/ and *.egg-info
~/venvs/ffr/bin/pip install -e '.[test,prod,dev]'  # are not git-ignored; dev = fastapi[standard] (fastapi-cli)
source ~/venvs/ffr/bin/activate                    # every later step assumes this venv is active
export PYTHONDONTWRITEBYTECODE=1                   # no __pycache__; pyproject sets -p no:cacheprovider
pytest -s
# ...../blocking-async: 5 requests in 1.05s on {'MainThread'}
# ./sync: 5 requests in 0.21s on {'AnyIO worker thread'}
# ./async: 5 requests in 0.21s on {'MainThread'}
# ......................
# 29 passed in 1.57s

In every new terminal used in steps 2–5, run source ~/venvs/ffr/bin/activate first (or call ~/venvs/ffr/bin/uvicorn, ~/venvs/ffr/bin/pytest, ~/venvs/ffr/bin/gunicorn, ~/venvs/ffr/bin/fastapi explicitly). The resolved versions of that install are saved as requirements.lock next to the run logs; pip install -r requirements.lock reproduces it. The output above is the verbatim output of a fresh venv with the project installed from its own pyproject.toml (-q is set in the pytest options, so the dots are per test; -s lets the concurrency test print its timings). A second run printed 1.03 s / 0.22 s / 0.21 s.

With uv on Python 3.12+: uv run --extra test pytest -s (expected, not run: uv is not installed on the build machine).

2. Start Uvicorn and call it with curl (real) ​

uvicorn app.main:app --port 18765
curl -i "http://127.0.0.1:18765/products?category=books&limit=1"
# HTTP/1.1 200 OK
# server: uvicorn
# content-type: application/json
# x-process-time-ms: 1.41
# [{"id":1,"name":"The Pragmatic Programmer","category":"books","price_cents":4200}]
curl -s "http://127.0.0.1:18765/products?limit=500"
# {"detail":[{"type":"less_than_equal","loc":["query","limit"],"msg":"Input should be less than or equal to 100","input":"500","ctx":{"le":100}}]}
curl -s -i -X POST http://127.0.0.1:18765/products -H 'Content-Type: application/json' \
     -d '{"name":"Catan","category":"games","price_cents":4500}'
# HTTP/1.1 201 Created
# location: /products/6
# {"id":6,"name":"Catan","category":"games","price_cents":4500}
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:18765/products/999
# 404
curl -s http://127.0.0.1:18765/openapi.json | head -c 80
# {"openapi":"3.1.0","info":{"title":"Catalog API","summary":"The pilot app of the

Open http://127.0.0.1:18765/docs and /redoc in a browser: the products, categories and legacy tags appear in the openapi_tags order, GET /v1/products/{product_id} is struck through, and /health and /static are absent.

3. Route order and 405 (real) ​

pytest -k "fixed_path or wrong_method or trailing_slash" -v
# collected 29 items / 26 deselected / 3 selected
# tests/test_main.py ...                                                   [100%]
# 3 passed, 26 deselected in 0.03s

The three tests assert: /products/featured returns ids [1, 2, 5]; PUT /products/1 is 405 with allow: GET; /products/ is a 307 to /products. Then move the featured_products route below get_product in a copy of app/main.py and rerun (real, done in a scratch copy):

pytest -k fixed_path
# >       assert r.status_code == 200
# E       assert 422 == 200            <- "featured" was matched by /products/{product_id} and failed int parsing
# 1 failed, 27 deselected in 0.05s      (run before the HEAD test was added: 28 tests then)

4. Workers and Gunicorn (real) ​

uvicorn app.main:app --port 18766 --workers 2
# INFO:     Started parent process [4011]
# INFO:     Started server process [4014]
# INFO:     Started server process [4015]
# INFO:     Application startup complete.        <- twice: one lifespan per worker
gunicorn app.main:app      # from the prod extra installed in step 1 -w 2 -k uvicorn_worker.UvicornWorker -b 127.0.0.1:18767
# [INFO] Starting gunicorn 23.0.0
# [INFO] Using worker: uvicorn_worker.UvicornWorker
# [INFO] Booting worker with pid: 4039
# [INFO] Booting worker with pid: 4040
# ... SIGTERM:
# [INFO] Handling signal: term
# [4039] [INFO] Application shutdown complete.

5. Reload in development (real start; the file-change step expected, not run) ​

fastapi dev --port 18770                             # fastapi-cli 0.0.22 from the dev extra (real)
#   app   Using import string: app.main:app
#   server   Server started at http://127.0.0.1:18770
#   server   Documentation at http://127.0.0.1:18770/docs
#   tip   Running in development mode, for production use: fastapi run
#   INFO   Started reloader process [14504] using WatchFiles
uvicorn app.main:app --port 18768 --reload          # the same through Uvicorn directly (real)
# INFO:     Will watch for changes in these directories: ['.../fastapi-fundamentals-routing']
# INFO:     Uvicorn running on http://127.0.0.1:18768 (Press CTRL+C to quit)
# INFO:     Started reloader process [10920] using WatchFiles
# INFO:     Started server process [10923]
# (edit app/main.py and save; expected: "WatchFiles detected changes in 'app/main.py'. Reloading...")
uvicorn app.main:app --port 18769 --reload --workers 2
# WARNING:  "workers" flag is ignored when reloading is enabled.      <- real: a warning, not an error
# INFO:     Started reloader process [10939] using WatchFiles

For PHP/Laravel developers ​

The biggest shift is the process model. Under PHP-FPM each request starts from a clean slate, so there is no event loop to block, no lifespan and no per-process state to worry about; a FastAPI process lives for days, serves many requests concurrently on one event loop, and keeps whatever you open in the lifespan. The closest Laravel analogue is Octane, which "supercharges your application's performance by serving your application using high-powered application servers, including FrankenPHP, Open Swoole, Swoole, and RoadRunner" and brings the same long-lived-process rules (no request data in singletons, workers do not share memory). Routing maps closely: Laravel's docs say "Route parameters are always encased within {} braces", like FastAPI's path templates, but Laravel injects them "based on their order - the names of the route callback / controller arguments do not matter", while FastAPI matches them by name and converts them by type. ->whereNumber('id') is what product_id: int does, with the difference that a failed Laravel constraint is a 404 (the route does not match) and a failed FastAPI conversion is a 422. Validation errors are 422 in both: Laravel "will automatically format the error messages for you and return a 422 Unprocessable Entity HTTP response". Laravel has no built-in OpenAPI generator; FastAPI's docs are what third-party packages add: Scramble describes itself as a "Laravel API documentation generator", L5-Swagger as "OpenApi or Swagger Specification for your Laravel project made easy". findOrFail throws Illuminate\Database\Eloquent\ModelNotFoundException, and "If the ModelNotFoundException is not caught, a 404 HTTP response is automatically sent back to the client"; API resources "extend the Illuminate\Http\Resources\Json\JsonResource class".

php
// routes/api.php (Laravel 13), the FastAPI catalog in Laravel terms
Route::get('/products/featured', [ProductController::class, 'featured']);            // declare before {id}, as in FastAPI
Route::get('/products/{id}', [ProductController::class, 'show'])->whereNumber('id'); // product_id: int (but a miss is 404, not 422)
Route::post('/products', [ProductController::class, 'store']);                       // status_code=201 is set in the controller

// app/Http/Controllers/ProductController.php
class ProductController extends Controller
{
    public function show(int $id) { return Product::findOrFail($id); }                // HTTPException(404) via ModelNotFoundException
    public function store(Request $request)
    {
        $data = $request->validate(['name' => 'required|string|min:1|max:120',          // ProductIn; 422 on failure
                                    'category' => 'required|in:books,games,music',
                                    'price_cents' => 'required|integer|min:0']);
        $p = Product::create($data);
        return response()->json($p, 201)->header('Location', "/products/{$p->id}");
    }
}
Laravel / PHPFastAPI
Route::get('/products/{id}', ...)@app.get("/products/{product_id}")
->whereNumber('id') (no match → 404)product_id: Annotated[int, Path(ge=1)] (bad value → 422)
$request->query('limit', 20)limit: Annotated[int, Query(ge=1, le=100)] = 20
$request->validate([...]) → 422Pydantic model parameter → 422 (RequestValidationError)
response()->json($p, 201)status_code=status.HTTP_201_CREATED + response_model
abort(404) / findOrFailraise HTTPException(404, ...)
API Resources (JsonResource)response_model filtering
php artisan route:list/openapi.json, /docs
Scramble / L5-Swagger packagesBuilt-in OpenAPI, Swagger UI, ReDoc
Service provider boot()lifespan (before yield)
Middleware in bootstrap/app.phpapp.add_middleware / @app.middleware("http")
PHP-FPM workers / Octane workersUvicorn or Gunicorn workers
php artisan servefastapi dev / uvicorn --reload
$this->getJson('/products/1') in testsTestClient(app).get("/products/1")

The Go angle ​

The Go twin of this chapter is net/http: Server, Client, 1.22 Routing. Since Go 1.22 ("The patterns used by net/http.ServeMux have been enhanced to accept methods and wildcards", per the release notes), the route table looks almost the same, but three rules differ; the ServeMux doc comment in server.go states them: "the most specific pattern takes precedence", conflicting registrations panic, and a pattern "with the method GET matches both GET and HEAD requests". Precedence: Go picks the most specific pattern regardless of order and panics at registration on ambiguous overlaps, while FastAPI takes the first match in order and silently accepts duplicates. Conversion and validation: r.PathValue("id") is always a string; you call strconv.ParseInt and write the 400/422 yourself, which FastAPI derives from the annotation. 405 and HEAD: Go answers 405 with an Allow header for every method registered on the path and lets GET patterns match HEAD; FastAPI lists only the first partial match and answers HEAD with 405 unless you register it. The concurrency model is the mirror image of this page's async-vs-def rule: Go handlers are ordinary blocking code on goroutines, so there is no "blocking the loop" mistake to make, and a single process uses every core. OpenAPI is not built in: Go services either write the spec first and generate code (oapi-codegen, ogen) or annotate handlers (swaggo), as in A REST API in Go.

go
// Go 1.22+: the same three catalog routes as app/main.py
mux := http.NewServeMux()
mux.HandleFunc("GET /products/featured", featured) // order does not matter: literal beats {id}
mux.HandleFunc("GET /products/{id}", func(w http.ResponseWriter, r *http.Request) {
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) // FastAPI: product_id: int
	if err != nil || id < 1 {                               // FastAPI: Path(ge=1) -> 422
		http.Error(w, `{"detail":"invalid id"}`, http.StatusUnprocessableEntity)
		return
	}
	p, ok := catalog.Get(r.Context(), id)
	if !ok {
		http.Error(w, `{"detail":"Product not found"}`, http.StatusNotFound) // HTTPException(404)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(p) // response_model: you choose the struct fields
})
mux.HandleFunc("POST /products", create) // writes 201 + Location itself
srv := &http.Server{Addr: ":8000", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
log.Fatal(srv.ListenAndServe())
ConcernFastAPIGo net/http (1.22+)
Route syntax@app.get("/products/{product_id}")mux.HandleFunc("GET /products/{id}", h)
Which route winsFirst registeredMost specific; conflicts panic
Path valueTyped argumentr.PathValue("id") string
Query valueTyped argument with defaultr.URL.Query().Get("limit") string
Validation errorsAutomatic 422 listHand-written
HEAD on GET routes405 unless registeredMatched by GET patterns
ConcurrencyEvent loop + thread pool; processes for coresGoroutine per connection; all cores
OpenAPIGeneratedSpec-first codegen or annotations
Startup/shutdownlifespanmain() + srv.Shutdown(ctx)
ServerUvicorn (separate)The binary is the server

Common misconceptions ​

BeliefReality
async def makes a route fasterOnly if everything inside awaits; blocking calls inside it freeze the loop (1.05 s vs 0.21 s measured)
def routes are legacyThey are the right choice for blocking libraries; they run in the thread pool
The thread pool is unlimited40 tokens by default, shared with sync dependencies and file responses
FastAPI is the serverUvicorn (or another ASGI server) is; FastAPI is the app
The most specific route winsThe first registered route wins; duplicates are silently ignored
Optional[str] makes a parameter optionalThe default does; without = None it is required
A path parameter can be optionalNever; it is part of the URL
422 means my code crashedIt means the request failed validation before your code ran; crashes are 500
FastAPI stops at the first validation errorIt reports every error in one detail list
Malformed JSON is a 400It is a 422 with json_invalid
return HTTPException(...) sends an errorYou must raise it
status_code= sets the error statusIt is the success status; errors come from exceptions
@app.get also serves HEADAPIRoute answers HEAD with 405 unless you add it
405 lists every allowed methodIt lists the methods of the first partially matching route
include_in_schema=False protects a routeIt only hides it from the docs
deprecated=True disables a routeIt still works; docs strike it through
Lifespan runs in every TestClientOnly inside with TestClient(app)
Workers share app.stateEach worker is a process with its own state and its own lifespan
--reload --workers 4 gives four reloading workersUvicorn 0.39.0 warns that workers is ignored and runs one process
Mounted apps get the parent's docs and lifespanThey are independent: no OpenAPI entries, no lifespan by default
ORJSONResponse is the fast pathDeprecated since 0.131.0; a response model serialises in Rust since 0.130.0

Cheat sheet ​

TopicRemember
StackUvicorn (server) → ASGI → FastAPI(Starlette) → Pydantic
Appapp = FastAPI(title=..., version=..., lifespan=..., openapi_tags=...)
Route@app.get("/products/{product_id}") + typed function
OrderLiteral paths before parameter paths; first match wins
Path paramsAlways required; Annotated[int, Path(ge=1)]; {p:path} for slashes
Query paramsNo default = required; = None = optional; list needs Query()
Enumclass Category(str, Enum) / StrEnum (3.11+)
Validation422, detail: [{type, loc, msg, input, ctx}], all errors at once
Statusstatus_code=status.HTTP_201_CREATED on the decorator; 204 returns nothing
Errorsraise HTTPException(404, detail=...)
Outputresponse_model filters and documents; fastest serialisation path
async vs defAwait-only → async def; blocking → def (thread pool, 40 tokens)
Docs/openapi.json (3.1.0), /docs Swagger UI, /redoc ReDoc; None disables
Metadatatags, summary, docstring, operation_id, deprecated, include_in_schema
Lifespan@asynccontextmanager with yield; per process; with TestClient
MiddlewareLast added = outermost; sees 404/422; 500s come from outside it
Rundev: --reload; VM: --workers N or Gunicorn + uvicorn_worker; k8s: 1 process per pod
Testwith TestClient(app) as c:; async: httpx.ASGITransport

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What are Uvicorn, Starlette and FastAPI each responsible for when a request arrives? Must-know ​

Answer

Answer: Uvicorn is the ASGI server: it owns the socket, parses HTTP, runs the event loop and calls the app as await app(scope, receive, send). Starlette is the toolkit FastAPI inherits from: middleware stack, router, request/response classes, StaticFiles, exception middleware. FastAPI adds signature analysis, parameter extraction, Pydantic validation (422), response_model and OpenAPI generation. See ASGI, Starlette and Uvicorn.

2 — You register GET /users/{user_id} and then GET /users/me. What does GET /users/me do, and how do you fix it? Must-know ​

Answer

Answer: The first route matches, because FastAPI/Starlette evaluate routes in registration order; "me" is passed as user_id (or, with user_id: int, the request fails with 422 int_parsing). Declare /users/me first. There is no specificity rule like Go 1.22's ServeMux, and duplicate registrations are silently ignored. See Route order.

3 — When do you write async def and when def for a path operation, and what happens to each? Must-know ​

Answer

Answer: async def runs on the event loop and must only wait with await (async drivers, httpx.AsyncClient). def is run in an external thread pool (AnyIO, 40 tokens by default) and may block. A blocking call inside async def stops the loop for every request: in the lab five 200 ms requests took 1.05 s instead of 0.21 s. If you do not know, the FastAPI docs say use def. See async def vs def routes.

4 — q: Optional[str] with no default: is q required? What about q: str | None = None? Must-know ​

Answer

Answer: The first is required: a request without q gets 422 with "type": "missing", because the default decides optionality, not the type. The second is optional and is None when absent. Path parameters can never be optional at all. See Query parameters.

5 — What does a 422 response from FastAPI contain, and which exception produces it? Must-know ​

Answer

Answer: RequestValidationError, raised before your function runs; the default handler answers 422 with {"detail": [...]}, one entry per error with type (Pydantic code such as int_parsing, less_than_equal, missing, json_invalid), loc (for example ["query", "limit"]), msg, input and often ctx. All errors are reported at once. RFC 9110 names 422 "Unprocessable Content"; Uvicorn logs it as "Unprocessable Entity". See Validation errors.

6 — How do you return 201 with a Location header from a create endpoint, and 204 from a delete? Important ​

Answer

Answer: Put status_code=status.HTTP_201_CREATED on the @app.post decorator, take a response: Response parameter and set response.headers["Location"]; return the created object through a response_model. For delete, status_code=status.HTTP_204_NO_CONTENT and return None; the body is empty and OpenAPI documents "no body". status_code belongs to the decorator, not the function. See status_code and the status module.

7 — Your function returns a dict containing password_hash. The decorator has response_model=UserOut without that field. What does the client receive? Important ​

Answer

Answer: The response without password_hash: FastAPI validates the return value against the response model and filters out every field that is not declared, without an error. That filtering is the security reason to always declare an output model, and since 0.130.0 it is also the fast JSON path (serialisation in Pydantic's Rust core). See JSON response and response_model.

8 — Why does PUT /products/1 return Allow: GET even though DELETE /products/{product_id} exists, and why does HEAD /health return 405? Important ​

Answer

Answer: Starlette's router remembers the first route whose path matched but whose method did not, and the 405 response lists that route's methods only. FastAPI's APIRoute does not add HEAD to GET routes (Starlette's plain Route and Go's ServeMux do), so HEAD needs @app.api_route(..., methods=["GET", "HEAD"]). Both behaviours were confirmed in the snippet run. See Route order and Path operations.

9 — What is the lifespan, when does it run, and what changes with --workers 4? Important ​

Answer

Answer: An async context manager passed as FastAPI(lifespan=...): code before yield runs once before the process accepts requests, code after yield once after it stops. It replaces the deprecated on_event hooks (which are ignored when a lifespan is set). With four workers it runs four times, once per process, and each process has its own app.state. TestClient runs it only inside with. See Lifespan.

10 — How do you run a FastAPI app in development, on a VM and on Kubernetes? Important ​

Answer

Answer: Development: fastapi dev or uvicorn app.main:app --reload (one process, restarted on change; --reload and --workers are mutually exclusive). VM: uvicorn app.main:app --workers N or gunicorn app.main:app -w N -k uvicorn_worker.UvicornWorker (the old uvicorn.workers module is deprecated). Kubernetes: one Uvicorn process per container and scale replicas, as the FastAPI docs advise. See Running it.

11 — What do /docs, /redoc and /openapi.json serve, and how do you turn them off? Good to know ​

Answer

Answer: /openapi.json is the OpenAPI 3.1.0 schema generated from the routes; /docs is Swagger UI (interactive, "Try it out"), /redoc is ReDoc (three-panel reference); both are HTML pages that load their JavaScript from a CDN and render the schema. docs_url=None or redoc_url=None disables one UI; openapi_url=None disables the schema and both UIs. Hiding docs is not access control. See OpenAPI, Swagger UI, ReDoc.

12 — Where does your @app.middleware("http") sit, and why can it miss headers on a 500? Good to know ​

Answer

Answer: Between Starlette's ServerErrorMiddleware (always outermost) and ExceptionMiddleware (around the router). It therefore sees 404, 405, 422 and HTTPException responses, but an unhandled exception escapes it and is turned into a 500 by the outer layer, after your middleware has been skipped. With several middlewares the last added is the outermost. See Middleware position.

Glossary ​

TermMeaning
ASGIAsynchronous Server Gateway Interface: async app(scope, receive, send), the successor of WSGI
WSGIThe older synchronous Python server/app interface (PEP 3333)
ScopeASGI dict describing one connection (for HTTP: one request): method, path, query string, headers
receive / sendASGI awaitables to read request events and write response events
UvicornASGI server used by FastAPI's CLI; uvicorn[standard] adds uvloop, httptools, watchfiles
StarletteASGI toolkit FastAPI subclasses: routing, middleware, responses, StaticFiles, TestClient
FastAPIclass FastAPI(Starlette) that builds routes, validation and OpenAPI from type hints
FastAPI()The application object: route table, middleware, handlers, OpenAPI metadata, lifespan
PydanticValidation and serialisation library; v2 core (pydantic-core) is written in Rust
pydantic-corePydantic's Rust engine that validates and, in FastAPI 0.130.0+, serialises responses
Event loopThe single scheduler thread that runs coroutines; blocking it stalls every request
CoroutineAn async def function's running instance; pauses at await
Thread poolAnyIO worker threads (40 tokens default) that run def routes and sync dependencies
anyio.to_thread.run_syncThe call Starlette uses to run sync code in the pool; run_in_threadpool wraps it
Path operationA path plus an HTTP method handled by one function
Path operation decorator@app.get, @app.post, @app.put, @app.patch, @app.delete, @app.api_route
HTTP methodsGET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE: the "operations" of OpenAPI
Route orderRule that the first registered matching route handles the request
Path parameter{name} in the path template, always required, converted by type
Path convertorStarlette syntax {name:path} (also int, float, uuid)
Type conversionPydantic turning the URL string into the annotated type, or a 422
Enum path paramsAn Enum (string enum) annotation that restricts and documents allowed values
StrEnumPython 3.11+ enum whose members are strings
Query parameterFunction parameter not in the path; read from the query string
Default valuesThe Python default that makes a non-path parameter optional
Optionaltyping.Optional[X] = X | None; allows None, does not by itself make a parameter optional
Annotatedtyping.Annotated[T, meta] (PEP 593); how FastAPI attaches Query(), Path(), Depends()
Query() / Path()Parameter classes carrying constraints (ge, le, max_length, pattern), alias, docs
Validation errorsThe detail list in a 422: type, loc, msg, input, ctx
RequestValidationErrorException FastAPI raises when the request does not match the signature
422 Unprocessable EntityRFC 4918 name of 422; RFC 9110 renames it "Unprocessable Content"
status_codeDecorator argument: the success status of the operation
status modulefastapi.status constants such as HTTP_201_CREATED, HTTP_422_UNPROCESSABLE_CONTENT
response_modelOutput model: validates, filters and documents the response
JSON responseJSONResponse, the default response class; bytes produced by Pydantic or jsonable_encoder
HTTPExceptionException carrying a status, detail and optional headers; raised, not returned
404 / 405Not Found (no route or no resource) / Method Not Allowed (path matched, method did not)
redirect_slashesFastAPI() option answering 307 when only the trailing slash differs
MountAn independent ASGI sub-application attached under a path prefix
StaticFilesStarlette ASGI app serving files from a directory or package
OpenAPILanguage-agnostic description format for HTTP APIs; FastAPI emits 3.1.0
JSON SchemaThe schema language OpenAPI 3.1 uses for request and response bodies
Swagger UIInteractive OpenAPI renderer served at /docs
ReDocThree-panel OpenAPI reference renderer served at /redoc
/openapi.jsonThe generated schema URL (openapi_url)
TagsOperation groups in the docs; described with openapi_tags
summary / descriptionOperation title / long text (docstring, Markdown)
operationIdUnique operation identifier; generated-client method name
generate_unique_id_functionFastAPI() hook that computes every operationId
deprecatedOpenAPI flag; route still works, docs strike it through
include_in_schemaFalse hides a route from the schema (not from callers)
LifespanAsync context manager run at startup and shutdown of each process
Startup and shutdownThe two ASGI lifespan events; on_event hooks are the deprecated form
App lifecycleImport → route registration → lifespan startup → serving → lifespan shutdown
Request lifecycleServer → middleware → router → extraction → validation → function → response model → middleware → server
MiddlewareLayer around the whole app; last added is outermost
ServerErrorMiddleware / ExceptionMiddlewareStarlette's outermost 500 layer / innermost handler layer for HTTPException and 422
uvicorn --reloadDevelopment mode: reloader process restarts the server on file changes
WorkersSeparate server processes (--workers N), each with its own loop and state
GunicornProcess manager; with -k uvicorn_worker.UvicornWorker it runs Uvicorn workers
uvicorn-workerPackage providing UvicornWorker for Gunicorn (replaces the deprecated uvicorn.workers)
fastapi-cliThe fastapi dev / fastapi run commands, included in fastapi[standard]
curlCommand-line HTTP client used in the lab
httpxPython HTTP client (sync and async); ASGITransport calls an app in-process
TestClientStarlette/FastAPI test client built on httpx; runs lifespan inside with
pytestTest runner used by the snippet project
orjsonFast JSON library; ORJSONResponse is deprecated since FastAPI 0.131.0
uvloop / httptoolsFaster event loop / HTTP parser Uvicorn uses with uvicorn[standard]
SQLAlchemy / SQLModel / AlembicThe ORM, the Pydantic-flavoured ORM layer and the migration tool of later chapters
eval-type-backportPackage letting Pydantic evaluate X | None annotations on Python 3.9

References ​

Built by Morteza Negahi