SERVER · ASGI · ROUTES · MIDDLEWARE · VALIDATION · ENDPOINTS · DEPENDENCIES · DOCS · THREADS · WORKERS

FastAPI:
how Uvicorn, Starlette and Pydantic fit together

FastAPI is a Python framework for building web APIs, and it sits on top of three other libraries. Uvicorn talks to the network, Starlette routes each request, Pydantic checks the data, and FastAPI reads your function’s type hints to join them.

A small bookshop sells through a JSON API. Customers list books, look one up by its number, and order one to ten copies; the API saves each order in SQLite and emails a confirmation. Partners call it with an API key, and in production it runs as four processes behind a load balancer. Each chapter adds the piece of the stack that one of those jobs needs.

Here is the whole service. Most boxes won’t mean much yet; each chapter explains one of them.

MapSolid outlines are processes and the app; dashed bands group what each library provides. Lines show what is attached to what.

You need to know Python functions, classes, type hints and async def, and what an HTTP request is; no web framework experience is assumed. The tutorial teaches FastAPI 0.165.0, Starlette 1.10.0, Uvicorn 0.54.0 and Pydantic 2.14.4, checked against their source on 27 November 2026. The bookshop and its numbers are illustrative; every default and error message comes from the libraries. Tap any figure to open it full screen and zoom. Dotted terms are tappable.

From a socket to a function call: Uvicorn

You have a Python function that should answer GET /books/42 with the book as JSON. A browser or curl sends bytes to port 8000, and nothing in Python is listening yet. Something has to accept the connection, read an HTTP request out of the bytes, call your function and write its answer back. That program is an ASGI server, and Uvicorn is the one FastAPI uses. What turns bytes arriving on port 8000 into a call to your Python code?

STEP 01 / 04

THE MAP SO FAR

Fig 1.1The accent parts are new: the socket, HTTP parser and event loop. Faint parts arrive in later chapters.

The program you start is one process running Uvicorn, an ASGI server. Inside it a socket listens on 127.0.0.1:8000 and accepts TCP connections, an HTTP parser reads each request out of the bytes, and an event loop runs every request on one thread, one task per request.

The event loop is asyncio’s scheduler; the async Python tutorial explains how one thread runs many tasks. Everything below the Uvicorn band is your app, drawn faint for now. The later chapters fill it in, one layer at a time.

STEP 02 / 04

UVICORN READS THE REQUEST, YOUR APP WRITES THE ANSWER

Fig 1.2Follow 1 to 5. The accent hop is the one call Uvicorn makes into your code.

uvicorn shop.main:app binds 127.0.0.1:8000 and prints four startup lines, with “Uvicorn running on” last. For each connection the HTTP parser (httptools if it is installed, otherwise h11) reads the request line and headers. Uvicorn then starts a task on the event loop that runs await app(scope, receive, send).

Whatever the app sends back, Uvicorn turns into bytes on the connection. It adds two headers of its own, server: uvicorn and date, and writes one access-log line per request, like the last line below.

INSTALL, START, AND ONE REQUEST
$ pip install "fastapi[standard]"
$ uvicorn shop.main:app
INFO:     Started server process [48213]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     127.0.0.1:51234 - "GET /books/42 HTTP/1.1" 200 OK
STEP 03 / 04

THE APP STRING NAMES A MODULE AND AN ATTRIBUTE

Fig 1.3Each row is a setting and its default. The accent row decides who can connect at all.

shop.main:app is an import string: Uvicorn imports the module shop.main, then takes its attribute app. A wrong name fails at startup, before any request, with Attribute "app" not found in module "shop.main". and exit code 3.

With no flags, Uvicorn listens on host 127.0.0.1 and port 8000, runs 1 worker process, keeps an idle connection open for 5 s, and picks the parser and the event loop automatically. --reload watches your *.py files and restarts the server when one changes; it is off by default.

STEP 04 / 04

UVICORN ANSWERS SOME FAILURES ITSELF

Fig 1.4Each row is a failure Uvicorn answers without your app. The accent row is the one you meet first.

Four failures never reach a response from your code. If the app raises an exception before it starts replying, Uvicorn sends a plain-text 500 Internal Server Error and logs Exception in ASGI application with the traceback. If the app returns without replying, the client also gets a 500, and the log says ASGI callable returned without starting response.

If the app raises after the reply has started, the status line has already gone out, so Uvicorn can only close the connection mid-response. With --limit-concurrency set (it is off by default), a connection over the limit gets a 503 Service Unavailable and your app is never called.

COMMON QUESTIONS

Why not Python’s http.server?
Its own documentation says it is not for production, and it calls handler classes, not ASGI apps. Uvicorn runs many connections on one event loop and can serve any ASGI app.
Do I need uvloop and httptools?
No. Without them Uvicorn uses the standard library’s asyncio loop and the pure-Python h11 parser. uvicorn[standard], which fastapi[standard] installs, adds the faster two, and the auto defaults pick them up.
Is Uvicorn the only server that can run FastAPI?
No. Any ASGI server runs the same app unchanged, such as Hypercorn or Granian. Chapter 02 shows the contract that makes that possible.

WHAT YOU NOW KNOW

  • Uvicorn listens on 127.0.0.1:8000 by default, parses each HTTP request and calls your app once per request.
  • shop.main:app tells Uvicorn which module to import and which attribute in it is the app.
  • When the app fails before replying, Uvicorn sends a plain 500 itself and logs the traceback.
DEEP DIVE: one loop per process, the two parsers, how --reload works, reading the access log

One loop per process

Uvicorn starts its server with asyncio.run(…, loop_factory=…). --loop auto picks uvloop when it imports, and otherwise asyncio’s SelectorEventLoop on Unix. Every request becomes loop.create_task(cycle.run_asgi(app)), a task on that one loop, so code that holds the thread holds up every other request in the process.

The async Python tutorial shows how such a loop switches between tasks at each await.

httptools or h11

--http auto uses httptools, a binding to a C parser, when it is installed, and h11, written in pure Python, otherwise. Uvicorn 0.52 added an experimental third parser, zttp, and 0.53 added --http2, which needs it. The setting h11_max_incomplete_event_size limits how large an unfinished request head may grow, and applies to h11 only.

How --reload works

With --reload, the process you start becomes a reloader that runs the server in a child process and restarts the child when a file changes. It uses watchfiles if it is installed, watching *.py and ignoring dotfiles and .pyc files; otherwise it polls the modification times of *.py files. --reload-delay is 0.25 s by default.

Reload needs the app as an import string, because the child process has to import it again. --workers is ignored under --reload, with a warning in the log.

Reading the access log

Each line holds the client’s address and port, the request line in quotes, and the status with its reason phrase. The path is URL-quoted, with the query string appended. --no-access-log turns the lines off. Ctrl-C prints four shutdown lines, the last naming the process id.

THE ACCESS LOG, THEN CTRL-C
# one line per request: client address, request line, status
INFO:     127.0.0.1:51234 - "GET /books/42?format=short HTTP/1.1" 200 OK
INFO:     127.0.0.1:51234 - "POST /orders HTTP/1.1" 201 Created
# Ctrl-C stops the server
INFO:     Shutting down
INFO:     Waiting for application shutdown.
INFO:     Application shutdown complete.
INFO:     Finished server process [48213]

ERRORS THIS CHAPTER EXPLAINS

Error loading ASGI app. Could not import module "shop.main".
Uvicorn was started from the wrong directory
run it from the project root, or pass --app-dir
Attribute "app" not found in module "shop.main".
the variable holding the app has another name
fix the part of the string after the colon
Address already in use
another server already holds port 8000
stop it, or pass --port 8001

The contract between server and app: ASGI

Uvicorn now accepts connections, parses HTTP and calls app. It can call any app written to one small contract, and so can every other ASGI server. That contract is ASGI, and every framework above it is built out of it. Writing one app against it by hand shows exactly what the frameworks later do for you. What exactly does Uvicorn hand your code, and what must your code send back?

STEP 01 / 04

THE MAP SO FAR

Fig 2.1The accent chip is new: the one call that joins Uvicorn to the app below it.

The line between Uvicorn and everything below it is the ASGI interface: one async call with three arguments, made once per request. Everything under that line is “the app”, whatever library built it, and Uvicorn knows nothing about it beyond that one call.

STEP 02 / 04

AN ASGI APP IS ONE ASYNC FUNCTION WITH THREE ARGUMENTS

Fig 2.2Uvicorn passes three things down. The accent arrow is send, the only way an answer gets back up.

A raw ASGI app fits in a dozen lines and answers every path with book 42. The scope describes the request. receive is an async function that returns the next piece of the request body, and send is an async function that takes the next piece of the reply.

uvicorn shop.raw:app runs it unchanged. The app never touches a socket or an HTTP header line: it reads one dict and exchanges more dicts through the two functions.

SHOP/RAW.PY: AN ASGI APP WITH NO FRAMEWORK
# shop/raw.py: an ASGI app with no framework at all
BOOK = b'{"id":42,"title":"Night Trains of Europe","price_cents":2400}'


async def app(scope, receive, send):
    assert scope["type"] == "http"      # lifespan arrives here too (chapter 04)
    await receive()                     # the request body: empty for a GET
    await send({
        "type": "http.response.start",
        "status": 200,
        "headers": [(b"content-type", b"application/json")],
    })
    await send({"type": "http.response.body", "body": BOOK})

# $ uvicorn shop.raw:app    then every path, /books/42 included, returns BOOK
STEP 03 / 04

THE SCOPE IS A DICT OF STRINGS AND BYTES

Fig 2.3One row per key Uvicorn puts in the scope. The accent row is bytes, not a string.

For GET /books/42?format=short the scope holds "type": "http", "method": "GET" and "path": "/books/42", a str with any percent-encoding already decoded. query_string is b"format=short", bytes. headers is a list of byte pairs, each name lowercased, such as (b"host", b"127.0.0.1:8000").

client is ("127.0.0.1", 51234), curl’s address and port, and server is ("127.0.0.1", 8000). state is an empty dict until chapter 04 puts something in it. Everything else about the request, the body included, comes through receive.

STEP 04 / 04

A RESPONSE IS TWO MESSAGES, START THEN BODY

Fig 2.4Follow 1 to 3 between Uvicorn and the app. The accent message must come before any body.

The first receive() returns {"type": "http.request", "body": b"", "more_body": False}: a GET has no body. The app then sends http.response.start with the status and headers, and Uvicorn writes the status line and headers and logs the request.

Then http.response.body carries the bytes and completes the reply. The order is fixed: a body sent first raises RuntimeError: Expected ASGI message 'http.response.start', but got 'http.response.body'.

COMMON QUESTIONS

Is ASGI the same as WSGI?
No. WSGI is the older, synchronous interface: one call per request that returns the whole reply. ASGI is async and message-based, so one app can stream replies and serve WebSockets.
Why does Uvicorn log “ASGI 'lifespan' protocol appears unsupported.”?
At startup Uvicorn sends one scope whose type is "lifespan", and the raw app’s assert fails on it. Under the default --lifespan auto Uvicorn logs that line and serves requests anyway; chapter 04 handles it properly.
Can I call an ASGI app without a server?
Yes. It is an async function, so a test can pass it a scope and two functions. The test client in chapter 07 does exactly that.

WHAT YOU NOW KNOW

  • An ASGI app is async def app(scope, receive, send), and Uvicorn calls it once per request.
  • The scope is a dict: the path is a str, while the query string and headers are bytes with lowercase names.
  • A reply is http.response.start with status and headers, then http.response.body with the bytes.
DEEP DIVE: the rest of the scope, bodies in pieces, when the client goes away, one interface for three kinds of connection

The rest of the scope

asgi is {"version": "3.0", "spec_version": "2.3"}. http_version and scheme say which protocol arrived. raw_path holds the path as bytes, before percent-decoding, and root_path is a prefix the app is mounted under, already included in path.

state is a shallow copy of what the app stored at startup (chapter 04). Uvicorn sends no extensions key.

Bodies in pieces

A large request body arrives over several receive() calls, each message carrying more_body: True until the last. A reply works the same way: several http.response.body messages, all but the last with more_body: True.

When a client asked for 100 Continue, Uvicorn sends it just before the app’s first receive(). A reply with no content-length header goes out with chunked transfer encoding.

When the client goes away

Once the client disconnects, or the reply is complete, receive() returns {"type": "http.disconnect"}. A long stream should check for it; otherwise it keeps producing bytes that nobody reads.

One interface for three kinds of connection

The scope’s type is "http", "websocket" or "lifespan", and all three arrive through the same call. A WebSocket app exchanges websocket.receive and websocket.send messages instead. --ws auto now picks the websockets-sansio implementation (Uvicorn 0.50).

Requests, responses and routes: Starlette

The raw ASGI app answers every path with the same book, and it makes you decode bytes and build message dicts yourself. A real API has several paths, each handled by its own function, and you want the path, the query and the JSON body already parsed. Starlette is a set of ASGI building blocks that does this: request and response classes, and a router. How does one ASGI app send each path to its own function?

STEP 01 / 04

THE MAP SO FAR

Fig 3.1The accent parts are new: the router and the Request and Response classes, inside the app.

Under the ASGI line sits the app, and a Starlette app is itself an ASGI app. It holds a router with an ordered list of routes. For each request it wraps the scope in a Request, calls the function the matching route names, and sends the Response that function returns.

STEP 02 / 04

AN ENDPOINT TAKES A REQUEST AND RETURNS A RESPONSE

Fig 3.2Follow 1 to 4. At the accent hop the returned JSONResponse sends chapter 02’s two messages.

An endpoint is a function that takes a Request and returns a Response. get_book(request) reads request.path_params["book_id"], which is already an int, because the route’s {book_id:int} is a path convertor. A Request is a thin wrapper around chapter 02’s scope and receive.

A Response is itself an ASGI app. Awaiting it sends http.response.start, then http.response.body, then runs any background task. JSONResponse writes compact JSON, with no spaces after separators and non-ASCII characters kept as they are, and sets content-type: application/json.

TWO STARLETTE ENDPOINTS AND THEIR ROUTES
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route

BOOKS = {42: {"id": 42, "title": "Night Trains of Europe", "price_cents": 2400}}


async def list_books(request: Request) -> JSONResponse:
    limit = int(request.query_params.get("limit", "10"))  # query values are str
    return JSONResponse(list(BOOKS.values())[:limit])


async def get_book(request: Request) -> JSONResponse:
    book_id = request.path_params["book_id"]  # already an int: the route says :int
    return JSONResponse(BOOKS[book_id])       # an unknown id raises KeyError: a 500


app = Starlette(routes=[
    Route("/books", list_books),
    Route("/books/{book_id:int}", get_book),
])
STEP 03 / 04

THE ROUTER TRIES ROUTES IN ORDER

Fig 3.3Four requests against three routes. The accent row matches no route, because int accepts only digits.

The router tries the routes in order and calls the first that fully matches both path and method. GET /books/42 fully matches /books/{book_id:int} and gets a 200. GET /books/abc matches nothing, because int accepts only [0-9]+, so the answer is a plain-text 404 Not Found.

DELETE /books/42 matches the path but not the method, a partial match, so the answer is a 405 whose Allow header lists GET and HEAD. GET /books/ matches nothing; with redirect_slashes on, the router retries without the slash, finds a route and answers 307, a redirect to /books.

STEP 04 / 04

STARLETTE HANDS YOU JSON, NOT CHECKED DATA

Fig 3.4Left, what Starlette does for you. Right, in accent, what each endpoint still has to write.

POST /orders in Starlette starts with data = await request.json(), which gives you dicts and lists. Checking that book_id is an int, quantity is 1 to 10 and email looks like an address takes about a dozen if lines and a hand-built error list, repeated in every endpoint that accepts an order.

The field types exist only inside those lines, so nothing else can read them, documentation and client generators included. Chapter 05 moves the checks into a class, and chapter 06 has them called for you before your function runs.

CREATE_ORDER IN STARLETTE, CHECKED BY HAND
async def create_order(request: Request) -> JSONResponse:
    data = await request.json()               # dicts and lists, nothing checked
    errors = []
    if not isinstance(data.get("book_id"), int):
        errors.append({"field": "book_id", "msg": "must be an integer"})
    quantity = data.get("quantity")
    if not isinstance(quantity, int) or not 1 <= quantity <= 10:
        errors.append({"field": "quantity", "msg": "must be 1 to 10"})
    if "@" not in str(data.get("email", "")):
        errors.append({"field": "email", "msg": "must be an email address"})
    if errors:
        return JSONResponse({"errors": errors}, status_code=400)
    order = save_order(data)                  # finally, the actual work
    return JSONResponse(order, status_code=201)

# and in the routes:  Route("/orders", create_order, methods=["POST"])

COMMON QUESTIONS

Is Starlette a framework or a library?
Both uses work. You can build a whole service with Starlette(), or use one piece, such as a Response class, inside any ASGI app.
What does {book_id:int} do with /books/007?
The int convertor matches [0-9]+ and calls int(), so path_params holds 7.
Where do query parameters go?
request.query_params, a read-only multi-dict built from scope["query_string"]. Its values are strings, so you convert them yourself, as list_books does with limit.

WHAT YOU NOW KNOW

  • A Starlette app is an ASGI app whose router tries each route in order and calls the first full match.
  • An endpoint receives a Request wrapping the scope and returns a Response, which is itself an ASGI app.
  • Starlette parses paths and JSON, but checking that a quantity is a positive int is still your code.
DEEP DIVE: the five path convertors, mounting sub-apps, streaming and file responses, what Starlette 1.0 removed

The five path convertors

str matches [^/]+ and is the default; path matches .*, slashes included; int matches [0-9]+; float and uuid match decimals and UUIDs. compile_path turns {book_id:int} into a regular expression with a named group.

Since Starlette 1.7.0, scope["route"] holds the route that matched, which logging and tracing code can read.

Mounting sub-apps

Mount("/admin", app=other_app) hands every path under a prefix to another ASGI app, with root_path set to that prefix. Host routes by the Host header instead, so one process can serve two domains.

Streaming and file responses

StreamingResponse takes an async or a sync iterable; a sync one is iterated in a separate thread. It sends each chunk as an http.response.body message with more_body: True and sets no content-length, so Uvicorn uses chunked encoding. FileResponse sends a file from disk and sets its length and type.

What Starlette 1.0 removed

Starlette 1.0 removed on_startup and on_shutdown, on_event(), and the decorators @app.route(), @app.middleware() and @app.exception_handler(). Plain generator functions passed as lifespan= are deprecated too. Code written for 0.x that uses them fails on 1.x; pass routes=, middleware= and lifespan= to Starlette() instead.

Code around every request: middleware, errors and lifespan

The app now sends each path to its own function. Some code has to run for every request, whatever its path: a timing header, CORS headers for a browser, turning a crash into a 500. Other code has to run once per process, before the first request: opening the database. Starlette has a place for each, and both are ASGI too. Where does code that runs around every request go, and where does once-per-process code go?

STEP 01 / 04

THE MAP SO FAR

Fig 4.1The accent parts are new: three middleware layers above the router, and the lifespan beside the ASGI line.

Between the ASGI line and the router sit layers of middleware: code that wraps the router and runs for every request, whatever its path. Starlette always puts ServerErrorMiddleware outermost and ExceptionMiddleware innermost. The middleware you add sits between those two, in the order you list it.

Beside the ASGI chip sits the lifespan: one conversation between Uvicorn and the app for the whole process, at startup and at shutdown, instead of one per request. The Pydantic models and everything FastAPI adds are still faint.

STEP 02 / 04

MIDDLEWARE IS AN ASGI APP THAT WRAPS ANOTHER

Fig 4.2Requests go in through 1 to 4 and replies come out through 5 to 8. The accent ring is yours.

A middleware is a class whose __init__ stores the next layer and whose __call__(scope, receive, send) is itself an ASGI app. TimingMiddleware notes the time, then calls the next layer with a wrapped send. When http.response.start passes through that wrapper on its way out, it gains an x-process-ms header.

Starlette builds the stack on the first call, outside in: ServerErrorMiddleware, your list in order, ExceptionMiddleware, the router. app.add_middleware() inserts at the front of your list, so the last one added runs first. Called once the app has started, it raises Cannot add middleware after an application has started.

A TIMING HEADER ON EVERY REPLY, AS PURE ASGI
import time

from starlette.middleware import Middleware


class TimingMiddleware:
    def __init__(self, app):
        self.app = app                        # the next layer inwards

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":           # lifespan passes straight through
            await self.app(scope, receive, send)
            return
        start = time.perf_counter()

        async def send_timed(message):
            if message["type"] == "http.response.start":
                ms = (time.perf_counter() - start) * 1000
                message["headers"] = [*message["headers"], (b"x-process-ms", b"%.1f" % ms)]
            await send(message)

        await self.app(scope, receive, send_timed)


app = Starlette(routes=routes, middleware=[Middleware(TimingMiddleware)])
STEP 03 / 04

TWO LAYERS TURN EXCEPTIONS INTO RESPONSES

Fig 4.3One row per way a request can fail. The accent row is a bug, caught by the outermost layer.

ExceptionMiddleware handles HTTPException. When an endpoint raises HTTPException(404), the handler, which runs inside the route, sends a plain-text 404 Not Found. A path that matches no route gets the same 404: the router raises the same exception, and the layer around it answers.

Any other exception is a bug as far as Starlette can tell. In chapter 03’s get_book, an unknown id makes BOOKS[book_id] raise KeyError. It passes through your middleware to ServerErrorMiddleware, which sends a plain 500 Internal Server Error and then raises the exception again, so Uvicorn logs the traceback. With debug=True the 500 carries the traceback: an HTML page for a browser, plain text otherwise.

STEP 04 / 04

LIFESPAN RUNS ONCE, AROUND EVERY REQUEST

Fig 4.4Follow 1 to 6. Every request runs in the accent gap between startup and shutdown.

A lifespan is an async context manager you pass to the app as lifespan=. The bookshop’s opens shop.db before the first request, yields {"db": db}, and closes the database after the last. Over ASGI, Uvicorn sends lifespan.startup, your code runs up to yield, the app answers lifespan.startup.complete, and Uvicorn logs “Application startup complete.”

Then requests run. Each one gets the yielded dict as request.state, a shallow copy Uvicorn makes for every request, so an endpoint reads request.state.db. At Ctrl-C Uvicorn sends lifespan.shutdown, the code after yield closes the database, and the app answers lifespan.shutdown.complete.

OPEN THE DATABASE ONCE PER PROCESS
import sqlite3
from contextlib import asynccontextmanager


@asynccontextmanager
async def lifespan(app):
    db = sqlite3.connect("shop.db", check_same_thread=False)  # before the first request
    yield {"db": db}            # reaches every request as request.state.db
    db.close()                  # after the last request, at shutdown


def get_book(request: Request) -> JSONResponse:   # a def endpoint runs in a thread
    row = request.state.db.execute(
        "SELECT id, title, price_cents FROM books WHERE id = ?",
        (request.path_params["book_id"],),
    ).fetchone()
    return JSONResponse(dict(zip(("id", "title", "price_cents"), row)))


app = Starlette(routes=routes, lifespan=lifespan)

COMMON QUESTIONS

Why does the browser report a CORS error when curl works?
A browser refuses a cross-origin reply unless it carries CORS headers, and curl never checks. Add CORSMiddleware with your frontend’s origin in allow_origins; the deep dive shows it.
What happened to @app.middleware("http")?
Starlette 1.0 removed the decorator; pass classes in middleware=[Middleware(...)] instead. FastAPI 0.165.0 still offers @app.middleware("http"), which wraps your function in a BaseHTTPMiddleware.
Can middleware read the request body?
Yes, by wrapping receive, but it must hand the same messages on, or the endpoint finds an empty body.

WHAT YOU NOW KNOW

  • Middleware is an ASGI app wrapping the next one: ServerErrorMiddleware, yours in order, ExceptionMiddleware, then the router.
  • An HTTPException becomes its own status; any other exception becomes a plain 500 and is re-raised for the log.
  • The lifespan context manager runs before the first request and after the last, and what it yields reaches request.state.
DEEP DIVE: CORS preflights, BaseHTTPMiddleware or pure ASGI, your own exception handlers, a body size limit

CORS preflights

A page on https://shop.example that calls the API at another origin first sends a preflight: an OPTIONS request with Origin and Access-Control-Request-Method headers. CORSMiddleware answers it itself, without calling the router: 200 OK when the origin and method are allowed, 400 Disallowed CORS origin when the origin isn’t.

Its defaults allow nothing cross-origin: allow_origins=(), allow_methods=("GET",), allow_credentials=False, and max_age=600, the seconds a browser may cache a preflight answer. Because ExceptionMiddleware sits inside it, a 404 still carries the CORS headers; a 500 from ServerErrorMiddleware, outside it, does not.

CORS FOR THE SHOP’S OWN FRONTEND
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware

middleware = [
    Middleware(
        CORSMiddleware,
        allow_origins=["https://shop.example"],  # the site whose pages call the API
        allow_methods=["GET", "POST"],           # the default allows GET only
        allow_headers=["x-api-key"],             # on top of the always-allowed four
    ),
    Middleware(TimingMiddleware),
]
app = Starlette(routes=routes, middleware=middleware)

BaseHTTPMiddleware or pure ASGI

BaseHTTPMiddleware gives a shorter API: a dispatch(request, call_next) method that gets a Request and returns a Response. Its one documented limitation in Starlette 1.10.0 is that changes to contextvars made further in don’t propagate back up to dispatch. The old problem with background tasks was fixed in 1.7.0. Starlette’s docs still recommend pure ASGI middleware, like TimingMiddleware, which sees every message as it passes.

Your own exception handlers

Pass exception_handlers={404: not_found, KeyError: on_key_error} to the app. A handler takes the request and the exception and returns a Response. Handlers for 500 or Exception go to ServerErrorMiddleware, which still re-raises afterwards for the log; every other key goes to ExceptionMiddleware.

For an HTTPException, the lookup tries the status code first. Then, for any exception, it walks the exception’s class hierarchy and uses the nearest class that has a handler.

A body size limit

Starlette 1.6.0 added Starlette(max_body_size=…), which adds a layer that answers 413 Content Too Large once a request body passes the limit. FastAPI has its own setting since 0.164.0, also called max_body_size; chapter 06’s deep dive shows where its layer sits.

ERRORS THIS CHAPTER EXPLAINS

Caught handled exception, but response already started.
an exception after http.response.start, often in a streaming reply
raise errors before the reply starts
Cannot add middleware after an application has started
add_middleware called after the first request
add it when you create the app
Application startup failed. Exiting.
the lifespan’s code before yield raised, so Uvicorn logs the traceback and stops
fix the setup code, such as a database path that doesn’t exist

Classes that check data: Pydantic

The Starlette version checks each order with a dozen if lines, and the field types exist only inside them. Pydantic moves those types into a class: you declare each field with a type hint, and the class checks any data you build it from, then reports every problem at once. It needs no web server, so this chapter uses it on its own, the way a script or a queue consumer would. How do you turn untrusted JSON into a Python object you can rely on?

STEP 01 / 05

THE MAP SO FAR

Fig 5.1The accent node is new: the Pydantic models, not yet joined to any route.

Pydantic models sit at the side of the app: OrderIn for what comes in, OrderOut for what goes back. Nothing on the map calls them yet; chapter 06 joins them to the routes.

Under every model, pydantic-core does the checking. It is written in Rust and installed as a compiled extension, so the Python package you import is a thin layer over it.

STEP 02 / 05

A MODEL CHECKS ITS DATA WHEN YOU CREATE IT

Fig 5.2Bytes go in at the left. The accent box is the validator, built once when the class was defined.

OrderIn declares three fields with type hints: book_id: int, quantity: int = Field(gt=0, le=10) and email: EmailStr. When Python runs the class statement, Pydantic turns those hints into one validator, __pydantic_validator__, and every later check reuses it. That check, types and limits tested and values converted where allowed, is called validation.

OrderIn.model_validate_json(raw) parses the bytes and checks them in one pass in Rust; model_validate() takes a dict you already have. Going back, model_dump() gives a dict, model_dump(mode="json") a dict of JSON-safe values, and model_dump_json() a JSON string. EmailStr needs one extra package: pip install "pydantic[email]".

ORDERIN, AND ONE ORDER CHECKED AGAINST IT
from pydantic import BaseModel, EmailStr, Field   # EmailStr needs pydantic[email]


class OrderIn(BaseModel):
    book_id: int
    quantity: int = Field(gt=0, le=10)      # 1 to 10 copies
    email: EmailStr


raw = b'{"book_id": 42, "quantity": "2", "email": "ana@example.com"}'
order = OrderIn.model_validate_json(raw)    # parse and check in one pass

order.quantity            # → 2, an int: lax mode converted "2"
order.model_dump()        # → {'book_id': 42, 'quantity': 2, 'email': 'ana@example.com'}
order.model_dump_json()   # → '{"book_id":42,"quantity":2,"email":"ana@example.com"}'
STEP 03 / 05

LAX MODE CONVERTS WHAT IT CAN WITHOUT LOSING INFORMATION

Fig 5.3One row per input. The accent row is the conversion that surprises people: a string becoming an int.

By default Pydantic validates in lax mode: it converts an input to the field’s type when nothing is lost. The string "2" becomes the int 2, and so does the float 2.0. The float 2.5 is refused with int_from_float, because the half would be lost. The int 2 is refused for a str field with string_type: by default Pydantic doesn’t turn numbers into strings.

Strings that spell a value convert too: "yes" becomes True for a bool, and "2026-11-27" becomes date(2026, 11, 27). Strict mode, ConfigDict(strict=True) on the model or Field(strict=True) on one field, refuses these conversions from Python data. From JSON a string still becomes a date, because JSON has no date type.

STEP 04 / 05

ONE ERROR LISTS EVERY BAD FIELD

Fig 5.4One row per error, in field order. The accent row carries ctx, the limit that was broken.

Validating the bad order, {"book_id": "abc", "quantity": 0, …}, raises one ValidationError with two entries. Pydantic checks every field before it raises, so book_id fails with int_parsing and quantity fails with greater_than in the same exception. The email is valid and adds nothing.

.errors() returns the entries as dicts. Each has a type, a machine-readable name; a loc, the path to the field; a msg for people; the input it got; and a url to the error’s page. ctx appears only when the error has context: {'gt': 0} for greater_than, nothing for int_parsing.

WHAT A CAUGHT VALIDATIONERROR PRINTS
# check_order.py validates the bad order and prints the caught ValidationError
$ python check_order.py
2 validation errors for OrderIn
book_id
  Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='abc', input_type=str]
    For further information visit https://errors.pydantic.dev/2.14/v/int_parsing
quantity
  Input should be greater than 0 [type=greater_than, input_value=0, input_type=int]
    For further information visit https://errors.pydantic.dev/2.14/v/greater_than
STEP 05 / 05

AN UNKNOWN FIELD IS DROPPED WITHOUT A WORD

Fig 5.5The same input, two settings. The accent column refuses the field the model doesn’t declare.

A client sends the good order plus a field the model doesn’t declare, "gift_wrap": true. Under the default, extra="ignore", validation succeeds, the model has its three fields, and gift_wrap is gone without an error or a log line.

Set model_config = ConfigDict(extra="forbid") and the same input fails with one error of type extra_forbidden at gift_wrap, message “Extra inputs are not permitted”. A third setting, extra="allow", keeps the field and stores it on the model.

REFUSING FIELDS THE MODEL DOESN’T DECLARE
from pydantic import BaseModel, ConfigDict, EmailStr, Field


class OrderIn(BaseModel):
    model_config = ConfigDict(extra="forbid")    # unknown fields are errors

    book_id: int
    quantity: int = Field(gt=0, le=10)
    email: EmailStr


OrderIn.model_validate({"book_id": 42, "quantity": 2,
                        "email": "ana@example.com", "gift_wrap": True})
# → ValidationError at gift_wrap: Extra inputs are not permitted [type=extra_forbidden]

COMMON QUESTIONS

Is Pydantic only for web APIs?
No. Settings files, queue messages and tool arguments use it the same way. FastAPI is one of its users.
A dataclass or a BaseModel?
A dataclass stores what you give it and checks nothing. A BaseModel checks and converts on creation and can dump to JSON; pydantic.dataclasses adds the checks to a dataclass.
Does validation slow every request?
The checks run in pydantic-core’s compiled code, built once per class. For a model like OrderIn, the database call or the network usually costs more.

WHAT YOU NOW KNOW

  • A Pydantic model declares fields with type hints and checks the data every time an instance is created.
  • Lax mode turns "2" into 2 but rejects 2.5 for an int, and every bad field appears in one ValidationError.
  • Unknown fields are dropped by default; extra="forbid" turns them into errors.
DEEP DIVE: strict mode, your own validators, JSON Schema from a model, TypeAdapter, what changed in 2.10–2.14

Strict mode

Strictness has three levels: the whole model (ConfigDict(strict=True)), one field (Field(strict=True), or a type such as StrictInt), and one call (OrderIn.model_validate(data, strict=True)). Even in strict mode, JSON input keeps the conversions JSON needs because it has no type for them: a string still becomes a date, datetime or Decimal.

Your own validators

@field_validator("email") runs your function on one field, in one of four modes: after (the default) on the converted value, before on the raw input, wrap around Pydantic’s own check, and plain instead of it.

@model_validator checks several fields together in before, after or wrap mode; since 2.12 an after-mode validator is an instance method that returns self. @computed_field adds a property to the dumped output.

JSON Schema from a model

OrderIn.model_json_schema() describes the model as JSON Schema, Draft 2020-12, with no $schema key. gt=0 becomes exclusiveMinimum, le=10 becomes maximum, titles come from field names ("Book Id"), and every field without a default is required.

A model has a validation schema and a serialization schema, which differ when, for example, a computed field appears only in the output. Chapter 08 serves this schema in the API’s docs.

THE JSON SCHEMA PYDANTIC WRITES FOR ORDERIN
OrderIn.model_json_schema()
# → {'properties': {'book_id': {'title': 'Book Id', 'type': 'integer'},
#                   'quantity': {'exclusiveMinimum': 0, 'maximum': 10,
#                                'title': 'Quantity', 'type': 'integer'},
#                   'email': {'format': 'email', 'title': 'Email', 'type': 'string'}},
#    'required': ['book_id', 'quantity', 'email'],
#    'title': 'OrderIn', 'type': 'object'}

TypeAdapter

Types that aren’t models, such as list[int], get the same machinery through TypeAdapter(list[int]), with validate_python, validate_json, dump_json and json_schema. Building an adapter builds a validator, so build it once at import and reuse it. FastAPI builds one per parameter and per response model (chapter 06).

What changed in 2.10–2.14

pydantic-core’s source moved into the pydantic repository in 2.13, and Pydantic 2.14.4 ships with pydantic-core 2.50.5. 2.14 needs Python 3.10 or newer. validate_by_alias and validate_by_name replaced populate_by_name in 2.11, and 2.12 lets you pass extra= to a single validation call. Since 2.14.2, JSON validation counts an unused alias as an extra field.

ERRORS THIS CHAPTER EXPLAINS

ImportError: email-validator is not installed, run pip install 'pydantic[email]'
EmailStr used without its extra package
install it, or fastapi[standard], which includes it
Field required [type=missing, …]
the input lacks a field that has no default, often because the client misspelled its key
fix the client, or give the field a default

The signature becomes the parser: FastAPI

You have Starlette routing requests and Pydantic checking data, but nothing joins them yet: an endpoint still calls request.json() and builds the model itself. FastAPI is a subclass of Starlette that reads each endpoint’s parameters and type hints, and does that joining for every request. The endpoint’s signature becomes the description of what the request must contain. How does FastAPI know where each argument comes from, and what happens when one is wrong?

STEP 01 / 05

THE MAP SO FAR

Fig 6.1The accent parts are new: FastAPI’s route handler and your endpoint, under Starlette’s router.

The app is now app = FastAPI(). Starlette’s router and the three middleware layers stay where they were. Under the router, FastAPI adds a route handler for each path operation: one path plus one HTTP method, such as POST /orders, together with the function that answers it.

That function is the endpoint, create_order(), which holds your business rule. The route handler between the router and the endpoint is joined to the Pydantic models from chapter 05, so every value on its way in passes their checks.

STEP 02 / 05

FASTAPI IS A STARLETTE APP

Fig 6.2The same endpoint written twice. The accent column is FastAPI: no request.json(), and no if lines.

FastAPI is declared as class FastAPI(Starlette), so everything from chapters 03 and 04 still works on it. The decorators @app.get("/books/{book_id}") and @app.post("/orders", status_code=201) add routes to the same router. Each is an APIRoute: a Starlette Route with FastAPI’s handler inside.

get_book(book_id: int) raises HTTPException(status_code=404) for an unknown book, or returns a dict, which FastAPI sends as JSON. create_order(order: OrderIn) receives an order that has already passed every check. You start the app with the same command as chapter 01: uvicorn shop.main:app.

SHOP/MAIN.PY: THE BOOKSHOP IN FASTAPI
from fastapi import FastAPI, HTTPException

from shop.models import OrderIn, OrderOut      # chapter 05 models

app = FastAPI(title="Bookshop API")            # a Starlette subclass: an ASGI app


@app.get("/books")
async def list_books(limit: int = 10):         # ?limit=5, checked as an int
    return list(BOOKS.values())[:limit]


@app.get("/books/{book_id}")
async def get_book(book_id: int):              # from the path, checked as an int
    if book_id not in BOOKS:
        raise HTTPException(status_code=404, detail="Book not found")
    return BOOKS[book_id]                      # a dict: FastAPI sends it as JSON


@app.post("/orders", status_code=201)
async def create_order(order: OrderIn) -> OrderOut:   # the body, checked as OrderIn
    return save_order(order)
STEP 03 / 05

EACH PARAMETER’S NAME AND TYPE PICK ITS SOURCE

Fig 6.3One row per parameter. The accent row is the model, read from the JSON body.

When a route is added, its handler reads each parameter’s name and annotation and decides where the value comes from. book_id: int is named in the path /books/{book_id}, so it comes from the path. limit: int = 10 is a simple type that isn’t in the path, so it is a query parameter: a name=value pair after the ? in the URL, such as ?limit=5.

order: OrderIn is a Pydantic model, so it is read from the JSON body. x_api_key: Annotated[str, Header()] is marked as a header, and FastAPI turns its underscores into hyphens to find X-API-Key. A parameter annotated request: Request gets Starlette’s Request object, passed in unchecked.

STEP 04 / 05

ONE ROUTE HANDLER, SIX STEPS

Fig 6.4Follow 1 to 6 through the handler. At the accent step every parameter meets its Pydantic check.

The handler is a function that get_request_handler in fastapi/routing.py builds for each route. It reads the body first, and parses it as JSON only when the Content-Type header says JSON. Then it validates every parameter, path, query, header and body, with Pydantic, and keeps every error instead of stopping at the first.

Any error raises RequestValidationError, which becomes a 422 response. With none, the handler calls your endpoint: it awaits an async def and runs a plain def in a separate thread (chapter 09). It then turns the return value into JSON, filtered by the return annotation (chapter 08), and builds the Response that goes back out through the router.

FASTAPI/ROUTING.PY AT 0.165.0, TRIMMED
# fastapi/routing.py at 0.165.0, inside get_request_handler, lines 539-814 (trimmed)
errors = solved_result.errors                    # ← every parameter, already validated
if not errors:
    raw_response = await run_endpoint_function(  # ← your endpoint runs here
        dependant=dependant,
        values=solved_result.values,
        is_coroutine=is_coroutine,               # ← async def awaited, def in a thread
    )
    if isinstance(raw_response, Response):
        response = raw_response                  # ← a Response passes straight through
    else:
        use_dump_json = response_field is not None and isinstance(
            response_class, DefaultPlaceholder
        )
        content = await serialize_response(      # ← the response model filters it
            field=response_field,
            response_content=raw_response,
            dump_json=use_dump_json,             # ← Pydantic writes the JSON bytes
        )
        if use_dump_json:
            response = Response(content=content, media_type="application/json")
        else:
            response = actual_response_class(content)
if errors:
    raise RequestValidationError(errors)         # ← any bad parameter: a 422
STEP 05 / 05

A BAD REQUEST GETS A 422 BEFORE YOUR CODE RUNS

Fig 6.5One row per bad request. The accent row is valid JSON refused only because a header is missing.

Send the bad order and FastAPI answers 422 Unprocessable Content, the status it uses when a request’s data fails validation. The body is {"detail": [...]}: Pydantic’s error list, one entry per bad value, each with type, loc, msg and input, plus ctx when the rule has a limit, such as {"gt": 0}. Unlike chapter 05’s errors, these entries carry no url.

loc starts with where the value was: body, path, query or header. So GET /books/abc now gets a 422 with int_parsing at ["path", "book_id"], where chapter 03’s {book_id:int} route gave a 404. A body that stops halfway gets json_invalid. None of these reach create_order.

THE BAD ORDER, SENT WITH CURL
$ curl -s -w "\n%{http_code}\n" -X POST http://127.0.0.1:8000/orders \
    -H "Content-Type: application/json" -H "X-API-Key: k-demo-7f3a" \
    -d '{"book_id": "abc", "quantity": 0, "email": "ana@example.com"}'
{"detail":[{"type":"int_parsing","loc":["body","book_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"abc"},{"type":"greater_than","loc":["body","quantity"],"msg":"Input should be greater than 0","input":0,"ctx":{"gt":0}}]}
422

COMMON QUESTIONS

Must endpoints be async def?
No. FastAPI awaits an async def and runs a plain def in a separate thread, so both work. Chapter 09 explains which to choose.
Does FastAPI replace Starlette’s Request?
No, it is the same class. Declare request: Request next to your typed parameters to get it.
What does FastAPI add to the middleware stack?
Three layers plain Starlette lacks: exception telemetry, a body-size limit, and one that closes uploaded files. The deep dive lists all seven in order.

WHAT YOU NOW KNOW

  • FastAPI is a Starlette subclass whose decorators add routes, each with a handler that reads the endpoint’s signature.
  • book_id named in /books/{book_id} comes from the path, order: OrderIn from the JSON body, and limit: int = 10 from the query string.
  • Every parameter is validated first; any failure returns 422 with Pydantic’s errors, and the endpoint never runs.
DEEP DIVE: seven middleware layers, built-in OpenTelemetry, parameter models, what changed since 0.115

Seven middleware layers

FastAPI.build_middleware_stack wraps the router in seven layers, three more than plain Starlette. ServerErrorMiddleware stays outermost and ExceptionMiddleware stays just outside the router. FastAPI adds exception telemetry and a body-size limit outside your middleware, and inside it an exit stack that closes uploaded files.

Dependencies with yield (chapter 07) don’t use that exit stack: each route opens exit stacks of its own.

Outermost first. The accent row is your middleware, between FastAPI’s outer layers and Starlette’s ExceptionMiddleware.

Built-in OpenTelemetry

FastAPI 0.142.0 added OpenTelemetry support. Once an OpenTelemetry provider is configured, each request gets a server span such as POST /orders, with spans for fastapi.dependencies, fastapi.endpoint, fastapi.serialization and fastapi.background_task, and the metrics http.server.request.duration and http.server.active_requests.

With no provider it does nothing, and a request goes straight to Starlette.__call__. FastAPI sets up exporters itself only when FASTAPI_OTEL_AUTO_CONFIGURE=true (0.143.0). The tracing tutorial explains spans and how to read them.

Parameter models

Since 0.115.0, Annotated[Filters, Query()] reads a group of query parameters into one Pydantic model, so several filters share one class and its checks, extra="forbid" included. Since 0.157.0 one endpoint can combine several such models.

What changed since 0.115

A JSON body needs a JSON Content-Type (0.132.0). Pydantic v1 models are gone (0.126.0 and 0.128.0), and using one raises PydanticV1NotSupportedError. Python 3.11 is the minimum (0.162.6).

FastAPI(root_path=...) is deprecated (0.146.0), Query() no longer takes extra keyword arguments (0.155.0), and the security classes answer a missing credential with 401 instead of 403 (0.122.0). on_event is still deprecated in favour of lifespan.

ERRORS THIS CHAPTER EXPLAINS

PydanticV1NotSupportedError
a model imported from pydantic.v1
port the model to Pydantic 2
a 422 with "loc": ["body"] for valid JSON
the request has no JSON Content-Type, so the body was never parsed
send Content-Type: application/json

Shared setup for endpoints: dependencies

Three endpoints now need the database connection, and two must check the X-API-Key header against the keys in that database. Copying the code into each endpoint repeats it, and every copy needs its own cleanup. FastAPI lets an endpoint ask for these by parameter instead: a dependency is a function FastAPI calls before the endpoint, passing its result in. How do several endpoints share a database connection and a key check without repeating code?

STEP 01 / 04

THE MAP SO FAR

Fig 7.1The accent parts are new: two dependencies, and the database file one of them opens.

Beside the route handler sit two dependencies. get_db opens a connection to shop.db, a SQLite file outside the process, and closes it when the request is done. require_key reads the X-API-Key header and looks it up in the api_keys table.

Your code never calls either of them. An endpoint names them in its parameters with Depends(), and the route handler calls them before the endpoint, in the same validation step as every other parameter.

STEP 02 / 04

FASTAPI SOLVES THE TREE ONCE PER REQUEST

Fig 7.2Read bottom to top. The accent node is asked for twice, by require_key and by create_order, and runs once.

DB = Annotated[sqlite3.Connection, Depends(get_db)] names the dependency once. require_key takes the header and db: DB, and raises 401 when the key isn’t in the table. create_order takes order and db: DB, and its decorator adds dependencies=[Depends(require_key)], because it needs the check but no value from it.

Before the endpoint runs, FastAPI solves this tree depth first. get_db is asked for twice and runs once: with the default use_cache=True, both callers get the same connection for this request. A missing header joins the same 422 list as a bad body field, and the endpoint never runs.

create_order is a plain def this time, not async def, because every sqlite3 call blocks. Chapter 09 shows where FastAPI runs it.

SHOP/DEPS.PY: TWO DEPENDENCIES, AND THE ENDPOINT THAT USES THEM
import sqlite3
from typing import Annotated

from fastapi import Depends, Header, HTTPException


def get_db():
    db = sqlite3.connect("shop.db", check_same_thread=False)
    try:
        yield db                     # the value every caller receives
    finally:
        db.close()                   # runs once the response has been sent


DB = Annotated[sqlite3.Connection, Depends(get_db)]


def require_key(x_api_key: Annotated[str, Header()], db: DB) -> None:  # X-API-Key
    found = db.execute("SELECT 1 FROM api_keys WHERE key = ?", (x_api_key,)).fetchone()
    if found is None:
        raise HTTPException(status_code=401, detail="Invalid API key")


@app.post("/orders", status_code=201, dependencies=[Depends(require_key)])
def create_order(order: OrderIn, db: DB) -> OrderOut:  # def: sqlite3 blocks (chapter 09)
    return save_order(db, order)
STEP 03 / 04

CODE AFTER YIELD RUNS ONCE THE RESPONSE IS SENT

Fig 7.3In the first timeline, the accent step closes the connection after the client already has its reply.

get_db is a generator: FastAPI runs it up to yield and passes the yielded connection to whoever asked. The code after yield is the cleanup, here db.close() in a finally block, so it runs even when the endpoint raises.

By default FastAPI runs that cleanup after the response has been sent: the client already has its 201 when the connection closes. Depends(get_db, scope="function"), added in FastAPI 0.121.0, moves it to the moment the endpoint returns, before the response goes out.

STEP 04 / 04

A TEST SWAPS A DEPENDENCY AND NEEDS NO SERVER

Fig 7.4Production at left, the test at right. In the accent column nothing listens on a port.

app.dependency_overrides is a dict on the app: app.dependency_overrides[get_db] = fake_db makes every Depends(get_db) call fake_db instead. Here it yields an in-memory SQLite database holding the tables and one API key, so require_key and create_order run unchanged against it.

TestClient is Starlette’s test client. It builds the scope and messages itself and calls the ASGI app as a function, through the httpx2 library, so no socket is opened and no Uvicorn runs. Inside with TestClient(app) as client: it also runs the lifespan. The test posts quantity 0 with the key k-demo-7f3a and expects a 422 with greater_than.

TEST_ORDERS.PY: THE BAD ORDER, WITH NO SERVER
import sqlite3

from fastapi.testclient import TestClient

from shop.deps import get_db
from shop.main import app


def fake_db():
    db = sqlite3.connect(":memory:", check_same_thread=False)
    db.executescript(SCHEMA_SQL)                 # empty tables and one API key
    yield db


app.dependency_overrides[get_db] = fake_db       # every Depends(get_db) gets this


def test_quantity_zero_is_refused():
    with TestClient(app) as client:              # runs lifespan; no socket, no Uvicorn
        r = client.post(
            "/orders",
            json={"book_id": 42, "quantity": 0, "email": "ana@example.com"},
            headers={"X-API-Key": "k-demo-7f3a"},
        )
    assert r.status_code == 422
    assert r.json()["detail"][0]["type"] == "greater_than"

COMMON QUESTIONS

Why does a missing X-API-Key give 422, not 401?
Header() with no default makes the header a required parameter, so validation fails before require_key runs. Give it a default of None and raise 401 yourself when it is absent.
Can a dependency be a class?
Yes. Any callable works: FastAPI reads the __init__ signature, solves its parameters like a function’s, and passes in the new instance.
How is Depends different from a module-level connection?
A module-level connection is shared by every request and can’t be swapped. A dependency gives each request its own setup and cleanup, and a test can override it. The design-patterns tutorial’s dependency-injection chapter covers the idea.

WHAT YOU NOW KNOW

  • A dependency is a function named in Depends(); FastAPI calls it before the endpoint and passes in its result.
  • The tree is solved once per request: get_db runs once, though require_key and create_order both ask for it.
  • Code after yield runs after the response is sent, and dependency_overrides swaps a dependency in tests.
DEEP DIVE: two exit points for yield, def dependencies and SQLite threads, security helpers, limiting concurrency

Two exit points for yield

Where the code after yield runs has moved twice. FastAPI 0.106.0 moved it before the response, 0.118.0 moved it back after, and 0.121.0 added scope= so each dependency can choose. The default also waits for background tasks (chapter 09), so a task can still use the connection.

A dependency with the default scope can’t depend on one with scope="function", because the inner one would be cleaned up first. FastAPI refuses that with DependencyScopeError.

def dependencies and SQLite threads

get_db is a plain generator, so FastAPI runs it in a worker thread (chapter 09), and the endpoint, also a def, may run on a different one. sqlite3 refuses a connection used on any thread but the one that made it, with the ProgrammingError listed below.

check_same_thread=False turns that check off. It is safe here because the dependency gives each request its own connection, and one request uses it from one thread at a time.

Security helpers

APIKeyHeader(name="X-API-Key") used with Security() reads the same header as require_key’s parameter, and also records the scheme in the API description, so the docs page (chapter 08) shows a lock and an Authorize button. Since 0.122.0 these classes answer a missing credential with 401, not 403.

Limiting concurrency

FastAPI 0.163.0 added Depends(..., max_concurrency=...), which caps how many requests can run that dependency at once. It suits a dependency that wraps something scarce, such as a partner API that allows only a few connections.

ERRORS THIS CHAPTER EXPLAINS

ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id … and this is thread id ….
a connection made on one pool thread is used on another
open it with check_same_thread=False and keep one connection per request
DependencyScopeError
a dependency with the default request scope depends on one with scope="function"
give the outer one scope="function" too, or drop it from the inner one
a 422 with "type": "missing" at ["header", "x-api-key"]
the client sent no X-API-Key header
send the header, or give the parameter a default and answer 401 yourself

What goes back, and the docs: response models and OpenAPI

create_order saves the order and gets back a database row with every column, including cost_cents, the shop’s purchase price, which no customer should see. A partner developer also needs a page that lists every endpoint and lets them try one. Both answers come from the Pydantic models you already have: a model decides what leaves, and the docs are generated from the same types. How do you control exactly what an endpoint sends back, and where do the interactive docs come from?

STEP 01 / 04

THE MAP SO FAR

Fig 8.1The accent parts are new: the response model under the endpoint, and the generated docs.

Under the endpoint sits its response model: the return annotation -> OrderOut, a Pydantic model that every return value passes through on its way out. It joins the same Pydantic models that already check the request body.

At the right of the FastAPI band sit /openapi.json and /docs, a description of the whole API and a page for trying it. FastAPI generates both from the routes and models you have already declared, so neither needs any code of yours.

STEP 02 / 04

THE RESPONSE MODEL DECIDES WHAT LEAVES

Fig 8.2What the endpoint returned at left, what the client got at right. Muted rows never leave the server.

create_order returns the saved row with six keys: id 1001, book_id 42, quantity 2, total_cents 4800, cost_cents 3000 and the email. Because its return annotation is OrderOut, FastAPI validates the row as OrderOut before sending it. The model has four fields, so cost_cents and email are dropped.

The check reads attributes as well as dict keys (from_attributes=True), so objects from a database library work too. With the default response class, Pydantic writes the JSON bytes itself and FastAPI sends them in a plain Response with application/json. A return value that doesn’t fit the model raises ResponseValidationError, and the client gets a 500.

SHOP/MAIN.PY: THE RETURN ANNOTATION IS THE RESPONSE MODEL
from pydantic import BaseModel


class OrderOut(BaseModel):
    id: int
    book_id: int
    quantity: int
    total_cents: int


@app.post("/orders", status_code=201, dependencies=[Depends(require_key)])
def create_order(order: OrderIn, db: DB) -> OrderOut:  # the annotation is the response model
    row = save_order(db, order)
    # row == {"id": 1001, "book_id": 42, "quantity": 2, "total_cents": 4800,
    #         "cost_cents": 3000, "email": "ana@example.com"}
    return row          # validated as OrderOut: cost_cents and email are dropped
STEP 03 / 04

THE OPENAPI DOCUMENT COMES FROM THE SAME TYPES

Fig 8.3Routes and models go in at the left. The accent box joins them into one document.

On the first request to /openapi.json, FastAPI’s get_openapi() walks every route for its path, method, parameters and status codes, and asks Pydantic for each model’s JSON Schema. The result is one OpenAPI 3.1.0 document, a standard JSON description of the API.

OrderIn appears with the limits you declared: quantity has exclusiveMinimum: 0 and maximum: 10, and email has format: email. FastAPI keeps the document in app.openapi_schema, so later requests get the cached copy, and builds it again only if routes are added after that. Client generators read the same file.

PART OF /OPENAPI.JSON
{
  "openapi": "3.1.0",
  "info": { "title": "Bookshop API", "version": "0.1.0" },
  "components": {
    "schemas": {
      "OrderIn": {
        "properties": {
          "book_id": { "title": "Book Id", "type": "integer" },
          "quantity": {
            "exclusiveMinimum": 0,
            "maximum": 10,
            "title": "Quantity",
            "type": "integer"
          },
          "email": { "format": "email", "title": "Email", "type": "string" }
        },
        "required": ["book_id", "quantity", "email"],
        "title": "OrderIn",
        "type": "object"
      }
    }
  }
}
STEP 04 / 04

/DOCS IS A PAGE THAT READS /OPENAPI.JSON

Fig 8.4Follow 1 to 4 in the browser. The accent hop is a real request to your app.

GET /docs returns a small HTML page, not the docs themselves. The page loads Swagger UI, a JavaScript app that draws an OpenAPI document, from cdn.jsdelivr.net, a public CDN. Swagger UI then fetches /openapi.json and draws one panel per endpoint.

“Try it out” on POST /orders sends a real request from your browser to the running app, through the route handler and the endpoint like any other. /redoc loads ReDoc the same way: a read-only view of the same document.

COMMON QUESTIONS

Why is /docs a blank page?
Its HTML loads Swagger UI from cdn.jsdelivr.net. On a network that blocks that site the page stays empty; serve the files yourself, as the deep dive shows.
Why are there two schemas, OrderOut-Input and OrderOut-Output?
separate_input_output_schemas=True, the default, writes a model twice when it is used both ways and the two shapes differ, such as a field with a default value.
How do I set a header on the reply?
Declare a parameter response: Response and set response.headers["x-order-id"]. FastAPI copies those headers onto the reply it builds.

WHAT YOU NOW KNOW

  • The return annotation, OrderOut, filters the row: cost_cents and email never reach the client.
  • FastAPI builds /openapi.json from the routes and Pydantic’s JSON Schema on the first request, then caches it.
  • /docs is Swagger UI from a CDN, reading /openapi.json and sending real requests to the app.
DEEP DIVE: JSON written by Pydantic, response_model or the annotation, streaming JSON Lines and events, docs without a CDN

JSON written by Pydantic

Since FastAPI 0.130.0, a route with a response model and the default response class serializes with Pydantic’s TypeAdapter.dump_json, which writes the bytes in compiled code with no Python dict in between. Setting any response_class falls back to dump_python and that class’s render.

ORJSONResponse and UJSONResponse are deprecated since 0.131.0. An endpoint with no response model still goes through jsonable_encoder, which turns dates, decimals and models into plain JSON types first.

response_model or the annotation

response_model= on the decorator wins over the return annotation, which helps when the function returns a dict but the docs should show a model. response_model=None turns the filter and the schema off. A returned Response subclass passes straight through, unfiltered.

Streaming JSON Lines and events

An endpoint written as a generator can stream its items one at a time instead of building one body in memory: as JSON Lines since 0.134.0, and as server-sent events since 0.135.0.

Docs without a CDN

FastAPI pins only the major version, swagger-ui-dist@5, so the files it loads can change under you, and a network without cdn.jsdelivr.net gets a blank page. Set docs_url=None, serve the JavaScript and CSS from your own static files, and add a route that returns get_swagger_ui_html(openapi_url=…, swagger_js_url=…, swagger_css_url=…) pointing at them. ReDoc works the same way with get_redoc_html.

async def or def: the event loop and the thread pool

The bookshop now emails a confirmation for every order, and the mail server takes about 2 s to answer. Uvicorn runs every request of a process on one event loop thread, so what an endpoint does while it waits decides whether other customers keep getting answers. FastAPI chooses where to run each function by how you declared it. When should an endpoint be async def, and what happens when one blocks?

STEP 01 / 04

THE MAP SO FAR

Fig 9.1The accent parts are new: the thread pool, a background task in it, and the mail server.

At the bottom of the process sits a thread pool: 40 threads beside the one that runs the event loop. FastAPI runs every endpoint and dependency written with plain def on one of them, so a slow call there holds a pool thread, not the loop.

Inside the pool sits a background task, a function FastAPI runs after the reply has gone out: send_confirmation(). It hands the email to the mail server over SMTP, outside the process at the right.

STEP 02 / 04

A DEF ENDPOINT RUNS IN THE THREAD POOL

Fig 9.2Two paths from the route handler. The accent path hands a def endpoint to a pool thread.

The route handler checks how the endpoint was declared. An async def endpoint is awaited right on the loop thread. A def endpoint goes through Starlette’s run_in_threadpool, which calls anyio.to_thread.run_sync to run it on a pool thread, and the loop serves other requests while it waits.

Sync dependencies such as get_db take the same path. The pool is anyio’s default limiter, 40 tokens per event loop, so with 40 calls already running the next one waits for a free thread. The async Python tutorial shows the same hand-off in plain asyncio, asyncio.to_thread.

STEP 03 / 04

ONE BLOCKING CALL IN ASYNC DEF STOPS EVERY REQUEST

Fig 9.33 versions of the endpoint on one scale. The accent bar finished last, behind the requests the loop ran first.

Send 3 requests at once to an endpoint that waits 2 s; the timings here are illustrative. With async def and time.sleep(2), the sleep holds the loop thread itself, so the requests run one after another and finish at 2 s, 4 s and 6 s.

With def and the same sleep, each request sleeps on its own pool thread and all finish at about 2 s. With await asyncio.sleep, each request pauses and hands the loop back, with the same result. Any blocking library call, such as requests.get, a sqlite3 query or an SMTP send, behaves like time.sleep.

SHOP/MAIN.PY: THREE WAYS TO WAIT
import asyncio
import time


@app.get("/slow-async")
async def slow_async():
    time.sleep(2)             # blocks the loop thread: no other request runs
    return {"ok": True}


@app.get("/slow-def")
def slow_def():
    time.sleep(2)             # blocks one pool thread; the loop serves others
    return {"ok": True}


@app.get("/slow-await")
async def slow_await():
    await asyncio.sleep(2)    # pauses this request; the loop serves others
    return {"ok": True}
STEP 04 / 04

BACKGROUND TASKS RUN AFTER THE RESPONSE IS SENT

Fig 9.4Follow 1 to 4. The client has its reply at 2; the accent task runs after it, in the same process.

create_order takes a tasks: BackgroundTasks parameter and calls tasks.add_task(send_confirmation, order.email, row["id"]). Nothing runs yet. The response sends its start and body messages, so the client already has its 201, and only then does Starlette run the task, inside the same ASGI call.

send_confirmation is a def, so it runs on a pool thread, about 2 s of SMTP while the loop serves other requests. After the tasks, the code after yield in get_db closes the connection. Tasks run in the order you added them, and one that raises stops the ones after it.

SHOP/MAIN.PY: THE CONFIRMATION AFTER THE REPLY
from fastapi import BackgroundTasks


def send_confirmation(email: str, order_id: int) -> None:
    ...                       # an SMTP call that takes about 2 seconds


@app.post("/orders", status_code=201, dependencies=[Depends(require_key)])
def create_order(order: OrderIn, db: DB, tasks: BackgroundTasks) -> OrderOut:
    row = save_order(db, order)
    tasks.add_task(send_confirmation, order.email, row["id"])  # runs after the reply
    return row

COMMON QUESTIONS

Should I make every endpoint async def?
Only when every wait inside it uses await. When you call blocking libraries, def is the safe choice.
Can I raise the 40-thread limit?
Yes: in lifespan, raise total_tokens on the limiter that anyio’s to_thread.current_default_thread_limiter() returns. More threads help only when they spend their time waiting.
Do the 40 threads use 40 CPU cores?
No. On the standard CPython build only one thread at a time runs Python code. More cores need more processes, which is chapter 10.

WHAT YOU NOW KNOW

  • A def endpoint or dependency runs in a pool of 40 threads; an async def endpoint runs on the event loop thread.
  • One blocking call in async def holds the loop: 3 requests of 2 s each finish at 2 s, 4 s and 6 s.
  • Background tasks run in the same process after the response is sent, so a restart loses them.
DEEP DIVE: the 40-thread limiter, run_in_threadpool in async code, mixing sync and async libraries, when to use a real queue

The 40-thread limiter

anyio keeps one CapacityLimiter(40) per event loop, and everything that runs sync code shares it: def endpoints, sync dependencies, sync background tasks, and a StreamingResponse over a plain iterator. When every token is taken the next call waits, so a burst of slow def endpoints can delay a quick one.

run_in_threadpool in async code

Inside an async def endpoint, await run_in_threadpool(fn, *args) from starlette.concurrency runs one blocking call on the pool and keeps the rest of the function on the loop. Use it for a single call into a blocking library, such as a file read or a sqlite3 query, when the rest of the endpoint awaits other things.

Mixing sync and async libraries

Most blocking clients have an async counterpart: httpx.AsyncClient for requests, asyncpg for psycopg, aiosmtplib for smtplib. One blocking call anywhere in an async def, even in a helper three calls down, is enough to stall the process. asyncio’s debug mode logs every step slower than 100 ms, which finds them.

When to use a real queue

A background task is gone if it raises or if the process stops, and nothing records whether it ran. A job queue stores each job outside the web process, runs it in separate processes and retries failures, so an email survives a deploy. Keep background tasks for work you can lose, such as warming a cache.

Running it for real: workers and proxies

One Uvicorn process runs Python on one core, and the shop’s server has 4. In production the app also sits behind a load balancer, so every connection arrives from the balancer’s address, not the customer’s. Uvicorn handles both: it can run several copies of the app and read the customer’s address from a header. How does one app use every core, and how does it learn the real client address behind a proxy?

STEP 01 / 04

THE MAP SO FAR

Fig 10.1The accent parts are new: the main process, the other workers, and the load balancer in front.

In production the process you start is the main Uvicorn process. It binds the socket once and starts worker processes, each a full copy of everything drawn below it: event loop, app, middleware and thread pool. The map draws one worker in full and the others as chips.

Above them sits the load balancer at 10.0.1.5, a reverse proxy: customers connect to it, and it opens its own connections to the workers. Every part of the service is now on the map.

STEP 02 / 04

EACH WORKER IS A SEPARATE PROCESS WITH ITS OWN APP

Fig 10.2One socket, 4 workers. The accent arrows are the parent’s pings, one every 0.5 s.

With --workers 4, the main process binds 0.0.0.0:8000 once and starts 4 child processes with the spawn method. Each imports shop.main:app and runs its own event loop, lifespan and thread pool. The kernel hands each new connection on the shared socket to one of them.

Every 0.5 s the parent pings each worker over a pipe. A worker that stays silent for 5 s is killed and replaced, and the log says Child process [pid] died. Sending SIGHUP to the parent restarts the workers one at a time.

STEP 03 / 04

DEV AND PRODUCTION COMMANDS SET DIFFERENT DEFAULTS

Fig 10.3Three commands, the same rows. The accent column is the one meant for production.

fastapi dev shop/main.py binds 127.0.0.1:8000 with reload on, for your laptop. fastapi run shop/main.py binds 0.0.0.0:8000, every network interface, with reload off and 1 worker unless you pass --workers. Both start Uvicorn for you, and both come with pip install "fastapi[standard]".

uvicorn shop.main:app is the same server with its own defaults: 127.0.0.1:8000, reload off, 1 worker. A plain pip install fastapi installs a fastapi command that only tells you to install fastapi[standard], and no Uvicorn at all.

DEVELOPMENT AND PRODUCTION
# development: reload on, this machine only
$ fastapi dev shop/main.py

# production: every interface, four workers, trust the load balancer
$ fastapi run shop/main.py --workers 4 --forwarded-allow-ips 10.0.1.5

# the same with Uvicorn directly
$ uvicorn shop.main:app --host 0.0.0.0 --workers 4 --forwarded-allow-ips 10.0.1.5
STEP 04 / 04

BEHIND A PROXY, THE CLIENT ADDRESS COMES FROM A HEADER

Fig 10.4Follow 1 to 3. The accent chip is the scope after Uvicorn trusts the balancer’s headers.

The customer at 203.0.113.9 connects to the load balancer at 10.0.1.5 over https. The balancer opens its own connection to a worker, so the socket sees 10.0.1.5 as the client, and adds two headers: X-Forwarded-For: 203.0.113.9 and X-Forwarded-Proto: https.

Uvicorn reads these headers by default, but only on connections from an address in --forwarded-allow-ips, which defaults to 127.0.0.1,::1. Start it with --forwarded-allow-ips 10.0.1.5 and the scope’s client becomes 203.0.113.9 and its scheme https, so access logs show the customer and redirects keep https.

COMMON QUESTIONS

How many workers should I run?
Start with one per CPU core and measure. In Kubernetes, run one worker per container and let replicas add processes.
Do I still need Gunicorn?
Usually not. Uvicorn’s own supervisor now restarts dead workers. Gunicorn with Uvicorn workers still works, through the separate uvicorn-worker package.
Does every worker run the lifespan?
Yes. With 4 workers, lifespan runs 4 times at startup and opens 4 database connections, one in each process.

WHAT YOU NOW KNOW

  • --workers 4 starts 4 processes on one socket, each with its own app, loop, lifespan and thread pool.
  • fastapi run binds 0.0.0.0 without reload; fastapi dev and --reload are for development only.
  • Behind a load balancer, list its address in --forwarded-allow-ips so the scope carries the customer’s address.
DEEP DIVE: the supervisor’s health checks and signals, graceful shutdown, limits that protect a worker, serving under a path prefix

The supervisor’s health checks and signals

The parent pings each worker over a pipe every 0.5 s and gives it 5 s to answer (--timeout-worker-healthcheck, since Uvicorn 0.37). SIGINT and SIGTERM stop everything, SIGHUP restarts the workers one by one (0.51), SIGTTIN adds a worker and SIGTTOU removes one.

A worker that exits with code 3, Uvicorn’s code for a failed startup, stops the parent instead of being restarted (0.50), so an app that can’t boot doesn’t restart forever.

Graceful shutdown

On SIGTERM a worker logs “Shutting down”, stops accepting connections, waits for open requests to finish, then runs the lifespan shutdown. --timeout-graceful-shutdown caps that wait; by default there is no cap. Idle keep-alive connections close after 5 s.

Limits that protect a worker

--limit-concurrency answers 503 once that many connections or tasks are open. --limit-max-requests restarts a worker after that many requests, and --limit-max-requests-jitter (0.41) spreads those restarts so the workers don’t all recycle at once. --backlog, 2,048 by default, is how many connections the kernel queues before Uvicorn accepts them.

Serving under a path prefix

When the proxy serves the app at /shop, start it with --root-path /shop (fastapi run takes the same flag), so /docs and redirects build URLs that include the prefix. FastAPI(root_path=…) is deprecated since 0.146.0.

ERRORS THIS CHAPTER EXPLAINS

Child process [pid] died
a worker crashed, or missed its health check for 5 s
the parent starts a new one; the lines above it in the log show why
every client logged as the load balancer’s address
the balancer is not in --forwarded-allow-ips
add its address, such as --forwarded-allow-ips 10.0.1.5

The whole picture

Here is every part from the ten chapters on one map, numbered to match the table below.

Find a number on the map, then its row below: what the part does, what it is attached to and what it checks.

ONE REQUEST, END TO END

A POST /orders reaches the socket (1), the parser (2) reads it, and the event loop (3) starts a task that calls the app through ASGI (4). It passes the middleware layers (7, 8, 9) to the router (5). The route handler (12) checks the body with the models (11), solves the dependencies (14) and calls the endpoint (13). The response model (15) filters the reply, and the background task (18) runs once it has gone.

  1. 1socket

    accepts connections on one address and port

    attached to
    Uvicorn; bound once and shared by every worker
    checks
    nothing; it only accepts connections
    when wrong
    “Address already in use” at startup, or clients refused
  2. 2HTTP parser

    turns bytes into a method, path, headers and body

    attached to
    each connection, inside Uvicorn
    checks
    that the bytes are valid HTTP
    when wrong
    a request rejected before your app logs anything
  3. 3event loop

    runs every request of one worker on one thread

    attached to
    the worker process
    checks
    nothing; it runs whichever request is ready
    when wrong
    every request slow at once: something blocks the loop
  4. 4ASGI interface

    the one call between server and app: scope, receive, send

    attached to
    the line between Uvicorn and the app
    checks
    that the reply starts before its body is sent
    when wrong
    “Expected ASGI message 'http.response.start'” in the log
  5. 5router

    sends each request to the first route that fully matches

    attached to
    the app, holding its routes in order
    checks
    the path, then the method
    when wrong
    a 404 for a path you defined: an earlier route caught it
  6. 6Request and Response

    wrap the scope; send the status, headers and body

    attached to
    each endpoint call
    checks
    nothing; they only carry the data
    when wrong
    a header lookup that never matches: names arrive lowercased
  7. 7ServerErrorMiddleware

    turns an unhandled exception into a plain 500

    attached to
    the outermost layer of the app
    checks
    nothing; it catches what every other layer missed
    when wrong
    a plain-text 500 and a traceback in Uvicorn’s log
  8. 8your middleware

    runs your code around every request

    attached to
    inside ServerErrorMiddleware, in list order
    checks
    whatever you write, such as allowed CORS origins
    when wrong
    a browser CORS error while the same call works from curl
  9. 9ExceptionMiddleware

    turns an HTTPException into its status and body

    attached to
    just outside the router
    checks
    which handler matches the exception
    when wrong
    “Caught handled exception, but response already started.”
  10. 10lifespan

    runs setup before the first request and cleanup after the last

    attached to
    the app, once per worker process
    checks
    nothing; it opens and closes shared resources
    when wrong
    “Application startup failed. Exiting.” and no server
  11. 11Pydantic models

    check data against type hints and turn it back into JSON

    attached to
    the route handler, for inputs and outputs
    checks
    types, ranges and required fields
    when wrong
    a ValidationError listing every bad field
  12. 12route handler

    reads the signature, validates every input, calls the endpoint

    attached to
    each path operation, inside the router
    checks
    that every parameter passes its Pydantic check
    when wrong
    a 422 with a detail list, and your endpoint never runs
  13. 13endpoint

    your function for one path and method

    attached to
    its route
    checks
    your business rules
    when wrong
    the HTTPException you raise, such as 404 “Book not found”
  14. 14dependencies

    run shared setup and cleanup before the endpoint

    attached to
    parameters declared with Depends()
    checks
    whatever they check, such as the API key
    when wrong
    a 401 from the key check, or a connection closed too early
  15. 15response model

    filters and serializes what the endpoint returns

    attached to
    the endpoint’s return annotation
    checks
    that the return value fits the model
    when wrong
    a 500 with ResponseValidationError in the log
  16. 16OpenAPI and /docs

    describe every route and let people try them

    attached to
    /openapi.json, /docs and /redoc on the app
    checks
    nothing; it only describes the routes
    when wrong
    a blank /docs page: the CDN is blocked
  17. 17thread pool

    runs def endpoints and dependencies off the loop thread

    attached to
    each worker, 40 threads by default
    checks
    nothing; it runs what it is given
    when wrong
    def endpoints waiting once 40 calls are already running
  18. 18background tasks

    run work after the reply has been sent

    attached to
    the response
    checks
    nothing; they run once, in order
    when wrong
    an email never sent after the worker restarted
  19. 19supervisor and workers

    runs several copies of the app and replaces dead ones

    attached to
    the main Uvicorn process
    checks
    that each worker answers its ping within 5 seconds
    when wrong
    “Child process [pid] died” in the log
  20. ·TestClient

    calls the app as a function in tests

    attached to
    your test code
    checks
    nothing; it sends what the test asks
    when wrong
    lifespan never ran: the client was not used in a with block
  21. ·proxy headers

    take the client address and scheme from a trusted proxy

    attached to
    each connection
    checks
    that the sender is listed in forwarded-allow-ips
    when wrong
    every client logged with the load balancer’s address
  22. ·load balancer

    spreads customer traffic over servers

    attached to
    in front of the socket
    checks
    nothing that Uvicorn sees
    when wrong
    all traffic on one server, or the wrong client address
  23. ·reloader

    restarts the server when a .py file changes

    attached to
    --reload, in development only
    checks
    changes to Python files
    when wrong
    --workers ignored, and restarts in production

THREE THINGS TO KEEP

  • Each layer is an async function that calls the next one. Uvicorn calls Starlette, and Starlette calls your code.
  • FastAPI reads your function’s type hints, and Pydantic checks every input against them before your code runs.
  • Never wait without await inside an async endpoint. One blocking call there stalls every request in that worker.
Read next. Async Python: how one thread checks 100 links for the event loop and tasks every worker runs on, and Chain of Responsibility in Starlette’s middleware for the pattern behind the layers.
$ uvicorn shop.main:app
INFO: 127.0.0.1:51234 - "POST /orders HTTP/1.1" 201 Created