01B.7 FastAPI Basics: Building a Small API
Almost every AI product you will build has a service in the middle: a program that holds the provider API keys, checks who is calling, applies your business rules, and streams answers back to a browser or another service. FastAPI is the Python framework this path uses for that job — it is async-native, validates every request and response with the Pydantic models you already know from 01B.6, generates interactive API documentation for free, and streams Server-Sent Events with three lines of code. In this lesson you will build a small but real API — a toolkit service with health, echo, completion and streaming endpoints — and learn every mechanism a production service needs around those endpoints: dependencies, middleware, auth, error handling, uploads, testing and deployment shape. No LLM calls appear here; the "model" is a fake backend that returns canned text, so every example runs offline.
What you'll learn
- What an API service does in an AI product, and why FastAPI (async, Pydantic, OpenAPI, streaming, dependency injection) is the default choice — with an honest comparison against Flask, Django, Litestar and raw Starlette
- How a request travels through ASGI, Uvicorn and your app — and the difference between
async defanddefendpoints - Path, query, header, cookie and body parameters; how FastAPI decides which is which; validation,
422errors and theAnnotatedstyle - Request and response models:
response_model, status codes,HTTPException, custom exception handlers and a consistent JSON error shape - The lifespan hook for building shared clients once,
app.state, and dependency injection withDepends— includingyielddependencies andapp.dependency_overridesfor tests APIRouter,BackgroundTasksversus a real queue, and middleware: request IDs, timing and safe CORS- Security basics for a service that proxies paid APIs: API-key auth with constant-time comparison, OAuth2/JWT awareness, CORS pitfalls, rate limits, body-size limits, proxy headers and docs exposure
- Streaming responses:
StreamingResponse, JSON Lines, Server-Sent Events with FastAPI's built-infastapi.ssesupport, disconnect handling, and when WebSockets are the right tool instead - File uploads and form data, testing with
TestClientandhttpx.ASGITransport, the OpenAPI schema as a contract,/v1versioning and health/readiness endpoints - The complete
aitoolkit/service.pydeliverable:/health,/echo,/completeand/stream, ready to run withuvicorn
What you don't need
- Any API keys. Everything here runs against a fake in-process backend. Provider keys only ever appear as placeholders, and the lesson shows why they must stay on your server.
- Prior web-framework experience. If you have used Flask, Django, Express or Spring you will recognise the shape immediately; the "Coming from another stack" callouts map the differences.
- Deep HTTP knowledge — Module 00's HTTP lessons cover the wire; this lesson assumes you know what a request, response, header and status code are.
- You should have finished 01B.3 (async/await), 01B.5 (httpx, SSE parsing) and 01B.6 (Pydantic), because the service is built from all three.
Setup
The code needs Python 3.11+ (3.13 recommended, matching the rest of the path) and the web packages below. The samples were checked against fastapi 0.162, pydantic 2.14 and pydantic-settings 2.16 as of November 2026; FastAPI is still a 0.x library, so a newer release can change behaviour, and the FastAPI release notes are the place to check if something does not match. If you are continuing the aitoolkit project from earlier lessons, just add the web packages:
uv add "fastapi[standard]" httpx pydantic pydantic-settings python-dotenv
# or, with pip inside your environment:
# pip install "fastapi[standard]" httpx pydantic pydantic-settings python-dotenvfastapi[standard] is the batteries-included extra: it pulls in uvicorn[standard] (the ASGI server), fastapi-cli (the fastapi dev/fastapi run commands), python-multipart (required for form data and file uploads — bare fastapi does not include it), jinja2, pydantic-settings, pydantic-extra-types, email-validator, fastar, httpx and httpx2, and OpenTelemetry hooks. If you install bare fastapi instead, you must add uvicorn[standard] and python-multipart yourself before uploads work.
First time? Create the project first — uv init aitoolkit --package --python 3.13 && cd aitoolkit gives you the src/-layout package every lesson in this module builds on (the details are in 01B.1). No .env keys are needed for this lesson; the service's own demo tokens are plain configuration shown inline.
What you must be able to do after this lesson#
- Explain what an API service does in an AI product
- Build a FastAPI app with path, query and body parameters
- Define request and response models and return consistent error responses
- Build shared clients once in the lifespan hook and inject them with Depends
- Protect a paid-API proxy with API-key auth and limits
- Stream a response with StreamingResponse or Server-Sent Events
- Test endpoints with TestClient and dependency overrides
Why this matters for an AI engineer#
You will meet FastAPI again every time the path builds something that faces users or other services. These are the phrases and decisions this lesson makes possible:
| You'll hear... | You'll understand it after... |
|---|---|
| "Put the LLM call behind a FastAPI service so the key never reaches the browser." | 1.1 What an API service does |
| "FastAPI is just Starlette plus Pydantic — what's the difference?" | 1.3 ASGI, Uvicorn and Starlette |
"Why is async def faster than def here — and when is def actually fine?" |
4.1 async def vs def endpoints |
"Build the httpx.AsyncClient once in lifespan, not per request." |
4.2 Lifespan and app.state |
"Use Depends for the settings, the backend and the auth check." |
4.4 Dependency injection |
| "The 422 body is ugly — make errors consistent." | 3.2 Errors: status codes, HTTPException and handlers |
| "Stream tokens to the UI with SSE, not polling." | Part 6: Streaming responses |
| "The docs endpoint is an attack surface in production." | 5.4 Rate limits, sizes, proxies and docs |
| "Test the API without starting a server or touching the network." | 7.2 TestClient and async tests |
"Never return the internal model — pick response_model fields." |
3.1 Request and response models |
Part 1: What an API service does in an AI product#
1.1 What an API service does in an AI product#
An API service (sometimes called a backend-for-frontend or just "the service") is the program that sits between your users' browsers and the expensive, secret-holding machinery: the LLM providers, the vector database, the file store. In an AI product it typically does five jobs:
- Holds the secrets. Provider API keys live in the service's environment, never in the browser bundle. Lesson 03.1, 3.5 explains why a key shipped to a browser is a key published to the world; your service is the wall that keeps it there.
- Authenticates and authorises callers. It knows who is asking (a logged-in user, a tenant, an API key) and refuses the rest before any paid work starts.
- Applies product rules. Rate limits per user, input size caps, content policies, prompt templates, retrieval scope — decisions that must be enforced server-side because the client cannot be trusted.
- Calls the expensive things efficiently. It pools connections to providers, manages timeouts and retries (01B.9 owns those), caches, and fans work out concurrently (01B.4).
- Streams results back. LLM answers arrive token by token; the service relays them as Server-Sent Events so the UI can render progressively. Lesson 03.3, Part 11 builds exactly this pattern for provider streams — this lesson builds the FastAPI mechanics underneath it.
The service in this lesson is deliberately small — a fake completion backend that returns canned text — because the framework mechanics are identical whether the backend is a ScriptedBackend or a real provider SDK. Lesson 11C.1 takes the same shapes (settings, injected client, auth, SSE route, tests) to a production llm_service; lesson 07.11 does it for RAG; 08E.1 and 09.7 reuse the same patterns for MCP and voice servers.
1.2 The landscape: FastAPI vs Flask vs Django vs Litestar vs Starlette#
Python has several serious web frameworks. The honest comparison as of November 2026:
| Framework | Style | Async? | Validation | Auto docs | Best for |
|---|---|---|---|---|---|
| FastAPI | Decorated functions on an app object |
Native async def endpoints |
Pydantic models, automatic | OpenAPI + Swagger UI + ReDoc, generated | JSON APIs, ML/LLM services — the default choice here |
| Flask | Decorated functions on an app object |
Via async extra / ASGI adapters, not core |
Manual (Marshmallow etc.) | Via extensions (Flask-RESTX, apispec) | Traditional server-rendered apps, huge ecosystem, huge installed base |
| Django | Class-based views, ORM, admin, batteries | Async views since 3.1, ORM async since 4.1 | Forms/Serializers (its own) | Via drf-spectacular etc. | Full-stack monoliths with admin, ORM and auth built in — heavier than an API service needs |
| Litestar (formerly Starlite; 2.25.0 on PyPI as of Nov 2026) | Route handlers, controllers | Native, also supports Trio via AnyIO | msgspec/Pydantic/dataclasses, layered params | OpenAPI 3.1 with several UIs | Performance-focused APIs; similar feature set to FastAPI, smaller community |
| Starlette | ASGI toolkit: routes, responses, middleware — no validation or docs | Native (anyio: asyncio or Trio) | None built in | None built in | The layer under FastAPI; also usable directly for minimal ASGI services |
Why FastAPI wins for this path specifically:
- Pydantic is already your data layer. Every provider SDK returns Pydantic objects (01B.6); FastAPI turns the same models into request validation, response serialisation and the OpenAPI schema in one step.
- Async is the native model, matching the I/O-bound shape of LLM work: an endpoint that waits 5 seconds on a provider holds no thread.
- The ecosystem around it is the one the later modules assume:
TestClient,dependency_overrides,fastapi.sse, thefastapiCLI, and the deployment patterns in 11C.1. - Docs are generated, not written.
/docsgives you an interactive console for every endpoint — the same contract your front end and your tests consume.
Choose Flask/Django when you need their ecosystems (admin panels, server-rendered templates at scale, an existing codebase). Choose Litestar if you want similar features with msgspec-level speed and don't mind a smaller community. Choose raw Starlette only when you want the toolkit without the framework — rare in application code.
1.3 ASGI, WSGI, Uvicorn and Starlette under the hood#
To see why FastAPI looks the way it does, you need the two acronyms:
- WSGI (Web Server Gateway Interface, PEP 3333) is the old Python web standard: a synchronous callable that takes one request and returns one response. Flask and Django are WSGI frameworks. Its limitation is structural: one request occupies one worker for its whole duration, so a handler that waits 5 seconds on a network call wastes a worker thread for 5 seconds.
- ASGI (Asynchronous Server Gateway Interface) is the async successor: an application is an
asynccallable that receives anscope(what kind of connection:httporwebsocket), areceivecallable (to read request body/messages) and asendcallable (to write response messages). It supports long-lived connections — streaming responses, WebSockets — that WSGI cannot express.
flowchart LR
subgraph client ["Client (browser / curl / another service)"]
REQ["HTTP request"]
end
subgraph server ["ASGI server: Uvicorn"]
CONN["One asyncio task per connection:<br/>reads bytes → ASGI messages"]
end
subgraph app ["Your FastAPI app (ASGI application)"]
MW["Middleware stack"] --> RT["Router: match path + method"]
RT --> DEP["Solve dependencies<br/>(Depends)"]
DEP --> VAL["Validate params & body<br/>(Pydantic)"]
VAL --> EP["Path operation<br/>(async def or def)"]
EP --> SER["Serialise response<br/>(response_model → JSON)"]
end
REQ --> CONN --> MW
SER --> CONN --> RES["HTTP response"]The layers, outside in:
- Uvicorn is the ASGI server: it owns the sockets, parses HTTP, runs the asyncio event loop and speaks ASGI messages to your app. It is to FastAPI what
php-fpm/gunicornis to PHP or what Node'shttpserver is to Express.uvicorn[standard]adds faster C-backed HTTP parsing (httptools), theuvloopevent loop on POSIX,watchfilesfor reload andwebsocketssupport. - Starlette is the web toolkit FastAPI is built on: routing, requests/responses, middleware, static files, templates, WebSockets, the TestClient. FastAPI 0.162.0 requires
starlette>=0.46.0(Starlette itself is at 1.10.0 as of November 2026 — it went 1.x in March 2026, and itsTestClientnow useshttpx2, Pydantic's httpx fork). - FastAPI adds the application layer on top: the
@app.getdecorators, Pydantic-powered parameter parsing and validation,Dependsdependency injection, automatic OpenAPI generation and the docs UI.
So "FastAPI" in a uvicorn main:app command means: Uvicorn serves the ASGI callable that is your FastAPI app, which delegates HTTP mechanics to Starlette and data contracts to Pydantic. When people say "FastAPI is just Starlette plus Pydantic", this is literally true — and it is a feature: the seams are clean, and you can drop to Starlette or Pydantic directly when you need to.
1.4 Anatomy of one request#
Here is what happens when curl http://localhost:8000/v1/echo arrives, end to end:
- Uvicorn accepts the TCP connection, reads the request head and body, and wraps them in ASGI
httpscope/receive messages. - The FastAPI app (Starlette underneath) runs the middleware stack outermost-first: your request-ID middleware, CORS, GZip, etc. Each wraps the next like onion layers.
- The router matches
POST /v1/echoto the path operation and resolves its dependencies:Depends(get_settings),Depends(require_api_key)— each runs once per request, in dependency order, and its result (or itsHTTPException) is injected into the handler signature. - Validation: path params, query params, headers, cookies and the JSON body are parsed and validated against the declared types and Pydantic models. Any failure short-circuits with
422before your code runs. - The path operation executes —
async defon the event loop, ordefin a worker thread (Part 4 explains the difference). - The return value is checked against
response_model, serialised to JSON, passed back out through the middleware stack, and Uvicorn writes the status line, headers and body to the socket.
Two consequences worth internalising now:
- Validation happens before your code. A malformed request never reaches the handler; FastAPI answers
422with a structured body listing every error. That is the same Pydantic validation you met in 01B.6, applied automatically to the HTTP boundary. - Dependencies are the seam for everything cross-cutting. Auth, settings, database sessions, the shared backend client — all are
Dependsfunctions, which is also why tests can swap them out (7.2).
Part 2: Your first app#
2.1 FastAPI() and path operations#
A FastAPI application is one object plus functions decorated with HTTP-method decorators. Create main.py:
# main.py — the smallest useful FastAPI app
from fastapi import FastAPI
app = FastAPI(title="aitoolkit demo", version="0.1.0")
@app.get("/")
def read_root() -> dict:
return {"service": "aitoolkit", "status": "ok"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None) -> dict:
return {"item_id": item_id, "q": q}Three things to notice:
app = FastAPI(...)creates the application.titleandversionshow up in the docs and the OpenAPI schema; there are many more options (description,docs_url,redoc_url,openapi_url,lifespan,dependencies,middleware— covered below).@app.get("/items/{item_id}")is a path operation decorator: it registersread_itemas the handler forGETrequests whose path matches/items/<something>. The{item_id}segment is a path parameter — the part of the URL that varies. FastAPI supportsget,post,put,patch,delete,options,headandtrace, plus@app.api_route(..., methods=[...])for custom combinations and@app.websocket(...)for WebSocket endpoints (Part 6 touches WebSockets).- The function's signature is the contract.
item_id: inttells FastAPI to extract the path segment and coerce it toint;q: str | None = Nonetells it there is an optional query parameterq. The return value is serialised to JSON automatically — adict, a Pydantic model, alist, even a plainstr(which becomes a JSON string) all work.
Run it (Part 2.4 shows the commands) and try:
GET / → {"service": "aitoolkit", "status": "ok"}
GET /items/42 → {"item_id": 42, "q": null}
GET /items/42?q=hello → {"item_id": 42, "q": "hello"}
GET /items/abc → 422 (item_id is not an int)That last line is the first taste of FastAPI's signature feature: types do validation. item_id: int is not a hint for readers — FastAPI parses "42" into 42, rejects "abc" with a structured 422 error, and documents both in the OpenAPI schema.
2.2 The five kinds of parameters#
Every input to an endpoint arrives in one of five places. FastAPI decides which from the annotation and the function signature:
| Kind | Where it lives | How you declare it | Example |
|---|---|---|---|
| Path parameter | Inside the URL path: /items/{item_id} |
Name must match the {...} in the decorator; annotate the type |
item_id: int |
| Query parameter | After ? in the URL |
A simple-typed parameter that is not in the path | q: str | None = None, limit: int = 20 |
| Header parameter | HTTP headers | Annotated[str | None, Header()] or Header(...) default |
x_request_id: Annotated[str | None, Header()] = None |
| Cookie parameter | Cookie: request header |
Annotated[str | None, Cookie()] |
session_id: Annotated[str | None, Cookie()] = None |
| Body parameter | The request body (usually JSON) | A Pydantic model, dict, list, or a scalar wrapped in Body() |
item: Item, payload: Annotated[dict, Body()] |
| Dependency | Anywhere (computed per request) | Annotated[T, Depends(func)] |
settings: Annotated[Settings, Depends(get_settings)] |
The decision rules, in order:
- If the name appears as
{name}in the path string → path parameter. - If the annotation is a Pydantic
BaseModel(or adict/listof them, orBody(...)) → body parameter. Singular scalar types (int,str,datetime,UUID…) are never bodies on their own — wrap them inBody()if you want one. - If wrapped in
Header()/Cookie()/Path()/Body()/Form()/File()→ that explicit kind. - Otherwise, a simple type → query parameter.
A single endpoint can mix all of them:
# params.py — every parameter kind in one signature
from typing import Annotated
from fastapi import Cookie, FastAPI, Header, Path, Query
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
name: str = Field(min_length=1, max_length=100)
price: float = Field(gt=0)
tags: list[str] = Field(default_factory=list)
@app.post("/items/{item_id}")
def update_item(
item_id: Annotated[int, Path(ge=1, description="the item to update")],
item: Item,
verbose: Annotated[bool, Query(description="include debug fields")] = False,
x_request_id: Annotated[str | None, Header()] = None,
session_id: Annotated[str | None, Cookie()] = None,
) -> dict:
return {
"item_id": item_id,
"item": item.model_dump(),
"verbose": verbose,
"x_request_id": x_request_id,
"session_id": session_id,
}Send POST /items/7?verbose=true with header X-Request-ID: abc and cookie session_id=xyz plus a JSON body {"name": "Portal Gun", "price": 999.99} and you get all six values back. Note x_request_id maps to the X-Request-ID header automatically — FastAPI converts underscores to hyphens for headers and cookies.
2.3 Validation, 422 responses and the Annotated style#
Where the 422 comes from. When validation fails — a path segment that isn't an int, a missing required query param, a body that doesn't match the model — FastAPI does not call your function. It returns 422 Unprocessable Content (the status code was renamed from 422 Unprocessable Entity in RFC 9110; FastAPI uses the new name in its docs and HTTP_422_UNPROCESSABLE_CONTENT constant) with a body shaped like:
{
"detail": [
{
"type": "int_parsing",
"loc": ["path", "item_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "abc"
}
]
}loc tells you where the error is (path, query, header, cookie, body followed by the field path), type/msg are Pydantic's error codes and messages, and input echoes what was sent. This is deliberately the same error vocabulary as ValidationError from 01B.6 — you can feed detail straight back to an LLM as a repair prompt, the same trick 03.4 uses for model output.
Annotated is the current recommendation. FastAPI's docs now show metadata in Annotated[T, ...] rather than as a default value, because it keeps the default (= None, = 20) separate from the validation metadata and reads cleanly with type checkers:
# Old style (still works): limit: int = Query(10, ge=1, le=100)
# Current style: limit: Annotated[int, Query(ge=1, le=100)] = 10The metadata objects — Query, Path, Header, Cookie, Body, Form, File, Depends, Security — all live in fastapi and share the same knobs: default, description, examples, deprecated, include_in_schema, plus the Pydantic Field constraints (ge, le, min_length, pattern, …) where they apply. Query(...) with ... (Ellipsis) marks a parameter required; Query(None) or = None makes it optional.
2.4 Running it: fastapi dev, fastapi run and uvicorn#
The fastapi command (from the fastapi-cli package, included in fastapi[standard]) is the front door:
# Development: auto-reload on file changes, finds your app automatically
uv run fastapi dev
# The same thing spelled out — watch mode + explicit entrypoint
uv run fastapi dev main.py
uv run uvicorn main:app --reload --host 127.0.0.1 --port 8000
# Production: no reload, workers for multiple cores
uv run fastapi run --workers 4 main.py
# or directly:
uv run uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4What each piece does:
fastapi devauto-detects your app — it assumes aFastAPIobject namedappinmain.py(or a couple of other conventional variants) — and starts Uvicorn with--reload, listening on127.0.0.1only. You can point it explicitly withfastapi dev main.py,fastapi dev --entrypoint aitoolkit.service:app, or[tool.fastapi] entrypoint = "aitoolkit.service:app"inpyproject.toml(the form the VS Code extension and FastAPI Cloud also read — worth setting for asrc/project). Before importing your app it setsFASTAPI_ENV=development(an existing value is preserved;fastapi runleaves it alone — the conventional values aredevelopment/production). It prints the server URL and the docs URL on startup.fastapi runstarts a production server — same Uvicorn underneath, no reloader.--workers Nspawns N processes; each is an independent copy of your app with its own memory (this matters for in-memory state — see 4.6 and the per-process warning in 5.4).uvicorn main:appis the underlying command both wrap;module:appis the import string —main.py'sappobject. Any ASGI app works here, not just FastAPI.
2.5 The interactive docs: /docs, /redoc, /openapi.json#
Start the server and open http://127.0.0.1:8000/docs. You get Swagger UI: every path operation listed, every parameter editable, a "Try it out" button that sends a real request and shows the real response — including your 422 errors. http://127.0.0.1:8000/redoc serves ReDoc, a cleaner read-only rendering of the same schema. http://127.0.0.1:8000/openapi.json returns the raw OpenAPI document — the machine-readable contract.
flowchart LR
subgraph docs ["What the docs are built from"]
SIG["Your function signatures<br/>+ Pydantic models<br/>+ decorators"] --> OA["OpenAPI JSON<br/>(/openapi.json)"]
end
OA --> SW["/docs — Swagger UI<br/>(interactive)"]
OA --> RD["/redoc — ReDoc<br/>(readable)"]
OA --> GEN["Generated clients<br/>(openapi-typescript,<br/>openapi-generator…)"]
OA --> CT["Your tests & contracts"]Three consequences:
- The docs cannot drift from the code. They are generated from the same signatures that validate requests, so they are always accurate — a property handwritten docs never have.
/openapi.jsonis a contract you can hand to other tools. Front-end type generators, API gateways, contract tests and SDK generators all consume it (7.3 returns to this).- The docs are also an attack surface. They reveal your whole API surface — every route, parameter and model — to anyone who can reach them. In production you usually disable or protect them (5.4).
Disable or relocate them per app:
app = FastAPI(
docs_url=None, # no /docs
redoc_url=None, # no /redoc
openapi_url=None, # no /openapi.json — also hides it from docs UIs
)
# or move them: docs_url="/internal-docs"Part 3: Request and response models#
3.1 Request and response models#
The body of a POST/PUT/PATCH is declared as a Pydantic model — the same BaseModel you validated in 01B.6. FastAPI parses the JSON body, runs model_validate, and injects the typed object:
# models_demo.py — request body in, response model out
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class TicketIn(BaseModel):
subject: str = Field(min_length=3, max_length=200)
priority: int = Field(default=3, ge=1, le=5)
tags: list[str] = Field(default_factory=list)
class TicketOut(BaseModel):
id: int
subject: str
priority: int
@app.post("/tickets", response_model=TicketOut, status_code=201)
def create_ticket(ticket: TicketIn) -> dict:
# the "stored" record carries staff-only fields; response_model strips them
return {
"id": 1,
"subject": ticket.subject.upper(),
"priority": ticket.priority,
"internal_note": "queued for triage", # never reaches the client
"owner_email": "ops@example.com", # never reaches the client
}Two separate models for input and output is the standard shape, for three reasons:
- Input and output contracts differ. Clients shouldn't have to send
id; servers often compute fields clients must not set. response_modelfilters what leaves. FastAPI validates and filters the return value throughTicketOut. If the handler returned a dict or an ORM object with extra keys (internal_note,owner_email,cost_usd— as above), only the fields declared onTicketOutare serialised; the extras never reach the wire. This is your first line of defence against leaking internals — the same "never expose provider keys" rule as 03.1 §3.5, applied to fields instead of credentials. Note the subtlety the example demonstrates:internal_notemust not be a field onTicketOut— a declared field is included in the output, so putting it there would leak it while looking protected.- The OpenAPI schema gets both shapes, so generated clients see exactly what to send and what to expect.
FastAPI also accepts the return type annotation as the response model: def create_ticket(ticket: TicketIn) -> TicketOut: filters and validates exactly like response_model=TicketOut, and a type checker then checks that the function really returns something compatible. The example above passes response_model= explicitly because the handler returns a plain dict that carries extra keys, which the annotation -> TicketOut would (rightly) reject in a type checker; when both are present, response_model wins.
response_model_exclude_none=True on the decorator (or response_model_exclude_unset, response_model_exclude_defaults, response_model_by_alias, response_model_exclude) trims null/unset fields from output — useful when your front end prefers absent keys to explicit nulls. Pydantic's own model_dump(exclude_none=True) does the same inside the model; the FastAPI flags apply it at the HTTP boundary for you.
3.2 Errors: status codes, HTTPException and handlers#
FastAPI gives you three layers of error handling, and a production service uses all three:
1. Validation errors → 422 automatically (Part 2.3). You rarely touch these, but you can customise the shape with @app.exception_handler(RequestValidationError) — useful for matching a company-wide error envelope.
2. Expected failures → HTTPException. For "the thing you asked for doesn't exist" or "you're not allowed", raise HTTPException inside the handler or a dependency:
from fastapi import FastAPI, HTTPException
app = FastAPI()
TICKETS = {1: {"id": 1, "subject": "Printer jammed", "priority": 2}}
@app.get("/tickets/{ticket_id}")
def get_ticket(ticket_id: int) -> dict:
if ticket_id not in TICKETS:
raise HTTPException(status_code=404, detail="ticket not found")
return TICKETS[ticket_id]HTTPException(status_code=..., detail=...) short-circuits the request and produces {"detail": "ticket not found"}. detail can also be a dict or list for structured errors. Status codes come from fastapi.status (a re-export of starlette.status — HTTP_404_NOT_FOUND, etc.) — learn the ones you use: 200 ok, 201 created, 202 accepted, 204 no content, 400 bad request, 401 unauthenticated, 403 forbidden, 404 not found, 409 conflict, 422 validation, 429 rate limited, 500 server error.
3. Unexpected failures → custom exception handlers. Register handlers for your own exception types and for the catch-all Exception:
# errors.py — a consistent JSON error envelope for the whole service
import logging
from fastapi import FastAPI, Request
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
logger = logging.getLogger(__name__) # structured logging lands in 01B.10
class ApiError(Exception):
"""Domain error with a stable machine-readable code."""
def __init__(self, status_code: int, code: str, message: str):
self.status_code = status_code
self.code = code
self.message = message
super().__init__(message)
def error_body(code: str, message: str, request_id: str | None = None) -> dict:
return {"error": {"code": code, "message": message, "request_id": request_id}}
def register_error_handlers(app: FastAPI) -> None:
@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError) -> JSONResponse:
return JSONResponse(status_code=exc.status_code,
content=error_body(exc.code, exc.message))
@app.exception_handler(RequestValidationError)
async def validation_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
# keep FastAPI's detailed 'loc/msg' list but wrap it in our envelope.
# jsonable_encoder: Pydantic error dicts can hold non-JSON values
# (input objects, ctx) — encode first or a weird input 500s your handler.
return JSONResponse(status_code=422, content={
"error": {"code": "validation_error", "message": "request failed validation",
"details": jsonable_encoder(exc.errors())},
})
@app.exception_handler(Exception)
async def unhandled_handler(request: Request, exc: Exception) -> JSONResponse:
# NEVER return str(exc) or a traceback to clients — it leaks internals.
# Log exc + request id (Part 4.7 middleware sets one) server-side instead.
logger.exception("unhandled error on %s %s", request.method, request.url.path)
return JSONResponse(status_code=500,
content=error_body("internal_error", "something went wrong"))Why bother: clients (your front end, your tests, other services) can rely on one error shape — {"error": {"code", "message", ...}} — instead of three different shapes ({"detail": ...} for HTTPException, {"detail": [...]} for 422, HTML or empty for crashes). Stable error contracts matter doubly when an LLM or agent consumes your API: a machine-readable code is something a retry policy or a tool call can branch on.
3.3 Response classes and content types#
By default a path operation returns JSON. When you need something else, return a Response object directly — returning a response bypasses response_model validation (the docs warn about this; it's the escape hatch, use it deliberately):
from fastapi import FastAPI
from fastapi.responses import HTMLResponse, PlainTextResponse, FileResponse, RedirectResponse
app = FastAPI()
@app.get("/health.txt", response_class=PlainTextResponse)
def health_text() -> str:
return "ok" # text/plain, not JSON
@app.get("/page", response_class=HTMLResponse)
def page() -> str:
return "<h1>aitoolkit</h1>" # text/html
@app.get("/monthly.pdf")
def monthly_pdf() -> FileResponse:
return FileResponse("data/reports/monthly.pdf", filename="monthly.pdf",
media_type="application/pdf")For streaming endpoints (StreamingResponse, SSE) see Part 6 — they produce response instances rather than a declared response_class, because the content is generated incrementally.
JSONResponse, PlainTextResponse, HTMLResponse, RedirectResponse, FileResponse, StreamingResponse and (since FastAPI 0.135.0) EventSourceResponse all live in fastapi.responses / fastapi.sse. Two rules of thumb:
- Prefer
response_class=on the decorator when the whole endpoint returns that type — it keepsresponse_modelfiltering and OpenAPI docs accurate. - Return a response instance when the content is produced incrementally (streams, files) or you need full control of headers/status.
3.4 Enums, lists and pagination parameters#
Three small patterns you'll use constantly:
Enums in paths and queries get automatic validation and documentation — an invalid value is a 422, and the docs render a dropdown:
from enum import Enum
from typing import Annotated
from fastapi import FastAPI, Query
app = FastAPI()
class Priority(str, Enum):
low = "low"
normal = "normal"
high = "high"
@app.get("/tickets")
def list_tickets(priority: Annotated[Priority | None, Query()] = None) -> dict:
return {"priority_filter": priority.value if priority else None}Lists arrive as repeated query params (?tag=a&tag=b) or as a JSON array in the body — declare list[str] and FastAPI handles both the OpenAPI schema (explode style) and parsing.
Pagination is just two query params with sane bounds — there is no magic, which is why it's worth getting right once:
@app.get("/tickets")
def list_tickets(
offset: Annotated[int, Query(ge=0)] = 0,
limit: Annotated[int, Query(ge=1, le=100)] = 20,
) -> dict:
# clamp server-side too: 'le=100' stops ?limit=1000000 doing damage,
# but your storage layer still needs its own cap — defence in depth.
return {"offset": offset, "limit": limit, "items": []}Cursor-based pagination (?cursor=eyJpZCI6NDJ9) is the production upgrade for large or mutable datasets — offset pagination skips/repeats rows when the underlying data changes mid-scroll. 05.8 and later data lessons use cursors; for this service, offset/limit is enough and honest about its limits.
Part 4: async endpoints, lifespan, app.state and dependencies#
4.1 async def vs def endpoints#
This is the single most important performance decision in a FastAPI app, and it connects directly to 01B.3:
async defendpoints run on the event loop. One loop per worker process; everyasync defendpoint shares it. While anasync defendpointawaits (anhttpxcall, a database driver,asyncio.sleep), the loop runs other requests. This is what makes a service that spends its life waiting on LLM APIs fast: thousands of concurrent requests can be in flight on one loop.defendpoints run in a thread pool (anyio's worker threads, sized ~40 by default). Starlette calls them viarun_in_threadpool, so blocking code —requests,time.sleep, a sync DB driver, CPU work — does not stall the loop. The cost: each occupies a thread, and threads are heavier than coroutines.
@app.get("/fast")
async def fast() -> dict:
await asyncio.sleep(0.1) # yields to the loop: other requests proceed
return {"ok": True}
@app.get("/slow-sync")
def slow_sync() -> dict:
time.sleep(0.1) # blocks a worker THREAD, not the loop
return {"ok": True}The trap is the combination: async def + blocking call. If an async def endpoint calls time.sleep(5) or a synchronous requests.get, it freezes the entire event loop — every other request on that worker stalls for 5 seconds. This is the same "forgot that sync code blocks the loop" bug from 01B.3, now with a web server attached. The failure gallery at the end shows the symptom.
| Endpoint does... | Write it as | Why |
|---|---|---|
| Awaits async I/O (httpx.AsyncClient, async DB, SSE stream) | async def |
Scales to thousands of concurrent waits on one loop |
Blocking I/O or CPU work (sync SDK, requests, time.sleep, pandas crunch) |
def |
Starlette runs it in the thread pool; the loop stays free |
| Mixes both | async def that calls blocking work via anyio.to_thread.run_sync / asyncio.to_thread |
Keep the loop free without paying a thread for the whole request |
| Almost no work, just returns data | either — async def is idiomatic |
Consistency with the rest of the app |
4.2 Lifespan and app.state#
Some resources must be created once when the server starts and destroyed when it stops: the shared httpx.AsyncClient (connection pool), the provider client, a database engine, a vector-store handle. Creating them per request leaks connections and pays setup cost every call. FastAPI's lifespan hook is the place:
# lifespan.py — the startup/shutdown pattern every service in this path uses
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI
from aitoolkit.backend import ScriptedBackend # built in 01B.3
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
# ---- startup: runs once per worker process, before serving requests ----
backend = ScriptedBackend() # the fake "model"; swap for a real client later
app.state.backend = backend # hand it to dependencies via request.app.state
# In a real service this is where you build httpx.AsyncClient(),
# an AsyncEngine, a Redis pool — ONE per process, reused by all requests.
yield # <-- the app serves requests here
# ---- shutdown: runs once, after the server stops accepting requests ----
# ScriptedBackend owns no sockets or files — nothing to close. A real
# service releases what startup built here: await client.aclose(),
# await engine.dispose(), pool.close() — same position, real cleanup.
app = FastAPI(title="aitoolkit", lifespan=lifespan)@asynccontextmanager + yield is the shape: everything before yield is startup, everything after is shutdown. The older @app.on_event("startup")/("shutdown") decorators still exist but are deprecated in the docs in favour of lifespan — one hook, one ordering, proper async cleanup. Note the ordering guarantee: startup completes before the first request is served, and shutdown runs after in-flight requests drain (Uvicorn's graceful-shutdown window; 11C.1, 2.14 goes deeper).
app.state is Starlette's State object — a typed-ish bag for arbitrary attributes on the app (app.state.backend, app.state.settings, app.state.started_at). It exists so objects built once can be reached from anywhere without globals:
def get_backend(request: Request) -> ScriptedBackend:
return request.app.state.backend # the instance lifespan storedYou will also see app.state used for feature flags, the OpenAPI schema cache and test doubles. Prefer it over module-level globals: app.state is per-app-instance, so tests that build a second FastAPI() don't share state with the first.
4.3 app.state in practice#
from fastapi import FastAPI, Request
app = FastAPI()
app.state.service_name = "aitoolkit" # plain attributes work too
app.state.request_count = 0
@app.get("/state")
def show_state(request: Request) -> dict:
return {"service": request.app.state.service_name}request.app is how you reach it from a handler or dependency; app.state from startup code. Starlette documents State as supporting both attribute access (app.state.x) and mapping access (app.state["x"]).
4.4 Dependency injection with Depends#
Dependency injection (DI) means: instead of your endpoint constructing or reaching for its collaborators, you declare what it needs and FastAPI supplies it — once per request, with caching so shared sub-dependencies run only once.
# deps.py — dependencies are just functions (or classes) FastAPI calls for you
from typing import Annotated
from fastapi import Depends, FastAPI, Request
from aitoolkit.backend import ScriptedBackend
from aitoolkit.models import CompletionRequest
from aitoolkit.settings import Settings, get_settings
app = FastAPI()
def get_backend(request: Request) -> ScriptedBackend:
"""The shared backend built in lifespan — one per process."""
return request.app.state.backend
def get_admin_settings(
settings: Annotated[Settings, Depends(get_settings)],
) -> Settings:
"""A sub-dependency: builds on get_settings, could add checks."""
return settings
@app.post("/v1/complete")
async def complete(
body: CompletionRequest,
backend: Annotated[ScriptedBackend, Depends(get_backend)],
settings: Annotated[Settings, Depends(get_admin_settings)],
) -> dict:
# backend.complete() returns the backend's Completion dataclass —
# .text holds the canned reply (01B.3); Part 8 maps it into the
# pydantic Completion response model from 01B.6.
result = await backend.complete(body.prompt, model=body.model)
return {"text": result.text, "env": settings.app_env}The mechanics:
Depends(get_backend)tells FastAPI "callget_backendfor this request and pass its return value asbackend". The function can itself declare dependencies —get_admin_settingsdepends onget_settings— and FastAPI resolves the graph bottom-up, caching each dependency per request soget_settings()(itselflru_cached in 01B.2) andget_backendeach run once even if ten endpoints need them.- Dependencies can be sync or async, can raise
HTTPException(a failed auth dep produces that status before the handler runs), and can return anything — settings, clients, a DB session, the current user. yielddependencies are the cleanup pattern — thetry/finallyof DI:
from collections.abc import Iterator
def db_session() -> Iterator[Session]: # Session/SessionLocal: SQLAlchemy-style, illustrative only
session = SessionLocal() # open
try:
yield session # handler runs with the open session
finally:
session.close() # runs AFTER the response is sentThe code after yield executes after the response — the right place to close a DB session or release a lock. (For async resources use async def + AsyncIterator + async with inside.)
app.dependency_overridesis the test seam:app.dependency_overrides[get_backend] = lambda: FakeBackend()swaps the dependency for tests without touching route code — 01B.8 uses this heavily, and 7.2 shows it.Security(...)isDependsplus OpenAPI security-scheme metadata — used for the API-key/OAuth2 flows in Part 5.
4.5 APIRouter and project structure#
One app object doesn't scale to a real service. APIRouter lets you split routes across modules and mount them with a shared prefix, tags and dependencies:
# aitoolkit/api_v1.py — routes for API version 1
from fastapi import APIRouter, Depends
from aitoolkit.deps import get_backend, require_api_key
from aitoolkit.models import Completion, CompletionRequest # 01B.6
# Part 8 keeps EchoIn/EchoOut in service.py; once routes move into their own
# module, move those two models into models.py as well so this import works.
from aitoolkit.models import EchoIn, EchoOut
router = APIRouter(prefix="/v1", tags=["v1"], dependencies=[Depends(require_api_key)])
@router.post("/echo")
def echo(body: EchoIn) -> EchoOut: ...
@router.post("/complete")
async def complete(body: CompletionRequest) -> Completion: ...# service.py — mount it once
from aitoolkit.api_v1 import router as v1_router
app.include_router(v1_router)Routers compose: a router can include another router; dependencies=[...] on the router applies auth to every route in it (better than repeating Depends(require_api_key) on each handler — you can't forget it). A sensible aitoolkit layout:
pyproject.toml
src/aitoolkit/
├── settings.py # 01B.2: Settings, get_settings()
├── backend.py # 01B.3: ScriptedBackend (the fake "model")
├── models.py # 01B.6: Pydantic request/response models
├── deps.py # Depends functions — only in the optional split (exercise 15)
├── service.py # this lesson: the FastAPI app, middleware, error handlers
├── api_v1.py # routes under /v1 (optional split; Part 8 keeps one file)
└── ...
tests/
└── test_service.py # 01B.8: TestClient + dependency_overrides4.6 BackgroundTasks vs a real queue#
BackgroundTasks lets a handler return its response first and run code after — "fire and forget inside the request":
from typing import Annotated
from fastapi import BackgroundTasks, Depends, FastAPI
from aitoolkit.backend import ScriptedBackend
from aitoolkit.deps import get_backend # the get_backend dependency from 4.4
app = FastAPI()
def write_audit_log(record: dict) -> None:
... # runs after the response is sent
@app.post("/v1/complete")
async def complete(
prompt: str,
background: BackgroundTasks,
backend: Annotated[ScriptedBackend, Depends(get_backend)],
) -> dict:
completion = await backend.complete(prompt) # a Completion dataclass
background.add_task(write_audit_log, {"prompt": prompt})
return {"text": completion.text} # .text is the reply stringThe task runs in the same process, after the response, before the request fully ends — fine for audit logs, metrics, cache warming. It is not durable: if the process dies, the task dies; there is no retry, no queue, no visibility. Decision table:
| Need | Use |
|---|---|
| Audit log, metric, cache warm — lose it, don't care | BackgroundTasks |
| Must survive restart, needs retry, fan-out to workers, rate-limited downstream | A real queue (Redis/RQ, Celery, SQS, Arq, Dramatiq) + worker process — 11C.1, 2.9 builds this shape |
| Long-running job the client polls for | 202 Accepted + job id + status endpoint (also 11C.1 §2.10) |
4.7 Middleware: request IDs, timing, CORS and friends#
Middleware wraps every request/response — the onion layers from 1.4. Two kinds exist:
@app.middleware("http")/ function middleware — simpler, but Starlette docs note it buffers responses and has caveats with streaming/websockets.- Pure ASGI middleware (a class with
__call__(scope, receive, send)) — the production choice: no buffering, works with streams, explicit. This is what 11C.1'sllm_serviceuses for structured logging.
Here is a minimal pure-ASGI middleware that adds a request ID and a Server-Timing-style header — the same pattern the deliverable in Part 8 uses:
# middleware.py — pure ASGI: request id + duration, no buffering
import time
import uuid
from collections.abc import Callable
class RequestContextMiddleware:
def __init__(self, app: Callable) -> None:
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http": # pass websockets/lifespan through untouched
await self.app(scope, receive, send)
return
request_id = uuid.uuid4().hex[:12]
scope.setdefault("state", {})["request_id"] = request_id
start = time.perf_counter()
async def send_with_headers(message):
if message["type"] == "http.response.start":
headers = dict(message.get("headers", []))
headers[b"x-request-id"] = request_id.encode()
# measured at http.response.start: ~total time for buffered
# responses, time-to-first-byte for streams — hence the name
headers[b"x-first-byte-ms"] = str(
int((time.perf_counter() - start) * 1000)).encode()
message["headers"] = list(headers.items())
await send(message)
await self.app(scope, receive, send_with_headers)
# wire it: app.add_middleware(RequestContextMiddleware) or wrap at ASGI levelTwo details that matter: you only touch scope["type"] == "http" (websocket and lifespan scopes pass through), and you inject headers by wrapping send at http.response.start — the response hasn't been written yet, so adding headers is still legal. Inside a handler, request.scope["state"]["request_id"] (or a contextvars.ContextVar set here — 01B.10 owns that pattern) gives you the ID for logs.
CORS (CORSMiddleware) controls which browser origins may call your API — irrelevant for curl/server-to-server, critical for browser front ends. Configure it tightly:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173"], # your front end's exact origin(s)
allow_credentials=True,
allow_methods=["GET", "POST"],
allow_headers=["Authorization", "Content-Type", "X-Request-ID"],
)allow_origins=["*"] with allow_credentials=True is invalid and dangerous — browsers refuse the combination, and "any origin + cookies/credentials" is exactly what CSRF attacks want. Wildcard origins are only safe for unauthenticated, credential-free public APIs. Part 5 returns to CORS with the full reasoning.
Static files and templates are awareness-level here: app.mount("/static", StaticFiles(directory="static"), name="static") serves a directory; Jinja2Templates renders HTML (it's in fastapi[standard]). An AI service is usually JSON-only — you mount static files when you also serve a small front end, and templating when you render server-side HTML. Both are one-liners; 11C.1 shows the JSON-only shape this path prefers.
Part 5: Security basics for a service that proxies paid APIs#
An AI service is a confused deputy waiting to happen: it holds expensive credentials and acts on whatever the client asks. The basics below are the minimum viable posture; Module 12 owns the full treatment, and 11C.1 shows the production version.
5.1 API-key auth with APIKeyHeader and constant-time comparison#
The simplest service auth is a shared secret in a header. FastAPI's security helpers make it a dependency:
# security.py — API-key auth as a dependency
import secrets
from typing import Annotated
from fastapi import HTTPException, Security, status
from fastapi.security import APIKeyHeader
# Demo key map: key -> owner. This stands in for your IdP/session store —
# production resolves the principal from a verified token instead
# (11.9 §2.3, Module 12). Demo-grade: fine for learning, never for real keys.
DEMO_API_KEYS = {
"demo-key-alice": "alice",
"demo-key-bob": "bob",
}
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
async def require_api_key(
api_key: Annotated[str | None, Security(api_key_header)],
) -> str:
"""Validate the caller's X-API-Key against the demo key map -> owner."""
if not api_key:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="missing API key",
headers={"WWW-Authenticate": "ApiKey"})
for valid_key, owner in DEMO_API_KEYS.items():
# compare_digest: constant-time — a plain == leaks the key one
# character at a time through response timing.
if secrets.compare_digest(api_key, valid_key):
return owner
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid API key",
headers={"WWW-Authenticate": "ApiKey"})Apply it three ways:
@app.get("/v1/me", dependencies=[Depends(require_api_key)]) # whole route
def me() -> dict: ...
@app.get("/v1/me2")
def me2(owner: Annotated[str, Depends(require_api_key)]) -> dict: # injected value
return {"owner": owner}
protected = APIRouter(prefix="/v1", dependencies=[Security(require_api_key)]) # whole routerSecurity(...) is Depends plus OpenAPI metadata: it marks the endpoint as requiring the X-API-Key security scheme in the docs, so Swagger UI shows a lock icon and a place to paste the key. auto_error=False on APIKeyHeader matters: with the default True, a missing header makes FastAPI raise its own error before your code runs (a 401 since FastAPI 0.122; older releases sent a 403, so check your pinned version); False lets your dependency return exactly the status and message you want. You'll see Depends(require_api_key) and Security(require_api_key) used interchangeably inside dependencies=[...] — they call the same function; prefer Security for auth so the scheme shows up in the docs (Part 8's router uses it).
Two HTTP details worth knowing: RFC 9110 requires a WWW-Authenticate header on every 401 — the examples send ApiKey (the scheme name isn't formally registered for header keys; Bearer is the alternative when the credential is a token). And a 401 means unauthenticated ("who are you?") while 403 means unauthorised ("I know who you are, and no") — the distinction matters to clients and to your logs.
5.2 Bearer tokens, OAuth2 and JWT — awareness level#
Real services rarely use a static shared key per user; they verify bearer tokens issued by an identity provider:
OAuth2PasswordBearer(tokenUrl="/token")describes theAuthorization: Bearer <token>scheme for OpenAPI/docs; your dependency extracts the token and you verify it (against your IdP's keys, or as a JWT signature+expiry).- JWTs (JSON Web Tokens) are signed claims (
sub,exp,iss, custom tenant claims). Verifying one means checking the signature against the issuer's public key and the expiry — use a maintained library (PyJWT,authlib, your IdP's SDK); never decode-and-trustjwt.decode(..., options={"verify_signature": False}). - OAuth2 scopes/roles map to your authorisation: a token for "read tickets" shouldn't delete them.
This lesson stops at "extract the bearer token and verify it before trusting anything" — 11C.1, 2.3 and Module 12 own the real implementations.
5.3 CORS, done safely#
CORS (Cross-Origin Resource Sharing) is the browser's enforcement layer: a page on https://app.example.com calling https://api.example.com is cross-origin, and the browser only lets it read the response if your server sends Access-Control-Allow-Origin headers permitting it. Your server must opt in explicitly — which is the security feature.
The rules that keep it safe:
- Name exact origins, never
"*"for credentialed APIs:allow_origins=["https://app.example.com"]."*"tells every website on the internet it may call your API with the user's credentials — combined with cookies that's a CSRF machine. allow_credentials=True+allow_origins=["*"]is rejected by browsers anyway — you must echo the specific origin (allow_origin_regexor explicit list).allow_methods/allow_headerstight:GET, POSTandAuthorization, Content-Typecover most APIs;allow_headers=["*"]lets any site send any header.- Preflight (
OPTIONS): for non-simple requests (JSON bodies, custom headers) the browser sends anOPTIONSprobe first;CORSMiddlewareanswers it. If your auth runs as a dependency it never seesOPTIONS— middleware handles it before routing, which is correct. - CORS is not auth. It stops browsers from reading responses cross-origin; curl and server-to-server clients ignore it entirely. Your API-key/JWT check is still mandatory — CORS is a browser guardrail, not a wall.
5.4 Rate limits, body size, proxy headers and docs#
The remaining posture items, each one line of reasoning:
- Rate limiting: per-user/per-key limits protect your provider budget (every
/completecall costs money). In-app token buckets are per-process (01B.4 builds one; 11C.3, Part 7 owns the shared version). For this service a dependency that counts calls per key and raises429+Retry-Afteris enough — and remember--workers Nmultiplies in-memory limits by N. - Body size limits: JSON bodies have no default cap in FastAPI —
?q=of 10 MB or a 500 MB upload is your problem. Enforcemax_lengthon Pydantic string fields, capUploadFilereads (Part 7), and set a proxy-level body limit (nginxclient_max_body_size, your platform's request-size cap) — 11C.1 covers the proxy layer. Host/proxy headers: behind a reverse proxy,request.client.hostis the proxy, not the user — trustX-Forwarded-Foronly from proxies you control, and run uvicorn with--proxy-headers --forwarded-allow-ips <proxy-ip>so it rewritesrequest.clientcorrectly. Never trustX-Forwarded-*from arbitrary clients.- HTTPS termination: TLS usually ends at the load balancer/ingress, not in Uvicorn — your app sees HTTP internally. Don't roll your own cert handling; ensure the proxy sets
X-Forwarded-Protoand HSTS. - Docs exposure:
/docs,/redoc,/openapi.jsonreveal your whole API — disable them in production (docs_url=Noneetc., Part 2.5) or gate them behind auth at the proxy. The OpenAPI schema is also mildly sensitive (field names leak your data model). - Provider keys never leave the server: your service holds
OPENAI_API_KEYetc.; the browser only ever sees your endpoints. If a response model or log line contains a key, that's a leak — 01B.2 owns secret hygiene and 03.1 §3.7 the incident response.
Part 6: Streaming responses#
6.1 StreamingResponse and async generators#
Not every answer fits in one JSON body — an LLM streams tokens, a file downloads, a log tail runs forever. FastAPI's answer is the async generator endpoint: yield pieces and the framework streams them as they arrive.
# stream_demo.py — the two ways to stream
import asyncio
from collections.abc import AsyncIterator
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
@app.get("/words")
async def words() -> AsyncIterator[dict]:
"""Yield-style endpoint: FastAPI serialises each yielded item to JSON
and streams them one per line — JSON Lines, covered properly in 6.5.
(Yielding bare strings would JSON-encode each chunk — '"hello"' on the
wire, not hello — so yield structured items or use response_class.)"""
for i, word in enumerate(["hello", "streaming", "world"]):
yield {"n": i, "word": word}
await asyncio.sleep(0.2)
@app.get("/manual")
async def manual() -> StreamingResponse:
async def body() -> AsyncIterator[bytes]:
for i in range(3):
yield f"chunk {i}\n".encode()
await asyncio.sleep(0.1)
return StreamingResponse(body(), media_type="text/plain")StreamingResponse takes an async (or sync) iterator/bytes and a media_type; it sends headers immediately then each chunk as produced — true streaming, not buffered-then-sent. Status and headers can be set on it (status_code=, headers={...}).
6.2 Server-Sent Events: the format#
SSE is the HTTP streaming format browsers understand natively (EventSource): text/event-stream body of text frames separated by blank lines, each frame carrying data:, optional event:, id:, retry: and :-comment lines. 01B.5 owns the client-side parsing of this format in depth (including a hand-rolled parser you can run); 03.3, Part 2 shows the exact bytes every provider emits. On the server side you only need to produce correct frames:
event: token
data: {"text": "Hello"}
id: 1
: ping
data: [DONE]
Rules that bite people: a blank line ends an event; multiple data: lines in one event are joined with \n; lines starting : are comments (the standard keep-alive — send one every ~15 s so proxies don't kill an idle stream); id: lets a reconnecting client resume via Last-Event-ID; data must not contain raw newlines (JSON-encode it — json.dumps escapes them for you).
6.3 Three ways to serve SSE: fastapi.sse, StreamingResponse, sse-starlette#
As of November 2026 you have three real options, and 03.3, 11.3 benchmarked all three on the wire:
fastapi.sse (FastAPI ≥ 0.135.0) |
StreamingResponse (manual) |
sse-starlette (3.x) |
|
|---|---|---|---|
| API | response_class=EventSourceResponse, yield ServerSentEvent(...) or plain objects |
You format every data:/event: byte yourself |
EventSourceResponse(async_gen) from the sse_starlette package |
data handling |
data= is JSON-encoded automatically (Pydantic models OK); raw_data= sent as-is; mutually exclusive |
Whatever you write | data must already be a string |
| Keep-alive | Automatic : ping comment every 15 s idle |
You add it | ping=15 default, configurable |
| Headers | Cache-Control: no-cache, X-Accel-Buffering: no set for you |
Only what you set | Cache-Control: no-store, Connection: keep-alive, X-Accel-Buffering: no |
| Methods | Any HTTP method (POST bodies work) | Any | Any |
| Disconnect | Generator cancelled | Starlette default | Detects disconnects, cancels generator; extra hooks (send_timeout, shutdown events) |
| Best for | New FastAPI apps — the default choice | Full control or non-FastAPI Starlette | Older FastAPI, or its extra lifecycle hooks |
# sse_demo.py — the modern, recommended form
from collections.abc import AsyncIterator
from fastapi import FastAPI
from fastapi.sse import EventSourceResponse, ServerSentEvent
app = FastAPI()
@app.get("/events", response_class=EventSourceResponse)
async def events() -> AsyncIterator[ServerSentEvent]:
yield ServerSentEvent(comment="stream opened")
for i in range(3):
yield ServerSentEvent(data={"n": i}, event="tick", id=str(i), retry=3000)
yield ServerSentEvent(raw_data="[DONE]", event="done")ServerSentEvent(data=...) JSON-encodes (pass a Pydantic model and it serialises); raw_data= sends text verbatim for sentinels like [DONE]; event=, id=, retry= (milliseconds), comment= map to the SSE fields. A plain yielded object (dict/model) becomes a data:-only event. X-Accel-Buffering: no is set for you — the header that tells nginx "don't buffer this stream" (03.3, 11.3 explains why buffering kills streams).
6.4 Disconnect handling and heartbeats#
Two production realities:
- The client can leave mid-stream. Closing the tab, navigating away, a flaky network — the generator keeps producing into a dead socket unless you check. FastAPI/Starlette cancels the generator when the connection drops (the
CancelledErrorpropagates into yourasync for/yieldloop), but the robust pattern is to also pollawait request.is_disconnected()inside the loop for long gaps between yields, and totry/finallycleanup (close the upstream provider stream — 03.3, 8.4-8.5 is emphatic that unclosed streams leak connections). 11C.3, 5.2 shows the "stop paying the provider when the client leaves" pattern. - Idle streams get killed by proxies. If your model "thinks" for 30 s before the first token, an idle SSE connection can be dropped by nginx/a load balancer. The built-in
: pingevery 15 s (or your ownServerSentEvent(comment=...)/heartbeat task) keeps bytes flowing. 03.3, Part 8 covers read timeouts and keep-alive strategy in depth.
6.5 JSON Lines and WebSockets — the alternatives#
- JSON Lines (
application/x-ndjson): one JSON object per line — simpler than SSE (no event names), ideal for "here are N results as they finish". FastAPI docs have a dedicated "Stream JSON Lines" tutorial; the mechanics are identical to SSE minus the event framing. Use it when you don't need named events or reconnect/resume. - WebSockets (
@app.websocket("/ws")): a persistent bidirectional channel — the right tool for chat UIs where the client also sends messages mid-stream, collaborative editing, or voice (09.7's realtime voice agents are WebSocket-heavy). SSE is one-way server→client over plain HTTP — simpler, survives proxies better, auto-reconnects viaEventSource. Decision: client needs to send after connecting → WebSocket; server just pushes → SSE. 09.7 owns the voice case.
6.6 The /stream endpoint with the fake backend#
This is the shape the deliverable uses — an SSE endpoint that streams the fake backend's tokens and stops when the client disconnects:
# stream_endpoint.py — POST /v1/stream: prompt in, SSE tokens out
from collections.abc import AsyncIterator
from typing import Annotated
from fastapi import APIRouter, Depends, Request
from fastapi.sse import EventSourceResponse, ServerSentEvent
from aitoolkit.backend import ScriptedBackend
from aitoolkit.models import CompletionRequest
from aitoolkit.service import get_backend # lives in service.py in the one-file deliverable
router = APIRouter()
@router.post("/stream", response_class=EventSourceResponse)
async def stream(
request: Request,
body: CompletionRequest,
backend: Annotated[ScriptedBackend, Depends(get_backend)],
) -> AsyncIterator[ServerSentEvent]:
try:
async for token in backend.stream(body.prompt):
if await request.is_disconnected(): # client left — stop producing
break
yield ServerSentEvent(data={"token": token}, event="token")
yield ServerSentEvent(raw_data="[DONE]", event="done")
finally:
# backend.stream()'s own cleanup runs here; if it wrapped a real
# provider stream you'd aclose() it in this finally too.
passrequest.is_disconnected() inside the loop is the polite check; the finally is where upstream cleanup goes. (get_backend is defined inside service.py in the Part 8 deliverable — the aitoolkit.deps module only exists if you do the optional split in exercise 15 or adopt the §4.5 layout.) On the provider side, 03.3 owns how SDK streams behave; on the service side, 07.11 and 11C.1, 2.8 show production SSE endpoints with auth, caps and logging — link forward, don't duplicate.
Part 7: Uploads, forms, testing and contracts#
Deep-dive
7.1 File uploads and form data#
File uploads use UploadFile (Starlette's spooled upload — small files in memory, large ones spooled to disk) and require python-multipart (already in fastapi[standard]; without it you get RuntimeError: Form data requires "python-multipart"):
# upload_demo.py — accept a file, stream it to disk in chunks
import uuid
from pathlib import Path
from typing import Annotated
from fastapi import FastAPI, File, HTTPException, UploadFile
app = FastAPI()
UPLOAD_DIR = Path("data/uploads")
MAX_UPLOAD_BYTES = 25 * 1024 * 1024 # 25 MB cap — your policy, enforced here
@app.post("/v1/upload")
async def upload(file: Annotated[UploadFile, File()]) -> dict:
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
# file.filename is client-controlled: keep only its last path component and
# prefix a random id, so "../../etc/passwd" can never choose where we write.
safe_name = Path(file.filename or "upload.bin").name
dest = UPLOAD_DIR / f"{uuid.uuid4().hex}-{safe_name}"
total = 0
too_big = False
with dest.open("wb") as out:
while chunk := await file.read(1024 * 1024): # 1 MiB chunks, not all at once
total += len(chunk)
if total > MAX_UPLOAD_BYTES:
too_big = True
break
out.write(chunk)
await file.close()
if too_big:
dest.unlink(missing_ok=True) # don't keep partials
raise HTTPException(413, "file too large")
return {"saved": dest.name, "bytes": total}Production rules: stream to disk in chunks (file.read(size)), never await file.read() unbounded into memory; cap the size yourself (there is no framework default — a Content-Length check plus the running total); sanitise file.filename (it is client-controlled — the example keeps only the last path component and adds a random prefix; never join it into a path as it arrives); file.content_type is a client claim, verify by content if it matters. For the ingestion pipeline this feeds, 05.1 owns what happens to uploaded documents next. Form fields (Form(...)) work the same way for application/x-www-form-urlencoded/multipart forms — HTML-form posts, not JSON.
7.2 TestClient and async tests#
FastAPI ships a test client that runs your app in-process — no server, no sockets, no network:
# test_service.py — the shape 01B.8 builds on
import pytest
from fastapi.testclient import TestClient
from aitoolkit.service import app
API_KEY = {"X-API-Key": "demo-key-alice"} # every /v1/* route needs it
@pytest.fixture(scope="module")
def client():
# `with` is REQUIRED: lifespan (which builds app.state.backend) runs
# only when TestClient is used as a context manager — a bare
# TestClient(app) never triggers startup, and /v1/* would 500.
with TestClient(app) as c:
yield c
def test_health(client):
r = client.get("/health") # unversioned, no key needed
assert r.status_code == 200
assert r.json()["status"] == "ok"
def test_echo_roundtrip(client):
r = client.post("/v1/echo", json={"message": "hi"}, headers=API_KEY)
assert r.status_code == 200
assert r.json() == {"message": "hi", "length": 2}
def test_echo_validation(client):
r = client.post("/v1/echo", json={"message": ""}, headers=API_KEY)
assert r.status_code == 422 # the service's error envelope
assert r.json()["error"]["code"] == "validation_error"
def test_v1_rejects_missing_key(client):
r = client.post("/v1/echo", json={"message": "hi"})
assert r.status_code == 401
def test_stream_is_sse(client):
with client.stream("POST", "/v1/stream", json={"prompt": "hi"},
headers=API_KEY) as r:
assert r.headers["content-type"].startswith("text/event-stream")
body = r.read().decode()
assert "event: token" in body and "event: done" in bodyTestClient is synchronous (it drives the async app for you) and built on httpx2 — Pydantic's httpx fork; plain httpx still works but is deprecated (Starlette 1.x ships the warning; fastapi[standard] installs httpx2). client.get/post/stream mirror the httpx API you know from 01B.5. For async tests — needed when your test function itself awaits — use httpx.ASGITransport directly with pytest.mark.anyio (official FastAPI pattern):
import pytest
from httpx import ASGITransport, AsyncClient
from aitoolkit.service import app
@pytest.mark.anyio
async def test_health_async():
async with AsyncClient(transport=ASGITransport(app=app),
base_url="http://test") as ac:
r = await ac.get("/health")
assert r.status_code == 200Two lifespan facts that decide whether your tests pass: TestClient runs lifespan only as a context manager (with TestClient(app) as client:) — instantiated bare, startup never runs and app.state.backend doesn't exist, so /v1/complete and /v1/stream 500. And httpx.ASGITransport never runs lifespan at all — fine for /health and for tests that inject app.dependency_overrides[get_backend], wrong for anything that needs the real lifespan-built objects. Dependency overrides swap collaborators: app.dependency_overrides[get_backend] = lambda: FakeBackend() — 01B.8 owns the full pytest treatment; the rule to remember now is tests hit your app in-process, never the network.
7.3 OpenAPI as a contract, versioning and health#
Three operational patterns:
- OpenAPI as contract:
/openapi.jsonis a stable machine-readable description of every route, parameter and model. Front-end codegen (openapi-typescript,datamodel-code-generator), API gateways, contract tests and SDK generators all consume it — treat it as your API's source of truth and keep it backward-compatible within a version. - Versioning: prefix route groups —
/v1/echo,/v1/complete— so breaking changes ship as/v2while/v1keeps working.APIRouter(prefix="/v1")(4.5) makes this one line; deprecate old versions withdeprecated=Trueon operations and a sunset header. Never break/v1silently — clients pin versions. - Health/readiness:
/health(or/healthz) returns200 {"status": "ok"}when the process is alive — load balancers and orchestrators poll it. Keep it cheap and dependency-free (don't check the DB/provider in liveness or a slow provider becomes a flapping restart loop); a deeper/readycan check dependencies if your platform distinguishes readiness from liveness (11C.3, 8.1 names the three kinds).
7.4 Deployment shape — preview#
You don't deploy FastAPI itself; you deploy Uvicorn serving your app, usually behind a proxy:
- Dev:
fastapi dev/uvicorn --reload— one process, reload on change. - Single host:
uvicorn main:app --workers Norfastapi run --workers N— N processes for N cores (each runs lifespan independently). - Gunicorn + Uvicorn workers:
gunicorn -k uvicorn.workers.UvicornWorker -w N main:app— Gunicorn manages process lifecycle, UvicornWorker serves ASGI; common on classic VPS setups. - Containers: one Uvicorn process per container, orchestrator replicates — the modern default (11C.1, 2.13 owns the whole deployment lesson: Dockerfile, workers-vs-replicas, graceful shutdown, SSE through nginx).
The rule of thumb for LLM services: I/O-bound → async single process per core is plenty; scale by replicas, not threads.
Part 8: The aitoolkit deliverable — service.py#
Here is the complete service, one file, using everything from Parts 2–7: lifespan-built backend, settings + auth dependencies, request-ID middleware, the JSON error envelope, /health unversioned and the API under /v1. It builds on the toolkit pieces from earlier lessons exactly as they are written: aitoolkit.settings.get_settings()/Settings.app_env (01B.2), aitoolkit.backend.ScriptedBackend whose complete() returns a Completion dataclass and stream() an async generator of text chunks (01B.3), and aitoolkit.models.Completion/CompletionRequest/Usage Pydantic models (01B.6). One contract note: 01B.2's Settings has no API-key field, so the demo key map lives in this file — production auth is 11C.1 §2.3 and Module 12.
# src/aitoolkit/service.py — the FastAPI service: /health, /v1/echo, /v1/complete, /v1/stream
#
# Run: uv run fastapi dev src/aitoolkit/service.py (dev, auto-reload)
# uv run uvicorn aitoolkit.service:app (or: fastapi run)
# Try: curl http://127.0.0.1:8000/health
# curl -X POST http://127.0.0.1:8000/v1/echo -H 'content-type: application/json' \
# -d '{"message": "hello"}'
# curl -N -X POST http://127.0.0.1:8000/v1/stream -H 'content-type: application/json' \
# -d '{"prompt": "hi"}' # -N = no buffering, watch SSE arrive
#
# Demo auth: X-API-Key must match a key in DEMO_API_KEYS below
# (the stand-in for your IdP — 11.9 §2.3 and Module 12 own real auth).
from __future__ import annotations
import logging
import secrets
import time
import uuid
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager
from typing import Annotated
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request, Security, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.security import APIKeyHeader
from fastapi.sse import EventSourceResponse, ServerSentEvent
from pydantic import BaseModel, Field
from aitoolkit.backend import ScriptedBackend # 01B.3: async complete()/stream()
from aitoolkit.models import Completion, CompletionRequest, Usage # 01B.6
from aitoolkit.settings import Settings, get_settings # 01B.2
logger = logging.getLogger(__name__) # structured logging lands in 01B.10
# ---------------------------------------------------------------------------
# Request/response models (the service-local ones; Completion* come from models.py)
# ---------------------------------------------------------------------------
class EchoIn(BaseModel):
message: str = Field(min_length=1, max_length=4000)
class EchoOut(BaseModel):
message: str
length: int
class HealthOut(BaseModel):
status: str
service: str
env: str
# ---------------------------------------------------------------------------
# Dependencies
# ---------------------------------------------------------------------------
# Demo key map: key -> owner. Stands in for your IdP/session store —
# production resolves the principal from a verified token (11.9, Module 12).
DEMO_API_KEYS = {
"demo-key-alice": "alice",
"demo-key-bob": "bob",
}
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
async def require_api_key(
api_key: Annotated[str | None, Security(api_key_header)],
) -> str:
"""X-API-Key auth against DEMO_API_KEYS (key -> owner).
compare_digest: constant-time — `==` on secrets is a timing oracle.
"""
if not api_key:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing API key",
headers={"WWW-Authenticate": "ApiKey"})
for valid_key, owner in DEMO_API_KEYS.items():
if secrets.compare_digest(api_key, valid_key):
return owner
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid API key",
headers={"WWW-Authenticate": "ApiKey"})
def get_backend(request: Request) -> ScriptedBackend:
"""The shared backend lifespan built — one per worker process."""
return request.app.state.backend
# ---------------------------------------------------------------------------
# Error envelope: one JSON shape for every failure
# ---------------------------------------------------------------------------
def error_body(code: str, message: str) -> dict:
return {"error": {"code": code, "message": message}}
def register_error_handlers(app: FastAPI) -> None:
@app.exception_handler(RequestValidationError)
async def validation_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
# jsonable_encoder: error dicts can hold non-JSON values — encode first
return JSONResponse(status_code=422, content={
"error": {"code": "validation_error", "message": "request failed validation",
"details": jsonable_encoder(exc.errors())}})
@app.exception_handler(Exception)
async def unhandled_handler(request: Request, exc: Exception) -> JSONResponse:
# Log exc + request id server-side; never leak internals to clients.
logger.exception("unhandled error on %s %s", request.method, request.url.path)
return JSONResponse(status_code=500,
content=error_body("internal_error", "something went wrong"))
# ---------------------------------------------------------------------------
# Middleware: pure ASGI — request id + duration on every response.
# No buffering (safe for SSE), passes non-http scopes through untouched.
# ---------------------------------------------------------------------------
class RequestContextMiddleware:
def __init__(self, app: Callable) -> None:
self.app = app
async def __call__(self, scope, receive, send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
request_id = uuid.uuid4().hex[:12]
scope.setdefault("state", {})["request_id"] = request_id
start = time.perf_counter()
async def send_with_headers(message):
if message["type"] == "http.response.start":
headers = dict(message.get("headers", []))
headers[b"x-request-id"] = request_id.encode()
# at http.response.start: ~total for buffered responses,
# time-to-first-byte for streams — hence the name
headers[b"x-first-byte-ms"] = str(
int((time.perf_counter() - start) * 1000)).encode()
message["headers"] = list(headers.items())
await send(message)
await self.app(scope, receive, send_with_headers)
# ---------------------------------------------------------------------------
# Lifespan: build the backend once per process, close it on shutdown
# ---------------------------------------------------------------------------
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
app.state.backend = ScriptedBackend() # real service: httpx.AsyncClient(), DB pool…
yield
# ScriptedBackend owns nothing closable; a real client/pool gets
# `await client.aclose()` / `await engine.dispose()` here (see 4.2).
# ---------------------------------------------------------------------------
# The app
# ---------------------------------------------------------------------------
settings = get_settings() # lru_cached; read once at import
app = FastAPI(
title="aitoolkit",
version="0.1.0",
lifespan=lifespan,
# docs off in prod; note `fastapi dev` sets FASTAPI_ENV=development while
# our Settings reads APP_ENV — two different switches, both worth knowing
docs_url=None if settings.app_env == "prod" else "/docs",
redoc_url=None if settings.app_env == "prod" else "/redoc",
)
app.add_middleware(RequestContextMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins, # from 01B.2 Settings (CORS_ORIGINS env);
allow_methods=["GET", "POST"], # never "*" together with credentials
allow_headers=["Authorization", "Content-Type", "X-API-Key", "X-Request-ID"],
)
register_error_handlers(app)
# -- unversioned ops endpoint -------------------------------------------------
@app.get("/health", response_model=HealthOut)
def health(settings: Annotated[Settings, Depends(get_settings)]) -> HealthOut:
"""Liveness for load balancers — cheap, no dependency checks."""
return HealthOut(status="ok", service="aitoolkit", env=settings.app_env)
# -- versioned API ------------------------------------------------------------
# include_router() snapshots the router's routes eagerly — it must come
# AFTER the @v1.* decorators below, or /v1/* never mounts (404s).
v1 = APIRouter(prefix="/v1", dependencies=[Security(require_api_key)])
@v1.post("/echo", response_model=EchoOut)
def echo(body: EchoIn) -> EchoOut:
return EchoOut(message=body.message, length=len(body.message))
@v1.post("/complete", response_model=Completion)
async def complete(
body: CompletionRequest,
backend: Annotated[ScriptedBackend, Depends(get_backend)],
) -> Completion:
# backend.complete() returns the backend's Completion *dataclass* (01B.3);
# map it into the pydantic Completion *model* (01B.6): text/model/usage,
# finish_reason defaults to "stop". max_tokens/temperature are accepted
# for contract realism — the fake backend ignores them.
result = await backend.complete(body.prompt, model=body.model)
return Completion(
text=result.text,
model=result.model,
usage=Usage(input_tokens=result.usage.input_tokens,
output_tokens=result.usage.output_tokens),
)
@v1.post("/stream", response_class=EventSourceResponse)
async def stream(
request: Request,
body: CompletionRequest,
backend: Annotated[ScriptedBackend, Depends(get_backend)],
) -> AsyncIterator[ServerSentEvent]:
"""SSE: one `token` event per chunk, then `done`. Stops if the client leaves."""
try:
async for token in backend.stream(body.prompt):
if await request.is_disconnected():
break
yield ServerSentEvent(data={"token": token}, event="token")
yield ServerSentEvent(raw_data="[DONE]", event="done")
finally:
pass # upstream cleanup goes here (see 6.6)
app.include_router(v1) # AFTER the routes — see the note above8.1 Trying it#
uv run fastapi dev src/aitoolkit/service.py╭────────── FastAPI CLI - Development mode ───────────╮
│ Server started at http://127.0.0.1:8000 │
│ Documentation at http://127.0.0.1:8000/docs │
╰─────────────────────────────────────────────────────╯In a second terminal, try the endpoints. The # → lines show what you should see (illustrative: exact JSON spacing, and the SSE tokens when you give the backend canned replies, may differ):
curl -s http://127.0.0.1:8000/health
# → {"status":"ok","service":"aitoolkit","env":"dev"}
curl -s -X POST http://127.0.0.1:8000/v1/echo \
-H 'content-type: application/json' -H 'X-API-Key: demo-key-alice' \
-d '{"message": "hello there"}'
# → {"message":"hello there","length":11}
curl -s -X POST http://127.0.0.1:8000/v1/echo \
-H 'content-type: application/json' -H 'X-API-Key: demo-key-alice' \
-d '{"message": ""}'
# → 422 {"error":{"code":"validation_error","message":"request failed validation","details":[…]}}
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/v1/echo \
-X POST -H 'content-type: application/json' -d '{"message":"x"}'
# → 401 (no X-API-Key)
curl -N -X POST http://127.0.0.1:8000/v1/stream \
-H 'content-type: application/json' -H 'X-API-Key: demo-key-alice' \
-d '{"prompt": "say hi"}'
# event: token
# data: {"token": "(no "} <- ScriptedBackend() has no canned replies, so the
# event: token stream is its default reply, one word per event
# data: {"token": "scripted "}
# …
# event: done
# data: [DONE]Every response that passes through your middleware carries x-request-id and x-first-byte-ms — check with curl -si (a crash that escapes to Starlette's outermost error handler bypasses them — see the failure gallery). The interactive docs at /docs show the lock icon on /v1/* routes and let you paste X-API-Key via "Authorize".
Failure gallery#
The failures this lesson exists to prevent, as symptom → cause → fix. The first three are shown below as the tracebacks or symptoms look in practice (file names and line numbers are examples):
| Symptom | Cause | Fix |
|---|---|---|
| Every request on the worker stalls for seconds; one slow call freezes all others | async def endpoint calling blocking code (time.sleep, sync requests, sync DB driver) — the whole event loop stops |
Write it def (thread pool), or await asyncio.sleep/anyio.to_thread.run_sync inside async def (4.1) |
AttributeError: 'State' object has no attribute 'backend' → 500 on /v1/* |
Lifespan never ran — bare TestClient(app) in tests, or startup skipped |
Use with TestClient(app) as client:; ASGITransport never runs lifespan at all (7.2) |
Internal fields (internal_note, owner_email, cost_usd) visible in API responses |
No response_model, or the "secret" field declared on the output model — declared fields are serialised, not filtered |
Separate in/out models; extras are stripped only when undeclared (3.1) |
| Browser console: "No 'Access-Control-Allow-Origin' header" despite working curl | CORS only restricts browsers; or allow_origins=["*"] + allow_credentials=True (rejected combo) |
Exact origins, credentials only with explicit origin list (5.3) |
| Stream keeps billing the provider after the user closes the tab | Generator never checks disconnect; upstream provider stream left open | await request.is_disconnected() in the loop + try/finally cleanup (6.4) |
RuntimeError: Form data requires "python-multipart" to be installed. on upload |
Bare fastapi install — multipart parsing is an optional extra |
fastapi[standard] or uv add python-multipart (7.1) |
| API keys accepted but auth feels "slow to reject" — or timing differences between right/wrong prefixes | == string comparison short-circuits at the first differing byte — a timing oracle |
secrets.compare_digest always (5.1) |
New AsyncClient/connection pool per request — slow, PoolTimeout-ish churn |
Client built inside the handler instead of lifespan | Build once in lifespan, store on app.state, inject via Depends (4.2) |
Three of them as the errors actually surface:
Missing lifespan under TestClient — app.state.backend was never built:
Traceback (most recent call last):
...
File ".../aitoolkit/service.py", line ..., in get_backend
return request.app.state.backend
^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'State' object has no attribute 'backend'(Surfaced to the client as a 500 through your Exception handler — or raised in the test when raise_server_exceptions=True.)
Upload without python-multipart:
RuntimeError: Form data requires "python-multipart" to be installed.
You can install it with: pip install python-multipartThe loop freeze has no traceback — that's what makes it dangerous. The symptom is timing, not an exception: fire 20 concurrent requests at an endpoint that does time.sleep(5) inside async def and the last response arrives ~100 s later instead of ~5 s, because every request queued behind the frozen loop. def + time.sleep(5) finishes all 20 in ~5 s of wall time across the thread pool — same blocking code, completely different behaviour (exercise 5 has you measure it).
Common misconceptions#
| Misconception | Reality |
|---|---|
| "FastAPI is a web framework like Flask — pick whichever." | FastAPI is async-native with Pydantic validation and generated OpenAPI; Flask/Django are WSGI-first ecosystems. For JSON APIs and LLM services, FastAPI is the default — but the choice is about ecosystem fit, not fashion (1.2). |
| "Type hints in FastAPI are just hints." | They are the validation contract: item_id: int coerces and rejects, Body models validate JSON, and the OpenAPI schema is generated from them. Wrong types get 422 before your code runs. |
"async def is always faster." |
Only if you await real async I/O. async def + a blocking call (time.sleep, sync requests) freezes the whole event loop — worse than def, which at least gets a thread. Match endpoint style to your dependencies (4.1). |
"Create the AsyncClient/DB pool per request." |
That leaks connections and pays setup per call. Build once in lifespan, store on app.state, inject via Depends — once per worker process (4.2). |
"response_model validates my return value." |
It filters and validates what you return — extra fields are stripped, wrong shapes raise ResponseValidationError (a 500). It's your output contract, not just documentation (3.1). |
| "Return the ORM object/dict and let the client sort it out." | Without response_model you leak every field — internal notes, costs, PII. Always declare the output shape (3.1). |
"BackgroundTasks is a queue." |
It runs after the response in the same process — no durability, no retry, no visibility. Real work that must survive restarts needs a real queue (4.6). |
"CORS allow_origins=['*'] is fine for an API." |
Only for credential-free public APIs. * + credentials is rejected by browsers and is a CSRF invitation; name exact origins (5.3). |
| "CORS protects my API." | CORS is a browser guardrail — curl and server-to-server clients ignore it. Auth is your Depends check, always (5.3). |
"== on API keys is fine for a demo." |
It's a timing oracle — response times leak the key byte by byte. secrets.compare_digest always, even in demos you might ship (5.1). |
| "SSE needs a library / is hard." | FastAPI ≥ 0.135 has fastapi.sse: response_class=EventSourceResponse + yield — keep-alive, headers and JSON encoding built in. sse-starlette remains for older versions or its extra hooks (6.3). |
| "The stream keeps running after the client disconnects." | Starlette cancels the generator on disconnect, and you should also check request.is_disconnected() and finally-cleanup the upstream — unclosed provider streams leak connections and keep billing (6.4). |
"/docs is harmless." |
It publishes your entire API surface — every route, param and model. Disable or protect it in production (2.5, 5.4). |
"TestClient hits a real server." |
It runs your ASGI app in-process — no sockets, no network, deterministic. Async tests use httpx.ASGITransport + pytest.mark.anyio (7.2). |
Key takeaways#
- A FastAPI service is the wall between users and your secrets/paid APIs: it authenticates, validates, applies product rules, calls providers efficiently and streams results back.
- FastAPI = Starlette (HTTP toolkit) + Pydantic (data contracts) + decorators/DI/OpenAPI. Uvicorn is the ASGI server that runs it;
async defendpoints share one event loop per worker,defendpoints get a thread pool. - The signature is the contract: path/query/header/cookie/body kinds are decided by annotation and
Annotated[...]metadata; failures are automatic422s with structured detail. response_modelfilters output — declare separate in/out models and never return raw ORM/dict internals.- Errors:
HTTPExceptionfor expected failures,@app.exception_handlerfor a consistent JSON envelope, and never leakstr(exc)to clients. - Build shared clients once in
lifespan, store onapp.state, inject withDepends;yielddependencies clean up after the response;app.dependency_overridesis the test seam. - Security floor: API-key/bearer auth with
secrets.compare_digest, tight CORS origins, rate limits, body caps, proxy-aware headers, docs disabled in prod, provider keys never in responses. - Streaming:
StreamingResponsefor raw streams,fastapi.sse'sEventSourceResponse/ServerSentEventfor SSE (automatic: ping,X-Accel-Buffering: no), disconnect checks + upstream cleanup, JSON Lines for simple streams, WebSockets when the client must send mid-stream. - Uploads stream to disk in chunks with your own size cap; tests use
TestClient/ASGITransportin-process;/openapi.jsonis your contract; version under/v1;/healthstays cheap. - The deliverable
aitoolkit/service.pywires it all:/health,/v1/echo,/v1/complete,/v1/stream— the same skeleton 11C.1 scales to production.
Where you'll use this in the AI path#
This lesson owns the FastAPI mechanics; these later sections apply them to real LLM systems — link forward rather than re-learning them here:
- 03.3, Part 11: Streaming to a browser — the full provider→FastAPI→browser SSE path, your own event protocol, and the three SSE server implementations compared on the wire (11.3, 11.4).
- 07.11, 1.4: The FastAPI service, complete — a production RAG service: auth dependencies, request IDs, concurrency caps, SSE framing and PII-safe logging, all built on the patterns here.
- 08E.1, 3.5: Running and packaging — MCP servers are FastAPI/HTTP services; 2.6 Transports and 5.2 The MCP authorization model cover the protocol and auth specifics.
- 09.7, 9.1: The token-minting endpoint — a FastAPI endpoint that mints ephemeral voice-session credentials, and the WebSocket servers of Parts 8–9.
- 11C.1, Part 2: The production FastAPI service — the complete
llm_service: settings, injected client, auth, error mapping, SSE route, structured logging, tests, containers (2.13, 2.15, 2.16). - Supporting casts: 11A.1, 3.6: Context propagation (request IDs through async code), 11C.3, 5.2: Cancellation and 8.1: health checks, 12.10, 4.2: Secure coding for LLM glue code.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| API service / backend-for-frontend | The server-side program that holds secrets, authenticates callers, applies product rules and proxies expensive work (LLM calls) for clients |
| ASGI | Asynchronous Server Gateway Interface — the async request/response protocol between an ASGI server and Python apps; supports streaming and WebSockets |
| WSGI | The older synchronous Python web standard (Flask/Django); one request occupies one worker for its duration |
| Uvicorn | The ASGI server that listens on a port and runs your FastAPI/Starlette app; uvicorn[standard] adds C extensions |
| Starlette | The lightweight ASGI toolkit under FastAPI: routing, requests/responses, middleware, static files, TestClient |
| Path operation | A function decorated with @app.get/post/… that handles one HTTP method on one path |
| Path / query / header / cookie / body parameter | The five places request input can arrive; FastAPI assigns each from the signature and Annotated metadata |
Annotated style |
Declaring FastAPI metadata (Query, Header, Depends…) inside Annotated[T, ...] — the current recommended form |
422 Unprocessable Content |
The automatic validation-failure status, with a structured detail list of Pydantic-style errors |
response_model |
The Pydantic model FastAPI validates and filters handler output through — your output contract |
HTTPException |
FastAPI's exception for expected HTTP failures (status_code, detail) |
| Exception handler | @app.exception_handler(...) — maps exception types to custom responses (your error envelope) |
| Lifespan | The asynccontextmanager startup/shutdown hook for building and closing per-process resources |
app.state |
Starlette's per-app attribute bag for objects built once (clients, pools, flags) |
Dependency / Depends |
A function FastAPI calls per request to supply a collaborator (settings, client, auth); cached per request, supports yield cleanup and dependency_overrides |
APIRouter |
A route group with shared prefix/tags/dependencies, mounted via app.include_router |
BackgroundTasks |
Post-response in-process tasks — convenience for audit/cache work, not a durable queue |
| Middleware | Onion-layer wrappers around every request/response; pure-ASGI classes avoid buffering and stream safely |
CORSMiddleware |
Browser cross-origin guard; configure exact origins, never * with credentials |
APIKeyHeader / Security |
FastAPI security helpers that extract an API key header and mark the OpenAPI security scheme |
secrets.compare_digest |
Constant-time string comparison — required for secret checks (timing-oracle defence) |
StreamingResponse |
Response class that sends an iterator's chunks as they're produced |
SSE / EventSourceResponse / ServerSentEvent |
Server-Sent Events: text/event-stream push format; FastAPI ≥0.135's built-in response class and event type |
X-Accel-Buffering |
Response header that tells proxies (nginx) not to buffer a stream |
UploadFile |
Starlette's spooled file-upload type; stream to disk in chunks with your own size cap |
TestClient / ASGITransport |
In-process test clients: sync TestClient for def tests, httpx.ASGITransport + pytest.mark.anyio for async tests |
All terms are also collected in the glossary.
Exercises#
- First app. Create
main.pywithGET /returning{"hello": "world"}andGET /items/{item_id}echoingitem_id: intplus optionalq: str | None. Runuv run fastapi dev, thencurl 'localhost:8000/items/7?q=x'(quote the URL: zsh treats an unquoted?as a wildcard) andcurl localhost:8000/items/abc. What status does the second return and why? - Parameter kinds. Extend the app with an endpoint taking a path int, a query
limitbounded1..100, a required headerX-Traceand a JSON body model with aname: str(min 2 chars) andscore: float(0..1). Send one valid and three invalid requests; paste the422detailentries. - Response filtering. Give your endpoint a handler that returns a dict with an extra
internal_debugkey and setresponse_modelto a model without it. Show that the key never reaches the client, then removeresponse_modeland show it does. - Error envelope. Add the
ApiErrorexception + handlers from 3.2 and a route that raises it; verify aPOSTwith a bad body returns your{"error": ...}shape for both422and your domain error. - async vs def. Write two endpoints:
async defthat doesawait asyncio.sleep(1), anddefthat doestime.sleep(1). Fire 20 concurrent requests at each (a loop ofcurl &orhttpx.AsyncClientgather) and compare wall time. Which scales and why? - Lifespan + state. Add a
lifespanthat stores a counter onapp.stateand increments it in a dependency; hit the endpoint twice and show the count reaches 2 (proving one shared object per process). - Dependency override. Write a
TestClienttest that overridesget_backendwith a fake returning"FAKE"and asserts/v1/completereturns it — without touching route code. - Auth. Implement
require_api_keyfrom 5.1 against a dict of two demo keys. Show 401 for missing, 401 for wrong, 200 for right — and explain whysecrets.compare_digestis used. - SSE by hand. Using only stdlib, write
frame_event(data: str, event: str = "message", id: str | None = None) -> strthat returns a correct SSE frame (fields + blank line), JSON-encodingdata. Run it on three events and verify the output parses the way a browser'sEventSourcewould read it. - fastapi.sse. Convert a
StreamingResponseSSE endpoint toresponse_class=EventSourceResponseyieldingServerSentEvents; note what the framework now does for you (JSON encoding, ping, headers). - Disconnect. In your
/streamendpoint addawait request.is_disconnected()in the loop and afinallythat prints "cleanup". Disconnect mid-stream withcurland observe. - Upload. Add
/v1/uploadfrom 7.1 with a 1 KB cap; upload a small file and a too-big one; show the413. - Middleware. Add the
RequestContextMiddlewarefrom Part 8 and confirm every response carriesx-request-idandx-first-byte-ms. - Deploy shape. Write the two commands to run the service in dev and with 4 workers; explain what changes about
app.statecontents between them. - Stretch. Split
service.pyintomodels.py,deps.py,api_v1.py,service.pyusingAPIRouter(prefix="/v1"), keeping all tests green.
Solutions
{"item_id": 7, "q": "x"}and422—item_id: intfails to parse"abc"before the handler runs; thedetail[0].locis["path","item_id"].- Sample valid call:
POST /items/3?limit=10+ headerX-Trace: t1+ body{"name":"ab","score":0.5}→ 200. Invalids:limit=0→ 422 (greater_than_equal); missingX-Trace→ 422 (missing);score: 1.5→ 422 (less_than_equal). Eachdetailentry has fields such astype,loc(["query","limit"],["header","x-trace"],["body","score"]),msg,input— andurlin current Pydantic. - With
response_model=TicketOut,internal_debugis stripped; without it the raw dict serialises including the key. This is the leakresponse_modelprevents. - See 3.2: 422s become
{"error":{"code":"validation_error",...}}, yourApiError(409,"conflict","duplicate")becomes{"error":{"code":"conflict","message":"duplicate"}}. async def+await asyncio.sleepinterleaves: ~1 s for 20 requests.def+time.sleepdoes not block the loop —defruns in the threadpool, so it's ~parallel but bounded by thread count (~40);async def+time.sleepwould take ~20 s (the trap).- Dependency increments
app.state.counter; two requests → 2, proving the lifespan-built object is shared per process (and per worker — 4 workers = 4 counters). app.dependency_overrides[get_backend] = lambda: FakeBackend()(the service reads.text,.modeland.usage.input_tokens/.output_tokensfrom whatcomplete()returns, so build the fake fromScriptedBackend(replies={"x": "FAKE"})and send the prompt"x", or return an object with those attributes) thenclient.post("/v1/complete", json={"prompt":"x"}, headers=API_KEY)→resp.json()["text"] == "FAKE"(the response is the 01B.6Completionshape:text/model/usage/finish_reason).- See 5.1: missing → 401 "missing API key"; wrong → 401 "invalid API key"; right → 200 + owner.
compare_digestprevents timing attacks on the comparison. - Runnable stdlib solution:
import json
def frame_event(data: str, event: str = "message", id: str | None = None) -> str:
lines = []
if event:
lines.append(f"event: {event}")
if id is not None:
lines.append(f"id: {id}")
# JSON-encoding escapes newlines so `data` stays one line
lines.append(f"data: {json.dumps(data)}")
return "\n".join(lines) + "\n\n"
print(frame_event("hello", event="token", id="1"), end="")
print(frame_event("two\nlines"), end="")
print(frame_event("[DONE]", event="done"), end="")event: token
id: 1
data: "hello"
event: message
data: "two\nlines"
event: done
data: "[DONE]"
response_class=EventSourceResponse+yield ServerSentEvent(data=..., event=..., id=...)replaces manual framing; you get JSON encoding,: pingkeep-alive andX-Accel-Buffering: nofree.curl -N ... & sleep 1; kill %1— the generator'sis_disconnected()sees the drop,breaks, andfinallyprints "cleanup" in the server log.- 1 KB file → 200
{"saved": ..., "bytes": 1024}; 2 KB file → 413 after the running total crosses the cap; partial file removed. curl -si localhost:8000/healthshowsx-request-id: <12hex>andx-first-byte-ms: <int>on every response that reaches your middleware.- Dev:
uv run fastapi dev(1 process, reload). Workers:uv run fastapi run --workers 4— lifespan runs 4×, soapp.state.backendexists once per worker, not once per server; in-memory state is not shared. - Move models to
models.py, deps todeps.py, routes toapi_v1.pywithAPIRouter(prefix="/v1", dependencies=[Security(require_api_key)]),app.include_router(v1)inservice.py; all tests still pass because the import surface is unchanged.
Check yourself#
- What are ASGI and WSGI, and why does WSGI struggle with LLM streaming?ASGI is the async request protocol (scope/receive/send) supporting streaming and WebSockets; WSGI is the older synchronous callables standard — one request occupies one worker for its whole duration, so long waits waste workers and can't stream.
- Name the five places request input can arrive and how FastAPI decides which applies.Path, query, header, cookie, body (+ dependencies). Path names match
{...}; Pydantic models/Body()→ body;Header()/Cookie()/Path()/Form()/File()explicit; simple types → query. - What status code does a failed path-param parse produce, and what does the body look like?
422 Unprocessable Contentwith{"detail": [{"type","loc","msg","input"}]}— before the handler runs. - Why declare separate request and response Pydantic models?Input and output contracts differ: clients shouldn't send computed fields, and the output model filters fields clients must never see (internal notes, costs, PII).
- What does
response_modelactually do to a handler's return value?It validates the return value and filters it to the declared fields — extra keys are stripped; wrong shapes raiseResponseValidationError(500). async defvsdefendpoint — which runs where, and what is the dangerous combination?async defruns on the event loop (one per worker);defruns in a thread pool. Dangerous:async defcalling blocking code (time.sleep, sync HTTP) — freezes the whole loop.- Where should a shared
httpx.AsyncClientbe created, and how do endpoints reach it?Once inlifespan(startup), stored onapp.state, reached viarequest.app.stateinside aDependsfunction — once per worker process. - What is a
yielddependency, and when does its cleanup code run?A dependency thatyields a resource; cleanup afteryieldruns after the response is sent — for closing sessions/locks. - Why is
secrets.compare_digestrequired for API-key checks?==short-circuits at the first differing byte, leaking the secret via response timing;compare_digestruns in constant time. allow_origins=["*"]+allow_credentials=True— what's wrong?Browsers reject the combination; "any origin + credentials" is a CSRF hole. Use explicit origins;*only for credential-free public APIs.- Name the three ways to serve SSE from Python/FastAPI and which is the current default.
fastapi.sseEventSourceResponse(built-in, ≥0.135 — the default), manualStreamingResponseframing, andsse-starlette3.x (older FastAPI or extra hooks). - What does
X-Accel-Buffering: noprevent, and who sets it for you?It stops nginx/proxies buffering the stream (users would see nothing until the end);fastapi.sseandsse-starletteset it automatically. - Why stream uploads to disk in chunks instead of
await file.read()?Unboundedfile.read()loads the whole upload into memory — a memory-exhaustion vector. Chunked reads + a running-total cap bound memory and let you reject oversized files. - How do
TestClientandhttpx.ASGITransportdiffer, and when do you need the latter?TestClientis sync and drives the async app fordeftests;ASGITransport+AsyncClientis needed when the test function itself isasync(markedpytest.mark.anyio). - Why is
/healthkept dependency-free, and what are the three kinds of health check?A dependency check (DB, provider) can fail or be slow, causing flapping restarts; liveness should prove only "the process runs". The three kinds: liveness, readiness, and model canary (11C.3, 8.1).
Further resources#
- FastAPI official docs (fastapi.tiangolo.com): the tutorial (parameters, body, dependencies, security, middleware, CORS, background tasks, static files, testing, SSE, lifespan) and the API reference — the authoritative source for every signature used here.
- Starlette docs (starlette.dev): the toolkit underneath — requests/responses, middleware, lifespan, TestClient, release notes (1.x as of November 2026).
- Uvicorn docs (uvicorn.dev): the ASGI server — deployment, workers,
--proxy-headers, graceful shutdown. - ASGI spec (asgi.readthedocs.io): the protocol itself, when you need to go below the framework.
- MDN: Server-Sent Events (developer.mozilla.org/en-US/docs/Web/API/Server-sent_events): the wire format and the browser
EventSourceAPI. - sse-starlette (github.com/sysid/sse-starlette): the Starlette-level SSE package and its extra hooks.
- RFC 9457 / RFC 9110: problem-details and the HTTP semantics behind status codes like
422 Unprocessable Content. - OWASP API Security Top 10 (owasp.org/www-project-api-security): the broader service-security checklist beyond this lesson's basics.
← 01B.6 — Data Validation with Pydantic | Module 01B overview | 01B.8 — Testing with pytest →