Exceptions & Responses: HTTPException, Custom Handlers, Problem Details, Response Models, StreamingResponse & SSE, Static Files
"Errors are any other exception that occurs within the application. These cases should bubble through the entire middleware stack as exceptions. Any error logging middleware should ensure that it re-raises the exception all the way up to the server." — Starlette documentation, "Exceptions", starlette.dev/exceptions
Summary: Every FastAPI response is produced in one of two ways: your path operation returns a value (or a Response object), or something raises. Raised exceptions are caught by a two-layer machine inherited from Starlette: ExceptionMiddleware runs the handlers for "handled" exceptions (HTTPException, RequestValidationError, your own domain classes) and turns them into ordinary responses, while ServerErrorMiddleware, the outermost layer, runs the handler registered for Exception (or 500), sends the 500 and then re-raises so the server logs it. On the success side, the return value is filtered by response_model (or the return type annotation) and serialised, or you pick a response class (JSONResponse, HTMLResponse, PlainTextResponse, RedirectResponse, FileResponse, StreamingResponse) and own the bytes. Streaming responses are generators: the body is sent with chunked transfer encoding, back-pressure pauses your generator at await send, a client disconnect cancels it, and Server-Sent Events are just a text framing (event:, id:, retry:, data:, blank line) on top of a stream. Focus: HTTPException (status_code, detail, headers on exceptions), FastAPI's vs starlette.exceptions.HTTPException, custom exception class, @app.exception_handler and add_exception_handler, the handler for Exception, ServerErrorMiddleware and why it re-raises, 500 Internal Server Error, debug mode, RequestValidationError override, Problem Details (RFC 9457, application/problem+json) as the house format, domain error mapping (OrderNotFound → 404 Not Found, OutOfStock → 409 Conflict), logging exceptions with request ids, the responses parameter and the error response model, response_model vs return type annotation, response_model_exclude_unset/response_model_exclude_none, response_class and every response class including ORJSONResponse and orjson, response headers and Set-Cookie on Response, 201 Created with a Location header, 204 No Content, 304 Not Modified and an ETag preview, FileResponse and uploads preview, StreamingResponse with a generator or async generator, chunked transfer encoding, back-pressure, client disconnect and request.is_disconnected, Server-Sent Events (text/event-stream, event id retry, Last-Event-ID), sse-starlette's EventSourceResponse and FastAPI 0.135's fastapi.sse, proxy buffering, X-Accel-Buffering, keep-alive comments, LLM token streaming, StaticFiles mounts with html=True, Cache-Control for static files and when a CDN or Nginx should serve them, and a BackgroundTasks preview. Learning goal: Build a FastAPI service in which every failure has exactly one place that decides its status code and body, no internal detail ever reaches a client, every 500 can be found in the logs by its request id, every response class is chosen on purpose, and every stream survives slow clients, disconnects and proxies.
This page owns the response side of FastAPI: how exceptions become responses and how non-JSON or long-lived responses are built. It does not re-teach its neighbours. The 422 body, the RFC 9457 validation format with JSON Pointers and the first Problem Details handler are in Request Validation (this page uses the same member names and adds the 500 path, the domain mapping layer and request ids); routes, status-code basics and the first HTTPException are in FastAPI Fundamentals; dependencies with yield and when their teardown runs relative to a streamed response are in Dependency Injection; where handlers and routers live in a bigger project is APIRouter & Project Structure; BackgroundTasks in depth, caching and outbound HTTP clients are in Background Tasks, Caching & External APIs; Uvicorn/Gunicorn tuning, log configuration and Nginx in front are in FastAPI in Production; the LLM streaming endpoint of the end-to-end project is in FastAPI AI/RAG Project and the provider side of streaming is in LLM APIs in Practice. Status-code and error-format design is in REST API Design, chunked encoding and HTTP/2 framing in HTTP Evolution, and the comparison of polling, SSE and WebSockets at scale in Real-time: Polling, SSE, WebSockets. The Go side is net/http: Server, Client, Errors, panic, recover, defer and File Uploads, S3 & CDN.
Facts below were checked against the FastAPI documentation (Handling Errors, Response Model, Response Status Code, Static Files, Background Tasks, Additional Responses, Additional Status Codes, Custom Response, Return a Response Directly, Response Headers, Response Cookies, Stream Data, Server-Sent Events, the reference for responses, exceptions and StaticFiles, and the release notes up to 0.165.0 of 2026-11-18), the Starlette docs (responses, exceptions, middleware, requests, static files), the installed source of Starlette 0.49.3, FastAPI 0.128.8, Uvicorn 0.39.0 and sse-starlette 3.3.0 (saved next to the other sources), the sse-starlette README, the WHATWG HTML "Server-sent events" section, RFC 9457, RFC 9110, RFC 9112, the Nginx ngx_http_proxy_module docs, the orjson README, the Laravel 13.x errors, responses and filesystem docs and the Go blog's "Working with Errors in Go 1.13". The page is written for Python 3.12+ and current FastAPI. The snippets ran on the only interpreter on the build machine, CPython 3.9.6, so the snippet project pins the newest releases that still install there: FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, Uvicorn 0.39.0, sse-starlette 3.3.0, orjson 3.11.5, httpx 0.28.1 and pytest 8.4.2, plus eval-type-backport; the resolved set is in the saved requirements.lock. Everything marked "real" below is what that run printed. Features newer than the pin are described from the release notes and dated: yield with response_class=StreamingResponse and JSON Lines in 0.134.0 (2026-02-27), fastapi.sse.EventSourceResponse in 0.135.0 (2026-03-01), the deprecation of ORJSONResponse in 0.131.0 (2026-02-22) and app.frontend() in 0.138.0 (2026-06-20).
Page map
| If you are looking for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
| Why errors are exceptions and responses are classes | Why it exists |
| Versions: Starlette handlers to FastAPI 0.135 SSE | Where it comes from |
| A before/after service | Python |
raise HTTPException(404, detail=..., headers=...) | HTTPException |
Which HTTPException to register a handler for | FastAPI's vs Starlette's HTTPException |
@app.exception_handler(MyError) | Custom exception classes and handlers |
The 500 path, ServerErrorMiddleware, re-raise | The handler for Exception |
FastAPI(debug=True) | Debug mode |
| Changing the 422 body | RequestValidationError override |
application/problem+json everywhere | Problem Details as the house format |
OrderNotFound → 404, OutOfStock → 409 | Domain error mapping |
| Finding a 500 in the logs | Logging exceptions with request ids |
Errors in /docs | The responses parameter and error models |
response_model or -> OrderOut? | response_model vs return type annotation |
Leaving out null and defaults | exclude_unset and exclude_none |
HTMLResponse, RedirectResponse, ORJSONResponse | Response classes |
return JSONResponse(...) | Returning a Response directly |
| Headers and cookies on a response | Response headers and Set-Cookie |
201 + Location, 204, 304 + ETag | Status codes that carry meaning |
Downloads, Range, uploads | FileResponse and downloads |
| Generators, chunked encoding | StreamingResponse |
| A slow client | Back-pressure |
| The client closed the tab | Client disconnect |
| An exception after the first byte | Errors in the middle of a stream |
text/event-stream, id:, retry: | Server-Sent Events |
sse-starlette, fastapi.sse or by hand | SSE implementations |
| Nginx buffering, idle timeouts | Proxies, buffering and keep-alive comments |
| Streaming tokens from an LLM | LLM token streaming |
app.mount("/app", StaticFiles(...)) | StaticFiles |
| Work after the response | BackgroundTasks preview |
| What happens inside, exact log lines | Mechanics |
| The common bugs and their fixes | Solving the classic problems |
| Which response class, which streaming transport | Choosing |
| Monolith to distributed system | In architecture |
| Reproduce it on your machine | Lab |
Laravel's exception handler and response()->stream | For PHP/Laravel developers |
Go's error values and errors.Is | The Go angle |
Everything in one minute
Where each failure goes. Every row was produced by the snippet app (real); each is unpacked in the concept catalogue.
| What happens | Caught by | Status | Body (snippet app) |
|---|---|---|---|
raise HTTPException(401, headers={"WWW-Authenticate": "Bearer"}) | ExceptionMiddleware → handler for Starlette's HTTPException | 401 + the header | application/problem+json, type: about:blank |
| Router finds no route | same handler (the router raises Starlette's HTTPException) | 404 | Problem, title: Not Found |
| Path matches, method does not | same handler | 405 + allow | Problem, title: Method Not Allowed |
| Invalid input | handler for RequestValidationError | 422 | Problem with an errors extension |
raise OrderNotFound(...) in the store | handler for DomainError + mapping table | 404 | Problem, type: .../order-not-found |
raise OutOfStock(...) / DuplicateOrder(...) | same | 409 | Problem, type: .../out-of-stock |
raise PaymentProviderDown(...) | same | 503 + Retry-After | Problem |
| Any other exception | ServerErrorMiddleware → handler for Exception | 500 | generic Problem with request_id; then re-raised and logged by Uvicorn |
| Exception after the first streamed byte | nobody can change the status any more | 200 already sent | truncated chunked body |
| No handlers installed at all | Starlette defaults | as above | {"detail": ...} JSON, 500 is Internal Server Error as text/plain |
Which response class. response_class= documents the media type; returning an instance sends it as is.
| Class | Media type | Use for | Note |
|---|---|---|---|
| (none, a model or return type) | application/json | Normal API responses | Fastest path: Pydantic serialises the model directly |
JSONResponse | application/json | Hand-built JSON, error bodies | Skips response_model when returned |
ORJSONResponse | application/json | Legacy speed-up | Deprecated in 0.131.0; needs orjson |
PlainTextResponse | text/plain; charset=utf-8 | Health checks, CSV snippets | |
HTMLResponse | text/html; charset=utf-8 | Small pages, email previews | Templates: Jinja2 |
RedirectResponse | — | 307 default; 301/302/303/308 by argument | Location header |
FileResponse | from the filename | Downloads | Content-Length, Last-Modified, ETag, Range → 206 |
StreamingResponse | you set it | Exports, proxies, LLM text, SSE by hand | Chunked; no Content-Length |
EventSourceResponse (sse-starlette, or fastapi.sse 0.135+) | text/event-stream | SSE with pings and headers done for you | Two different classes with the same name |
Response | you set it | 204, 304, bytes you built | Base class of all of them |
Streams in one table.
| Concern | What to do | Real result in the snippet |
|---|---|---|
| Framing | StreamingResponse(gen(), media_type=...) | transfer-encoding: chunked, no content-length |
| Blocking source (file, sync DB cursor) | sync generator; Starlette iterates it in the thread pool | CSV export of 5000 rows |
| Slow client | nothing: await send blocks the generator | producer stopped after 18 × 64 KiB while the client read nothing |
| Disconnect | an await per chunk; request.is_disconnected() between chunks | ticks cancelled after 18 chunks (client disconnected) |
| SSE headers | text/event-stream, Cache-Control: no-store, X-Accel-Buffering: no | set by hand or by sse-starlette |
| Idle connection | a comment line (: keep-alive) every ~15 s | three comments in 0.3 s with ping=0.1 |
| Resume | id: per event; read Last-Event-ID | Last-Event-ID: 1 → only event 2 |
Why it exists
An HTTP API has two kinds of outcome: the thing the client asked for, and the reasons it could not have it. In most frameworks the second kind is scattered: a function returns {"error": ...} with status 200, another returns a tuple, a third lets an exception escape as an HTML page. FastAPI inherits Starlette's answer, which treats failures as exceptions and puts the translation to HTTP in one place: raise anywhere (a dependency, a service three calls deep), and a handler registered once turns the exception into a response. Expected failures ("handled exceptions" in Starlette's words) become normal responses that flow back through every middleware; unexpected ones ("errors") become a 500 and keep propagating so the server logs them. The same split runs through the success side: a returned value goes through the response model (validation, filtering, documentation), while a returned Response object is sent exactly as built, which is how you produce HTML, files, redirects, 204s and streams.
| Errors as return values (the "Before" app) | Errors as exceptions + one mapping layer (the "After" app) |
|---|---|
return {"error": "not found"} with 200 | raise OrderNotFound(...) → 404 Problem |
| Every endpoint invents its own shape | One application/problem+json envelope |
| Services return HTTP-ish values | Services raise domain errors and know no HTTP |
except Exception: return 400 hides bugs | Bugs become a 500, logged once with a request id |
Tracebacks or secrets in bodies (debug=True) | Generic body; details in the log only |
/docs shows only 200 | responses= documents 404/409/503 with the error model |
An everyday picture. A hotel. The front desk is the response layer: whatever happens upstairs, a guest gets a clear, polite answer in the house format ("Room 412 is not ready, here is your waiting time"). Housekeeping and the kitchen do not walk into the lobby to explain; they raise a short note ("room not cleaned", "oven broken") that travels down to the desk. The desk has a binder (the exception handlers): for each kind of note it knows what to say and which code to give. A note nobody has a page for ("water coming through the ceiling") goes to the duty manager (ServerErrorMiddleware), who tells the guest only "we have a problem, here is your reference number" and also files an incident report (re-raise, server log) with that number. Room service that carries dishes one by one up the stairs is a stream: if the guest's table is full, the waiter waits at the door (back-pressure); if the guest checks out, the kitchen stops cooking (disconnect).
Three common misunderstandings, up front
- "A handler for
Exceptionmeans exceptions are now 'handled'." It means the 500 response is yours. Starlette'sServerErrorMiddlewarestill re-raises the exception after sending it: "We always continue to raise the exception. This allows servers to log the error, or allows test clients to optionally raise the error within the test case" (source, Starlette 0.49.3). That is whyTestClient(app)raisesRuntimeErrorin the test even though a 500 was produced, and why Uvicorn logsException in ASGI application(both real). - "
return HTTPException(...)andraise HTTPException(...)are the same." Returning it is a bug: without a return annotation it is serialised as{"status_code":409,"detail":"out of stock","headers":null}with status 200; with-> Anythe serialiser fails and the client gets a 500 (both real). - "Streaming is for big files only." A stream is any response whose body is produced while it is sent: CSV exports, proxying an upstream, LLM tokens, and every Server-Sent Events endpoint. Its rules (status and headers are fixed at the first byte; a slow client pauses you; a gone client cancels you) apply to all of them.
Where it comes from
Starlette's exception design predates FastAPI: handled exceptions (HTTPException) are rendered by ExceptionMiddleware, errors by ServerErrorMiddleware, which is "always the outermost middleware layer". FastAPI kept that machine and added its own HTTPException subclass (whose detail accepts "any JSON-able data"), RequestValidationError and the default handlers in fastapi.exception_handlers. Over time FastAPI changed when things happen around exceptions: 0.106.0 (2023-12-25) let dependencies with yield raise after yield ("Before FastAPI 0.106.0, raising exceptions after yield was not possible"), and 0.118.0 (2025-09-29) moved the exit code of yield dependencies back to after the response is sent, because otherwise "the StreamingResponse would not be able to use that session while streaming data". On the response side, 0.131.0 (2026-02-22) deprecated ORJSONResponse and UJSONResponse after 0.130.0 made Pydantic serialise JSON in Rust; 0.134.0 (2026-02-27) added "streaming JSON Lines and binary data with yield"; 0.135.0 (2026-03-01) added "support for Server Sent Events" (fastapi.sse). Starlette's FileResponse gained HTTP range requests ("If the request includes a Range header, and the file exists, the response will be a 206 Partial Content response"). Problem Details became RFC 7807 in 2016 and RFC 9457, which "obsoletes RFC 7807", in July 2023. Server-Sent Events are defined in the WHATWG HTML standard, section 9.2.
1 2016-03 RFC 7807 Problem Details for HTTP APIs
2 2019-02 FastAPI 0.1.x on Starlette: HTTPException + exception_handlers
3 2022-06 RFC 9110 (HTTP semantics: 201/204/304/409/422) and RFC 9112 (chunked coding)
4 2023-07 RFC 9457 obsoletes RFC 7807; FastAPI 0.100 on Pydantic v2
5 2023-12 FastAPI 0.106: dependencies with yield may raise after yield
6 2025-09 FastAPI 0.118: yield-dependency exit runs after the response (streams keep their session)
7 2026-02 0.130 Rust JSON serialisation; 0.131 ORJSONResponse deprecated; 0.134 yield streaming + JSON Lines
8 2026-03 FastAPI 0.135: fastapi.sse EventSourceResponse, ServerSentEvent
9 2026-06 FastAPI 0.138: app.frontend() for single-page apps on top of StaticFiles
10 2026-11 sse-starlette 3.7.1 (needs Python 3.11+); snippets pin 3.3.0, the last for 3.9Python
Before
An orders API that works on a quiet day. A missing order is a 200 with {"error": ...}; out-of-stock returns an HTTPException instead of raising it; creation answers 200 without Location; a catch-all except Exception turns a bug (KeyError('sku')) into a 400 and leaks its message; debug=True sends tracebacks (and the secret in the exception message) to clients; the export builds 10 000 rows in memory before streaming them and sends no Content-Type; the "events" endpoint streams JSON with no SSE framing and no SSE headers.
"""Before: the error and response bugs this chapter removes. Every one is pinned by tests/test_before.py."""
import asyncio
import json
from typing import Any, Dict
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse, StreamingResponse
app = FastAPI(debug=True) # 1. debug=True: a 500 sends the full traceback (with locals' source) to the client
ORDERS: Dict[int, Dict[str, Any]] = {1: {"id": 1, "sku": "BOOK-1", "qty": 1, "status": "shipped"}}
STOCK = {"BOOK-1": 5, "GAME-1": 0}
@app.get("/orders/{order_id}")
def get_order(order_id: int) -> Any:
try:
return ORDERS[order_id]
except KeyError:
return {"error": "not found"} # 2. status 200 for a failure; caches and clients believe it
@app.post("/orders")
def create_order(body: Dict[str, Any]): # type: ignore[no-untyped-def] (no return annotation)
try:
if STOCK[body["sku"]] < body["qty"]:
return HTTPException(409, "out of stock") # 3. *returned*, not raised: serialised with 200
STOCK[body["sku"]] -= body["qty"]
new_id = max(ORDERS) + 1
ORDERS[new_id] = {"id": new_id, **body, "status": "open"}
return ORDERS[new_id] # 4. 200 instead of 201, no Location header
except Exception as exc: # 5. catch-all turns bugs into 400s and leaks the message
return JSONResponse({"error": str(exc)}, status_code=400)
@app.get("/boom")
def boom() -> Any:
raise RuntimeError("database password is hunter2")
@app.get("/export")
def export() -> StreamingResponse:
rows = [json.dumps({"id": i}) + "\n" for i in range(10_000)] # 6. whole export built in memory first
return StreamingResponse(iter(rows)) # 7. no media_type: no Content-Type header at all
@app.get("/events")
async def events() -> StreamingResponse:
async def gen(): # type: ignore[no-untyped-def]
for i in range(3):
yield json.dumps({"n": i}) # 8. not SSE framing: no "data:" and no blank line
await asyncio.sleep(0)
# 9. text/plain, no Cache-Control: no-store, no X-Accel-Buffering: no, no keep-alive comments
return StreamingResponse(gen())The tests pin each bug down (all real):
"""Pins down every bug in app/before.py."""
from fastapi.testclient import TestClient
from app.before import app
client = TestClient(app, raise_server_exceptions=False)
def test_missing_order_is_a_200() -> None:
r = client.get("/orders/99")
assert r.status_code == 200 and r.json() == {"error": "not found"}
def test_returned_http_exception_is_serialised_with_200() -> None:
r = client.post("/orders", json={"sku": "GAME-1", "qty": 1})
assert r.status_code == 200
assert r.json() == {"status_code": 409, "detail": "out of stock", "headers": None}
def test_create_answers_200_without_location() -> None:
r = client.post("/orders", json={"sku": "BOOK-1", "qty": 1})
assert r.status_code == 200 and "location" not in r.headers
def test_catch_all_turns_a_bug_into_400_and_leaks_the_message() -> None:
r = client.post("/orders", json={"qty": 1}) # KeyError('sku') is a bug, reported as a client error
assert r.status_code == 400 and r.json() == {"error": "'sku'"}
def test_debug_true_sends_the_traceback_to_the_client() -> None:
r = client.get("/boom")
assert r.status_code == 500
assert r.headers["content-type"].startswith("text/plain") # non-browser client: plain traceback
assert "hunter2" in r.text and "Traceback" in r.text
def test_streaming_without_media_type_has_no_content_type() -> None:
r = client.get("/export")
assert "content-type" not in r.headers
assert r.text.count("\n") == 10_000
def test_events_are_not_sse() -> None:
r = client.get("/events")
assert "content-type" not in r.headers
assert r.text == '{"n": 0}{"n": 1}{"n": 2}' # no data: lines, no blank-line separatorsAfter
The domain layer raises meaning, not HTTP:
"""Domain errors: raised by the service layer, which knows nothing about HTTP.
The HTTP layer (app/problems.py) maps each class to a status code and a Problem Details type.
Compare Go's sentinel errors + errors.Is and Laravel's report()/render() on the exception.
"""
from typing import Any, Dict
class DomainError(Exception):
"""Base class: one handler for this class covers every subclass (handler lookup walks the MRO)."""
def __init__(self, detail: str, **context: Any) -> None:
super().__init__(detail)
self.detail = detail
# Safe, client-facing context (ids, counts). Never secrets or raw input.
self.context: Dict[str, Any] = context
class OrderNotFound(DomainError):
"""No order with that id (or not visible to this caller)."""
class OutOfStock(DomainError):
"""The request is valid, but the current stock cannot satisfy it."""
class DuplicateOrder(DomainError):
"""The idempotency key was already used: the UNIQUE constraint said so."""
class OrderNotCancellable(DomainError):
"""The order's state forbids the transition (shipped orders cannot be cancelled)."""
class PaymentProviderDown(DomainError):
"""A dependency is unavailable; the client may retry later."""
def __init__(self, detail: str, retry_after: int = 30, **context: Any) -> None:
super().__init__(detail, **context)
self.retry_after = retry_afterThe store translates SQL outcomes into domain errors (rowcount == 0 → OutOfStock, IntegrityError on the UNIQUE key → DuplicateOrder):
"""A small SQLite store. The SQL is what the page's ```sql block shows.
sqlite3 is a blocking driver, so the routes that call it are `def` (FastAPI runs them in the thread pool).
The same mapping applies to SQLAlchemy: IntegrityError -> DuplicateOrder, NoResultFound -> OrderNotFound.
"""
import sqlite3
import threading
from typing import Any, Dict, Optional
from app.domain import DuplicateOrder, OrderNotCancellable, OrderNotFound, OutOfStock
SCHEMA = """
CREATE TABLE stock (
sku TEXT PRIMARY KEY,
available INTEGER NOT NULL CHECK (available >= 0)
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
sku TEXT NOT NULL REFERENCES stock (sku),
qty INTEGER NOT NULL CHECK (qty > 0),
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'shipped', 'cancelled')),
note TEXT,
idempotency_key TEXT UNIQUE
);
"""
RESERVE_SQL = "UPDATE stock SET available = available - ? WHERE sku = ? AND available >= ?"
INSERT_SQL = "INSERT INTO orders (sku, qty, note, idempotency_key) VALUES (?, ?, ?, ?)"
GET_SQL = "SELECT id, sku, qty, status, note FROM orders WHERE id = ?"
CANCEL_SQL = "UPDATE orders SET status = 'cancelled' WHERE id = ? AND status = 'open'"
class Store:
def __init__(self) -> None:
self._conn = sqlite3.connect(":memory:", check_same_thread=False)
self._conn.row_factory = sqlite3.Row
self._lock = threading.Lock()
self._conn.executescript(SCHEMA)
self._conn.executemany(
"INSERT INTO stock (sku, available) VALUES (?, ?)", [("BOOK-1", 5), ("GAME-1", 0)]
)
self._conn.execute("INSERT INTO orders (sku, qty, status) VALUES ('BOOK-1', 1, 'shipped')")
self._conn.commit()
def get(self, order_id: int) -> Dict[str, Any]:
row = self._conn.execute(GET_SQL, (order_id,)).fetchone()
if row is None:
raise OrderNotFound(f"Order {order_id} does not exist.", order_id=order_id)
return dict(row)
def create(self, sku: str, qty: int, note: Optional[str], key: Optional[str]) -> Dict[str, Any]:
with self._lock, self._conn: # one transaction: reserve stock, insert order
if self._conn.execute(RESERVE_SQL, (qty, sku, qty)).rowcount == 0:
available = self._conn.execute(
"SELECT available FROM stock WHERE sku = ?", (sku,)
).fetchone()
raise OutOfStock(
f"{sku}: {available[0] if available else 0} left, {qty} requested.",
sku=sku,
requested=qty,
)
try:
cur = self._conn.execute(INSERT_SQL, (sku, qty, note, key))
except sqlite3.IntegrityError as exc: # UNIQUE(idempotency_key); the with-block rolls back
raise DuplicateOrder("This Idempotency-Key was already used.") from exc
return self.get(cur.lastrowid)
def cancel(self, order_id: int) -> None:
with self._lock, self._conn:
if self._conn.execute(CANCEL_SQL, (order_id,)).rowcount == 1:
return
status = self.get(order_id)["status"] # raises OrderNotFound when missing
raise OrderNotCancellable(f"Order {order_id} is {status}.", order_id=order_id, state=status)One module owns the HTTP side of errors: the mapping table, the Problem model, and the four handlers:
"""The HTTP side of errors: one mapping table, Problem Details bodies, and every handler.
Same member names as the Request Validation chapter's Problem model (type, title, status, detail,
instance + extensions); this module adds request_id and the domain mapping.
"""
import logging
from http import HTTPStatus
from typing import Any, Dict, Optional, Tuple, Type
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from fastapi.utils import is_body_allowed_for_status_code
from pydantic import BaseModel
from starlette.exceptions import HTTPException as StarletteHTTPException
from app.domain import (
DomainError,
DuplicateOrder,
OrderNotCancellable,
OrderNotFound,
OutOfStock,
PaymentProviderDown,
)
from app.observability import request_id_var
log = logging.getLogger("shop")
PROBLEM_JSON = "application/problem+json"
TYPE_BASE = "https://shop.example/problems/"
# The domain error mapping: the only place that knows which domain failure is which HTTP status.
DOMAIN_STATUS: Dict[Type[DomainError], Tuple[int, str, str]] = {
OrderNotFound: (404, "order-not-found", "Order not found"),
OutOfStock: (409, "out-of-stock", "Not enough stock"),
DuplicateOrder: (409, "duplicate-order", "Duplicate order"),
OrderNotCancellable: (409, "order-not-cancellable", "Order cannot be cancelled"),
PaymentProviderDown: (503, "payment-provider-down", "Payment provider unavailable"),
}
class Problem(BaseModel):
"""Error response model (RFC 9457), used in `responses=` so OpenAPI documents the errors."""
type: str = "about:blank"
title: str
status: int
detail: Optional[str] = None
instance: Optional[str] = None
request_id: Optional[str] = None
PROBLEM_RESPONSES: Dict[Any, Dict[str, Any]] = {
code: {
"model": Problem,
"description": desc,
"content": {PROBLEM_JSON: {"schema": {"$ref": "#/components/schemas/Problem"}}},
}
for code, desc in [(404, "Not found"), (409, "Conflict"), (503, "Dependency unavailable")]
}
def problem(request: Request, status: int, title: str, *, type_: str = "about:blank",
detail: Optional[str] = None, headers: Optional[Dict[str, str]] = None,
**extensions: Any) -> JSONResponse:
body: Dict[str, Any] = {"type": type_, "title": title, "status": status,
"instance": request.url.path, "request_id": request_id_var.get()}
if detail is not None:
body["detail"] = detail
body.update(extensions)
return JSONResponse(body, status_code=status, headers=headers, media_type=PROBLEM_JSON)
async def domain_error_handler(request: Request, exc: DomainError) -> JSONResponse:
# Walk the MRO so a subclass of OutOfStock still maps to 409.
for cls in type(exc).__mro__:
if cls in DOMAIN_STATUS:
status, slug, title = DOMAIN_STATUS[cls] # type: ignore[index]
break
else: # an unmapped DomainError is a bug in the mapping, not a client error
log.error("unmapped domain error %s", type(exc).__name__)
status, slug, title = 500, "unmapped-domain-error", "Internal Server Error"
headers = {"Retry-After": str(exc.retry_after)} if isinstance(exc, PaymentProviderDown) else None
log.info("domain error %s -> %s", type(exc).__name__, status)
return problem(request, status, title, type_=TYPE_BASE + slug, detail=exc.detail,
headers=headers, **exc.context)
async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> Response:
# Registered for Starlette's class: catches router 404/405 too, not only our raise HTTPException.
detail = exc.detail if isinstance(exc.detail, str) else None
extra = {} if isinstance(exc.detail, str) else {"errors": exc.detail}
title = HTTPStatus(exc.status_code).phrase
if not is_body_allowed_for_status_code(exc.status_code): # 1xx, 204, 304: headers only
return Response(status_code=exc.status_code, headers=exc.headers)
return problem(request, exc.status_code, title, detail=detail,
headers=dict(exc.headers) if exc.headers else None, **extra)
async def validation_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
# Minimal: the full RFC 9457 validation format (pointers, per-field codes) lives in the
# Request Validation chapter. Never echo `input`; it may hold passwords or personal data.
errors = [{"loc": list(e["loc"]), "code": e["type"], "detail": e["msg"]} for e in exc.errors()]
return problem(request, 422, "Unprocessable Content", type_=TYPE_BASE + "validation",
detail=f"{len(errors)} validation error(s)", errors=errors)
async def unhandled_handler(request: Request, exc: Exception) -> JSONResponse:
# Runs inside ServerErrorMiddleware, which re-raises afterwards so Uvicorn logs the traceback
# too. Log once here with the request id; return nothing internal to the client.
log.exception("unhandled %s on %s %s", type(exc).__name__, request.method, request.url.path)
rid = request_id_var.get()
return problem(request, 500, "Internal Server Error", detail="Unexpected error. Quote the request id.",
headers={"X-Request-ID": rid})
def install_problem_handlers(app: FastAPI) -> None:
app.add_exception_handler(DomainError, domain_error_handler)
app.add_exception_handler(StarletteHTTPException, http_exception_handler)
app.add_exception_handler(RequestValidationError, validation_handler)
app.add_exception_handler(Exception, unhandled_handler) # key Exception (or 500) -> ServerErrorMiddlewareRequest ids, a log filter and a pure ASGI middleware:
"""Request ids for logs and error bodies.
A pure ASGI middleware (not BaseHTTPMiddleware, which is awkward with streaming responses) stores the id
in a ContextVar and adds X-Request-ID to every response that passes through it. The 500 response built
by ServerErrorMiddleware does NOT pass through it (that middleware is outside every user middleware),
so the 500 handler reads the ContextVar and sets the header itself.
"""
import logging
import uuid
from contextvars import ContextVar
from starlette.datastructures import MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
request_id_var: ContextVar[str] = ContextVar("request_id", default="-")
class RequestIdFilter(logging.Filter):
"""Copies the current request id onto every log record as %(request_id)s."""
def filter(self, record: logging.LogRecord) -> bool:
record.request_id = request_id_var.get()
return True
def configure_logging() -> logging.Logger:
logger = logging.getLogger("shop")
if not logger.handlers:
logger.addFilter(RequestIdFilter()) # on the logger: every record from "shop" gets the id
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(levelname)s [%(request_id)s] %(name)s: %(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger
class RequestIdMiddleware:
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
incoming = dict(scope["headers"]).get(b"x-request-id", b"").decode("latin-1")
rid = incoming if 0 < len(incoming) <= 64 else uuid.uuid4().hex
# Not reset on exit on purpose: the 500 handler runs after this middleware has unwound
# and still needs the id. Each request runs in its own task, so values do not leak across requests.
request_id_var.set(rid)
async def send_with_id(message: Message) -> None:
if message["type"] == "http.response.start":
MutableHeaders(scope=message)["X-Request-ID"] = rid
await send(message)
await self.app(scope, receive, send_with_id)The application: response models and return annotations, 201 + Location, 204, an ETag/304 route, every response class, cookies, responses= for errors, a StaticFiles mount with html=True and per-file Cache-Control:
"""After: errors raised as exceptions and mapped once, every response class used on purpose."""
from __future__ import annotations
import hashlib
import json
import logging
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Annotated, Any, AsyncIterator, Dict
from fastapi import BackgroundTasks, FastAPI, Header, HTTPException, Path as PathParam, Request, Response, status
from fastapi.responses import (
FileResponse,
HTMLResponse,
JSONResponse,
ORJSONResponse,
PlainTextResponse,
RedirectResponse,
)
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
from app.db import Store
from app.domain import PaymentProviderDown
from app.observability import RequestIdMiddleware, configure_logging
from app.problems import PROBLEM_RESPONSES, install_problem_handlers
from app.streaming import router as streaming_router
log = configure_logging()
HERE = Path(__file__).parent
class OrderIn(BaseModel):
sku: str = Field(min_length=1, max_length=32)
qty: int = Field(gt=0, le=10)
note: str | None = None
class OrderOut(BaseModel):
id: int
sku: str
qty: int
status: str
note: str | None = None
class Preferences(BaseModel):
language: str = "en"
newsletter: bool = False
timezone: str | None = None
class CachedStaticFiles(StaticFiles):
"""StaticFiles sets ETag and Last-Modified but no Cache-Control; add one per file kind."""
def file_response(self, *args: Any, **kwargs: Any) -> Response:
response = super().file_response(*args, **kwargs)
path = str(args[0]) if args else ""
if "/assets/" in path: # fingerprinted names (app.3f9a1c.css) never change: cache for a year
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
else: # index.html and friends: revalidate every time (the ETag makes that a cheap 304)
response.headers["Cache-Control"] = "no-cache"
return response
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
app.state.store = Store()
app.state.prefs = {"u1": {"language": "fa"}} # only one field ever set by the user
yield
app = FastAPI(title="Orders with errors done right", version="1.0.0", lifespan=lifespan)
install_problem_handlers(app)
app.add_middleware(RequestIdMiddleware)
app.include_router(streaming_router)
def store(request: Request) -> Store:
return request.app.state.store
def send_confirmation(order_id: int) -> None:
log.info("confirmation sent for order %s", order_id) # BackgroundTasks preview: runs after the response
@app.get("/orders/{order_id}", response_model=OrderOut, response_model_exclude_none=True,
responses={404: PROBLEM_RESPONSES[404]}, tags=["orders"])
def get_order(order_id: Annotated[int, PathParam(ge=1)], request: Request) -> Dict[str, Any]:
order = store(request).get(order_id) # raises OrderNotFound -> 404 Problem via the handler
order["internal_cost_cents"] = 412 # filtered out by response_model, never sent
return order
@app.post("/orders", status_code=status.HTTP_201_CREATED, responses={409: PROBLEM_RESPONSES[409]},
tags=["orders"])
def create_order(body: OrderIn, request: Request, response: Response, tasks: BackgroundTasks,
idempotency_key: Annotated[str | None, Header()] = None) -> OrderOut:
order = store(request).create(body.sku, body.qty, body.note, idempotency_key)
response.headers["Location"] = f"/orders/{order['id']}" # 201 Created + Location header
tasks.add_task(send_confirmation, order["id"])
return OrderOut(**order) # the return type annotation is the response model here
@app.delete("/orders/{order_id}", status_code=status.HTTP_204_NO_CONTENT,
responses={404: PROBLEM_RESPONSES[404], 409: PROBLEM_RESPONSES[409]}, tags=["orders"])
def cancel_order(order_id: int, request: Request) -> None:
store(request).cancel(order_id) # 204 No Content: FastAPI sends no body
@app.get("/orders/{order_id}/receipt", tags=["orders"])
def receipt(order_id: int, request: Request,
if_none_match: Annotated[str | None, Header()] = None) -> Response:
order = store(request).get(order_id)
body = json.dumps(order, sort_keys=True).encode()
etag = '"' + hashlib.sha256(body).hexdigest()[:16] + '"' # ETag preview: strong validator of the bytes
headers = {"ETag": etag, "Cache-Control": "private, no-cache"}
if if_none_match == etag:
return Response(status_code=status.HTTP_304_NOT_MODIFIED, headers=headers) # no body
return Response(body, media_type="application/json", headers=headers)
@app.get("/legacy/orders/{order_id}", include_in_schema=False)
def legacy_order(order_id: int) -> RedirectResponse:
return RedirectResponse(f"/orders/{order_id}", status_code=status.HTTP_308_PERMANENT_REDIRECT)
@app.get("/fast/orders/{order_id}", response_class=ORJSONResponse, tags=["responses"])
def fast_order(order_id: int, request: Request) -> ORJSONResponse:
# Deprecated in FastAPI 0.131.0: a response model is serialised in Rust and is as fast.
return ORJSONResponse(store(request).get(order_id))
@app.get("/health", response_class=PlainTextResponse, include_in_schema=False)
def health() -> str:
return "ok"
@app.get("/welcome", response_class=HTMLResponse, tags=["responses"])
def welcome() -> str:
return "<!doctype html><title>Shop</title><h1>Welcome</h1>"
@app.get("/invoices/{order_id}.pdf", response_class=FileResponse, tags=["responses"])
def invoice(order_id: int, request: Request) -> FileResponse:
store(request).get(order_id) # 404 Problem first if the order is unknown
return FileResponse(HERE / "files" / "invoice.pdf", media_type="application/pdf",
filename=f"invoice-{order_id}.pdf") # Content-Disposition: attachment
@app.post("/session", tags=["responses"])
def login(response: Response) -> Dict[str, str]:
response.set_cookie("session", "opaque-token", httponly=True, secure=True, samesite="lax", max_age=3600)
return {"status": "signed in"} # Set-Cookie on Response: merged into the final JSON response
@app.get("/users/{user_id}/preferences", response_model=Preferences,
response_model_exclude_unset=True, tags=["responses"])
def preferences(user_id: str, request: Request) -> Preferences:
# Only fields that were explicitly set are sent; defaults stay out of the payload.
return Preferences(**request.app.state.prefs.get(user_id, {}))
@app.get("/me", tags=["errors"])
def me(authorization: Annotated[str | None, Header()] = None) -> Dict[str, str]:
if not authorization:
raise HTTPException(status_code=401, detail="Missing bearer token.",
headers={"WWW-Authenticate": "Bearer"}) # headers on exceptions
return {"user": "u1"}
@app.post("/payments", tags=["errors"], responses={503: PROBLEM_RESPONSES[503]})
def pay() -> Dict[str, str]:
raise PaymentProviderDown("The card processor timed out.", retry_after=30)
@app.get("/boom", include_in_schema=False)
def boom() -> Dict[str, str]:
raise RuntimeError("database password is hunter2") # must never reach the client
@app.get("/manual-404", tags=["errors"])
def manual_404() -> JSONResponse:
# Returning a Response skips response_model and the exception handlers: you own everything.
return JSONResponse({"detail": "hand-made"}, status_code=404)
# A mount owns every path under its prefix; html=True serves index.html for "/app/".
app.mount("/app", CachedStaticFiles(directory=HERE / "static", html=True), name="static")Streaming and SSE: a sync-generator CSV export, an async generator that notices disconnects, a back-pressure probe, hand-rolled SSE with id/retry/keep-alive comments and Last-Event-ID, the same stream through sse-starlette, and an LLM-style token stream:
"""StreamingResponse and Server-Sent Events on FastAPI 0.128.8 (no fastapi.sse yet: that is 0.135.0+)."""
import asyncio
import csv
import io
import json
import logging
from typing import Annotated, Any, AsyncIterator, Dict, Iterator, List, Optional
from fastapi import APIRouter, Header, Query, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from sse_starlette import EventSourceResponse, ServerSentEvent
log = logging.getLogger("shop")
router = APIRouter(tags=["streaming"])
# What the generators did, so tests (and the lab) can see cleanup after a disconnect.
STREAM_EVENTS: List[str] = []
PRODUCED: Dict[str, int] = {"chunks": 0}
SSE_HEADERS = {
"Cache-Control": "no-store", # never store an event stream (no-cache would allow storage + revalidation)
"X-Accel-Buffering": "no", # Nginx: pass bytes through as they arrive
}
# ---------- StreamingResponse ----------
def csv_rows(count: int) -> Iterator[str]:
"""A sync generator: Starlette iterates it in the thread pool (iterate_in_threadpool)."""
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow(["id", "sku", "qty"])
for i in range(1, count + 1):
writer.writerow([i, f"SKU-{i % 7}", i % 3 + 1])
if buf.tell() > 8192: # flush in ~8 KiB pieces, not one write per row
yield buf.getvalue()
buf.seek(0)
buf.truncate()
yield buf.getvalue()
@router.get("/export/orders.csv")
def export_csv(rows: Annotated[int, Query(ge=1, le=1_000_000)] = 1000) -> StreamingResponse:
return StreamingResponse(csv_rows(rows), media_type="text/csv",
headers={"Content-Disposition": 'attachment; filename="orders.csv"'})
@router.get("/stream/ticks")
async def ticks(request: Request, n: Annotated[int, Query(ge=1, le=10_000)] = 5,
delay: Annotated[float, Query(ge=0, le=5)] = 0.0) -> StreamingResponse:
async def gen() -> AsyncIterator[bytes]:
sent = 0
try:
for i in range(n):
if await request.is_disconnected(): # cheap check between chunks
STREAM_EVENTS.append(f"ticks: client gone after {sent}")
return
yield f"tick {i}\n".encode()
sent += 1
await asyncio.sleep(delay) # an await: also the point where cancellation lands
STREAM_EVENTS.append(f"ticks: done {sent}")
except asyncio.CancelledError:
STREAM_EVENTS.append(f"ticks: cancelled after {sent}")
log.info("ticks cancelled after %s chunks (client disconnected)", sent)
raise
finally:
STREAM_EVENTS.append("ticks: cleanup") # close upstream calls, cursors, files here
return StreamingResponse(gen(), media_type="text/plain")
@router.get("/stream/big")
async def big(chunks: Annotated[int, Query(ge=1, le=100_000)] = 64,
size: Annotated[int, Query(ge=1, le=1_048_576)] = 65536) -> StreamingResponse:
"""For the back-pressure lab: counts how far the producer gets ahead of a slow reader."""
PRODUCED["chunks"] = 0
payload = b"x" * size
async def gen() -> AsyncIterator[bytes]:
for _ in range(chunks):
PRODUCED["chunks"] += 1
yield payload # `await send(...)` behind this yield blocks while the socket buffer is full
return StreamingResponse(gen(), media_type="application/octet-stream")
# ---------- Server-Sent Events, hand-rolled ----------
def sse_frame(data: str, event: Optional[str] = None, id: Optional[str] = None,
retry: Optional[int] = None) -> bytes:
"""One SSE event: field lines, then a blank line. Multi-line data becomes several data: lines."""
lines = []
if event:
lines.append(f"event: {event}")
if id is not None:
lines.append(f"id: {id}")
if retry is not None:
lines.append(f"retry: {retry}")
lines.extend(f"data: {part}" for part in data.split("\n"))
return ("\n".join(lines) + "\n\n").encode()
ORDER_EVENTS = [
{"id": 1, "status": "paid"},
{"id": 1, "status": "packed"},
{"id": 1, "status": "shipped"},
]
@router.get("/sse/orders")
async def order_events(request: Request,
last_event_id: Annotated[Optional[str], Header()] = None,
# idle: seconds of silence after the last event (up to 5 min, for proxy-timeout labs)
idle: Annotated[float, Query(ge=0, le=300)] = 0.0,
# ping: keep-alive interval in seconds; 0 disables keep-alive comments
ping: Annotated[float, Query(ge=0, le=30)] = 15.0) -> StreamingResponse:
start = int(last_event_id) + 1 if last_event_id and last_event_id.isdigit() else 0
async def gen() -> AsyncIterator[bytes]:
yield b": stream opened\n\n" # a comment line: ignored by EventSource
yield b"retry: 5000\n\n" # reconnection time for EventSource, in ms
for seq in range(start, len(ORDER_EVENTS)):
if await request.is_disconnected():
return
yield sse_frame(json.dumps(ORDER_EVENTS[seq]), event="order", id=str(seq))
# Quiet period: keep-alive comments so proxies do not close an idle connection.
if ping == 0:
await asyncio.sleep(idle) # silent: a proxy with a shorter read timeout closes the stream
else:
waited = 0.0
while waited < idle:
step = min(ping, idle - waited)
await asyncio.sleep(step)
waited += step
yield b": keep-alive\n\n"
yield sse_frame("bye", event="end")
return StreamingResponse(gen(), media_type="text/event-stream", headers=SSE_HEADERS)
# ---------- Server-Sent Events with sse-starlette ----------
@router.get("/sse/lib")
async def lib_events(request: Request) -> EventSourceResponse:
async def gen() -> AsyncIterator[Any]:
for seq, item in enumerate(ORDER_EVENTS):
yield ServerSentEvent(data=json.dumps(item), event="order", id=str(seq))
yield {"event": "end", "data": "bye"} # dicts work too
return EventSourceResponse(gen(), ping=15) # sets Cache-Control, X-Accel-Buffering, pings
# ---------- LLM token streaming (provider-neutral fake) ----------
class ChatIn(BaseModel):
prompt: str
async def fake_llm_tokens(prompt: str) -> AsyncIterator[str]:
"""Stands in for an OpenAI-compatible or native SDK stream (`async for chunk in stream`)."""
try:
for word in f"You asked: {prompt}. Here is a short answer.".split(" "):
await asyncio.sleep(0.01)
yield word + " "
finally:
STREAM_EVENTS.append("llm: upstream closed") # with a real SDK: close the HTTP stream
@router.post("/chat/stream")
async def chat_stream(body: ChatIn, request: Request) -> StreamingResponse:
async def gen() -> AsyncIterator[bytes]:
tokens = fake_llm_tokens(body.prompt)
try:
async for token in tokens:
if await request.is_disconnected():
STREAM_EVENTS.append("llm: client gone, stop paying for tokens")
break
yield sse_frame(json.dumps({"delta": token}), event="token")
else:
yield sse_frame("[DONE]") # sentinel the OpenAI-style clients look for
except Exception: # headers are already sent: a status code cannot change any more
log.exception("stream failed mid-way")
yield sse_frame(json.dumps({"title": "stream failed"}), event="error")
finally:
await tokens.aclose()
return StreamingResponse(gen(), media_type="text/event-stream", headers=SSE_HEADERS)A separate tiny app for the mid-stream failure lab: the generator raises after the first chunk, so the Exception handler can never run:
"""Lab 5: an exception after the first streamed chunk. Run: uvicorn app.midstream:app --port 18922"""
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, StreamingResponse
app = FastAPI()
@app.exception_handler(Exception)
async def any_error(request: Request, exc: Exception) -> JSONResponse:
return JSONResponse({"never": "sent"}, status_code=500) # cannot run: the response already started
@app.get("/s")
async def s() -> StreamingResponse:
async def gen(): # type: ignore[no-untyped-def]
yield b"part 1\n"
raise RuntimeError("upstream died") # status 200 and headers are already on the wire
return StreamingResponse(gen(), media_type="text/plain")The tests: handlers and the 500 path, response classes and status codes, static files, stream framing under TestClient, and the behaviours only a real Uvicorn shows (chunked encoding, disconnects, back-pressure, the server's own error log):
from typing import Iterator
import pytest
from fastapi.testclient import TestClient
from app.main import app
from app.streaming import STREAM_EVENTS
@pytest.fixture
def client() -> Iterator[TestClient]:
# `with` runs the lifespan: a fresh Store (and fresh stock) for every test.
with TestClient(app, raise_server_exceptions=False) as c:
yield c
@pytest.fixture(autouse=True)
def clear_stream_events() -> None:
STREAM_EVENTS.clear()"""Exception handlers: domain mapping, Starlette's HTTPException, 422, 500, request ids."""
import logging
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.domain import DomainError, OutOfStock
from app.main import app
from app.observability import RequestIdMiddleware
from app.problems import install_problem_handlers
PROBLEM = "application/problem+json"
def test_domain_error_maps_to_404_problem(client: TestClient) -> None:
r = client.get("/orders/99")
assert r.status_code == 404 and r.headers["content-type"] == PROBLEM
body = r.json()
assert body["type"] == "https://shop.example/problems/order-not-found"
assert body["title"] == "Order not found" and body["status"] == 404
assert body["instance"] == "/orders/99" and body["order_id"] == 99
assert body["request_id"] == r.headers["x-request-id"]
def test_router_404_and_405_reach_the_starlette_handler(client: TestClient) -> None:
r = client.get("/no-such-route")
assert r.status_code == 404 and r.headers["content-type"] == PROBLEM
assert r.json()["type"] == "about:blank" and r.json()["title"] == "Not Found"
r = client.put("/orders/1")
assert r.status_code == 405 and r.json()["title"] == "Method Not Allowed"
assert r.headers["allow"] == "GET" # headers on exceptions survive the custom handler
def test_http_exception_headers_are_kept(client: TestClient) -> None:
r = client.get("/me")
assert r.status_code == 401 and r.headers["www-authenticate"] == "Bearer"
assert r.json()["detail"] == "Missing bearer token."
def test_retry_after_on_503(client: TestClient) -> None:
r = client.post("/payments")
assert r.status_code == 503 and r.headers["retry-after"] == "30"
def test_out_of_stock_is_409_with_extensions(client: TestClient) -> None:
r = client.post("/orders", json={"sku": "GAME-1", "qty": 1})
assert r.status_code == 409
assert r.json()["sku"] == "GAME-1" and r.json()["requested"] == 1
def test_duplicate_idempotency_key_is_409_and_rolls_back(client: TestClient) -> None:
h = {"Idempotency-Key": "k-1"}
assert client.post("/orders", json={"sku": "BOOK-1", "qty": 2}, headers=h).status_code == 201
r = client.post("/orders", json={"sku": "BOOK-1", "qty": 3}, headers=h)
assert r.status_code == 409 and r.json()["title"] == "Duplicate order"
# 5 - 2 = 3 left: the second reservation was rolled back with the failed INSERT
assert client.post("/orders", json={"sku": "BOOK-1", "qty": 3}).status_code == 201
def test_cancel_shipped_order_is_409(client: TestClient) -> None:
r = client.delete("/orders/1")
assert r.status_code == 409 and r.json()["state"] == "shipped"
assert client.delete("/orders/42").status_code == 404
def test_validation_error_is_a_problem_without_input(client: TestClient) -> None:
r = client.post("/orders", json={"sku": "", "qty": 99, "password": "secret"})
assert r.status_code == 422 and r.headers["content-type"] == PROBLEM
codes = sorted(e["code"] for e in r.json()["errors"])
assert codes == ["less_than_equal", "string_too_short"]
assert "secret" not in r.text and "input" not in r.text
def test_unhandled_error_is_a_generic_500_with_request_id(client: TestClient,
caplog: pytest.LogCaptureFixture) -> None:
with caplog.at_level(logging.ERROR, logger="shop"):
r = client.get("/boom", headers={"X-Request-ID": "req-123"})
assert r.status_code == 500 and r.headers["content-type"] == PROBLEM
assert "hunter2" not in r.text and r.json()["request_id"] == "req-123"
assert r.headers["x-request-id"] == "req-123" # set by the handler, not by the middleware
rec = next(x for x in caplog.records if x.getMessage().startswith("unhandled RuntimeError"))
assert rec.request_id == "req-123" and rec.exc_info is not None # traceback logged once, with the id
def test_server_error_middleware_re_raises() -> None:
# The handler's response was produced, and the exception still propagates to the server/test client.
with TestClient(app) as strict: # raise_server_exceptions=True (the default)
with pytest.raises(RuntimeError, match="hunter2"):
strict.get("/boom")
def _mini_app() -> FastAPI:
mini = FastAPI()
install_problem_handlers(mini)
mini.add_middleware(RequestIdMiddleware)
return mini
def test_handler_lookup_walks_the_mro() -> None:
class FlashSaleSoldOut(OutOfStock):
pass
class Unmapped(DomainError):
pass
mini = _mini_app()
@mini.get("/sold-out")
def sold_out() -> None:
raise FlashSaleSoldOut("Gone in 3 seconds.")
@mini.get("/unmapped")
def unmapped() -> None:
raise Unmapped("nobody mapped me")
c = TestClient(mini, raise_server_exceptions=False)
assert c.get("/sold-out").status_code == 409 # handled by the DomainError handler, OutOfStock entry
assert c.get("/unmapped").json()["type"].endswith("/unmapped-domain-error")
def test_a_bug_inside_a_handler_becomes_a_500() -> None:
mini = _mini_app()
class Broken(Exception):
pass
@mini.exception_handler(Broken)
async def broken_handler(request, exc): # type: ignore[no-untyped-def]
raise TypeError("handler bug")
@mini.get("/x")
def x() -> None:
raise Broken()
r = TestClient(mini, raise_server_exceptions=False).get("/x")
assert r.status_code == 500 and r.json()["title"] == "Internal Server Error"
def test_without_handlers_a_500_is_plain_text() -> None:
bare = FastAPI()
@bare.get("/boom")
def boom() -> None:
raise RuntimeError("x")
r = TestClient(bare, raise_server_exceptions=False).get("/boom")
assert r.status_code == 500 and r.text == "Internal Server Error"
assert r.headers["content-type"].startswith("text/plain")"""Response models, status codes, response classes, headers and cookies."""
import logging
import pytest
from fastapi.testclient import TestClient
def test_201_with_location_and_background_task(client: TestClient, caplog: pytest.LogCaptureFixture) -> None:
with caplog.at_level(logging.INFO, logger="shop"):
r = client.post("/orders", json={"sku": "BOOK-1", "qty": 1, "note": "gift"})
assert r.status_code == 201 and r.headers["location"] == f"/orders/{r.json()['id']}"
assert any("confirmation sent" in m for m in caplog.messages) # ran after the response
def test_response_model_filters_and_excludes_none(client: TestClient) -> None:
body = client.get("/orders/1").json()
assert "internal_cost_cents" not in body # filtered by response_model
assert "note" not in body # response_model_exclude_none=True (note is NULL)
def test_return_annotation_is_the_model(client: TestClient) -> None:
body = client.post("/orders", json={"sku": "BOOK-1", "qty": 1}).json()
assert body["note"] is None # no exclude_none on this route: null is sent
def test_exclude_unset_sends_only_what_was_set(client: TestClient) -> None:
assert client.get("/users/u1/preferences").json() == {"language": "fa"}
assert client.get("/users/u2/preferences").json() == {}
def test_204_has_no_body(client: TestClient) -> None:
order_id = client.post("/orders", json={"sku": "BOOK-1", "qty": 1}).json()["id"]
r = client.delete(f"/orders/{order_id}")
assert r.status_code == 204 and r.content == b""
# Real on 0.128.8: no body and no Content-Length, but a stray "content-type: application/json".
assert "content-length" not in r.headers
assert r.headers["content-type"] == "application/json" # the stray header, pinned as a regression check
def test_etag_and_304(client: TestClient) -> None:
first = client.get("/orders/1/receipt")
etag = first.headers["etag"]
second = client.get("/orders/1/receipt", headers={"If-None-Match": etag})
assert second.status_code == 304 and second.content == b"" and second.headers["etag"] == etag
def test_redirect_html_text_orjson(client: TestClient) -> None:
r = client.get("/legacy/orders/1", follow_redirects=False)
assert r.status_code == 308 and r.headers["location"] == "/orders/1"
assert client.get("/welcome").headers["content-type"] == "text/html; charset=utf-8"
assert client.get("/health").text == "ok"
r = client.get("/fast/orders/1")
assert r.headers["content-type"] == "application/json" and r.json()["note"] is None
def test_file_response_download_and_range(client: TestClient) -> None:
r = client.get("/invoices/1.pdf")
assert r.status_code == 200 and r.headers["content-type"] == "application/pdf"
assert r.headers["content-disposition"] == 'attachment; filename="invoice-1.pdf"'
assert {"etag", "last-modified", "content-length", "accept-ranges"} <= set(r.headers)
part = client.get("/invoices/1.pdf", headers={"Range": "bytes=0-7"})
assert part.status_code == 206 and part.content == b"%PDF-1.4"
assert client.get("/invoices/99.pdf").status_code == 404
def test_set_cookie_on_response(client: TestClient) -> None:
r = client.post("/session")
cookie = r.headers["set-cookie"]
for attr in ("session=opaque-token", "HttpOnly", "Max-Age=3600", "SameSite=lax", "Secure"):
assert attr in cookie
assert r.json() == {"status": "signed in"}
def test_returning_a_response_bypasses_handlers(client: TestClient) -> None:
r = client.get("/manual-404")
assert r.status_code == 404 and r.headers["content-type"] == "application/json"
assert r.json() == {"detail": "hand-made"} # not a Problem: no handler ran
def test_openapi_documents_error_models(client: TestClient) -> None:
spec = client.get("/openapi.json").json()
get_order = spec["paths"]["/orders/{order_id}"]["get"]["responses"]
assert set(get_order) == {"200", "404", "422"}
assert "application/problem+json" in get_order["404"]["content"]
assert "Problem" in spec["components"]["schemas"]
assert "/boom" not in spec["paths"]
assert "text/html" in spec["paths"]["/welcome"]["get"]["responses"]["200"]["content"]"""StaticFiles mount: html=True, validators, Cache-Control per file kind."""
from fastapi.testclient import TestClient
def test_html_mode_serves_index_and_404_page(client: TestClient) -> None:
r = client.get("/app/")
assert r.status_code == 200 and "Shop front end" in r.text
assert r.headers["cache-control"] == "no-cache"
missing = client.get("/app/nope.html")
assert missing.status_code == 404 and "Page not found" in missing.text # 404.html in HTML mode
def test_fingerprinted_assets_are_immutable(client: TestClient) -> None:
r = client.get("/app/assets/app.3f9a1c.css")
assert r.headers["cache-control"] == "public, max-age=31536000, immutable"
assert r.headers["content-type"] == "text/css; charset=utf-8"
def test_conditional_get_returns_304(client: TestClient) -> None:
etag = client.get("/app/").headers["etag"]
r = client.get("/app/", headers={"If-None-Match": etag})
assert r.status_code == 304 and r.content == b""
def test_only_get_and_head(client: TestClient) -> None:
assert client.head("/app/").status_code == 200
assert client.post("/app/").status_code == 405
def test_path_traversal_is_refused(client: TestClient) -> None:
assert client.get("/app/../main.py").status_code == 404
assert client.get("/app/%2e%2e/main.py").status_code == 404"""A tiny SSE parser that follows the WHATWG line rules (enough for tests)."""
from typing import Dict, List
def parse_sse(text: str) -> List[Dict[str, str]]:
events: List[Dict[str, str]] = []
current: Dict[str, str] = {}
data: List[str] = []
for line in text.replace("\r\n", "\n").split("\n"):
if line == "": # blank line: dispatch
if data or current:
if data:
current["data"] = "\n".join(data)
events.append(current)
current, data = {}, []
elif line.startswith(":"): # comment
current.setdefault("comments", "")
current["comments"] += line[1:].strip() + ";"
else:
field, _, value = line.partition(":")
value = value[1:] if value.startswith(" ") else value
if field == "data":
data.append(value)
else:
current[field] = value
return events"""StreamingResponse and SSE framing under TestClient (finite streams only: TestClient reads to the end)."""
import json
from fastapi.testclient import TestClient
from app.streaming import STREAM_EVENTS, sse_frame
from tests.sse import parse_sse
def test_csv_export_streams_with_attachment_header(client: TestClient) -> None:
r = client.get("/export/orders.csv", params={"rows": 5000})
assert r.headers["content-type"] == "text/csv; charset=utf-8"
assert r.headers["content-disposition"] == 'attachment; filename="orders.csv"'
assert "content-length" not in r.headers # length unknown up front
assert r.text.splitlines()[0] == "id,sku,qty" and len(r.text.splitlines()) == 5001
def test_async_generator_runs_cleanup(client: TestClient) -> None:
with client.stream("GET", "/stream/ticks", params={"n": 3}) as r:
lines = list(r.iter_lines())
assert lines == ["tick 0", "tick 1", "tick 2"]
assert STREAM_EVENTS == ["ticks: done 3", "ticks: cleanup"]
def test_sse_frame_format() -> None:
assert sse_frame("a\nb", event="note", id="7") == b"event: note\nid: 7\ndata: a\ndata: b\n\n"
def test_hand_rolled_sse_headers_and_events(client: TestClient) -> None:
r = client.get("/sse/orders")
assert r.headers["content-type"] == "text/event-stream; charset=utf-8"
assert r.headers["cache-control"] == "no-store" and r.headers["x-accel-buffering"] == "no"
events = parse_sse(r.text)
assert events[0] == {"comments": "stream opened;"} and events[1] == {"retry": "5000"}
orders = [e for e in events if e.get("event") == "order"]
assert [e["id"] for e in orders] == ["0", "1", "2"]
assert json.loads(orders[-1]["data"]) == {"id": 1, "status": "shipped"}
assert events[-1] == {"event": "end", "data": "bye"}
def test_last_event_id_resumes(client: TestClient) -> None:
r = client.get("/sse/orders", headers={"Last-Event-ID": "1"})
ids = [e["id"] for e in parse_sse(r.text) if e.get("event") == "order"]
assert ids == ["2"]
def test_keep_alive_comments_while_idle(client: TestClient) -> None:
r = client.get("/sse/orders", params={"idle": 0.3, "ping": 0.1})
assert r.text.count(": keep-alive\n\n") == 3
def test_ping_zero_means_silence(client: TestClient) -> None:
r = client.get("/sse/orders", params={"idle": 0.2, "ping": 0})
assert ": keep-alive" not in r.text and parse_sse(r.text)[-1] == {"event": "end", "data": "bye"}
assert client.get("/sse/orders", params={"idle": 301}).status_code == 422 # bound kept
def test_error_after_first_chunk_is_not_handled() -> None:
import pytest
from app.midstream import app as mid
with pytest.raises(RuntimeError, match="upstream died"):
TestClient(mid).get("/s") # the 500 handler cannot replace a started response
r = TestClient(mid, raise_server_exceptions=False).get("/s")
assert r.status_code == 200 and "never" not in r.text
def test_sse_starlette_headers_and_framing(client: TestClient) -> None:
r = client.get("/sse/lib")
assert r.headers["content-type"] == "text/event-stream; charset=utf-8"
assert r.headers["cache-control"] == "no-store" and r.headers["x-accel-buffering"] == "no"
assert "\r\n" in r.text # sse-starlette's default separator is CRLF
events = parse_sse(r.text)
assert [e.get("id") for e in events] == ["0", "1", "2", None]
def test_llm_token_stream_ends_with_done(client: TestClient) -> None:
r = client.post("/chat/stream", json={"prompt": "hi"})
events = parse_sse(r.text)
text = "".join(json.loads(e["data"])["delta"] for e in events if e.get("event") == "token")
assert text.startswith("You asked: hi.") and events[-1] == {"data": "[DONE]"}
assert "llm: upstream closed" in STREAM_EVENTS"""Behaviour that only a real server shows: chunked encoding, disconnects, back-pressure, server logs.
Uvicorn runs in a background thread of the test process, so the app's STREAM_EVENTS/PRODUCED globals
are visible here. Numbers printed with `pytest -s` are machine-specific; the assertions are loose.
"""
import logging
import socket
import threading
import time
from typing import Iterator, List
import httpx
import pytest
import uvicorn
from app.main import app
from app.streaming import PRODUCED, STREAM_EVENTS
def _free_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return int(s.getsockname()[1])
@pytest.fixture(scope="module")
def base_url() -> Iterator[str]:
port = _free_port()
server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="info"))
thread = threading.Thread(target=server.run, daemon=True)
thread.start()
while not server.started:
time.sleep(0.01)
yield f"http://127.0.0.1:{port}"
server.should_exit = True
thread.join(timeout=5)
def _wait_for(predicate, timeout: float = 3.0) -> bool: # type: ignore[no-untyped-def]
end = time.monotonic() + timeout
while time.monotonic() < end:
if predicate():
return True
time.sleep(0.02)
return False
def test_streaming_uses_chunked_transfer_encoding(base_url: str) -> None:
r = httpx.get(f"{base_url}/stream/ticks", params={"n": 3})
assert r.headers["transfer-encoding"] == "chunked" and "content-length" not in r.headers
assert r.text == "tick 0\ntick 1\ntick 2\n"
plain = httpx.get(f"{base_url}/orders/1")
assert "content-length" in plain.headers and "transfer-encoding" not in plain.headers
def test_client_disconnect_stops_the_generator(base_url: str) -> None:
with httpx.stream("GET", f"{base_url}/stream/ticks", params={"n": 10_000, "delay": 0.01}) as r:
got = [line for _, line in zip(range(3), r.iter_lines())]
assert got == ["tick 0", "tick 1", "tick 2"]
assert _wait_for(lambda: "ticks: cleanup" in STREAM_EVENTS)
print("\nafter disconnect:", STREAM_EVENTS)
assert any(e.startswith(("ticks: cancelled after", "ticks: client gone after")) for e in STREAM_EVENTS)
assert not any(e.startswith("ticks: done") for e in STREAM_EVENTS)
def test_back_pressure_pauses_the_producer(base_url: str) -> None:
chunks, size = 512, 65536 # 32 MiB in total
host, port = base_url.replace("http://", "").split(":")
sock = socket.create_connection((host, int(port)))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 16384)
sock.sendall(f"GET /stream/big?chunks={chunks}&size={size} HTTP/1.1\r\nHost: x\r\n\r\n".encode())
time.sleep(0.5) # a slow client: read nothing for half a second
produced_while_stalled = PRODUCED["chunks"]
received = 0
while True:
data = sock.recv(1 << 20)
if not data:
break
received += len(data)
if received >= chunks * size:
break
sock.close()
print(f"\nproduced while the client read nothing: {produced_while_stalled}/{chunks} chunks "
f"({produced_while_stalled * size // 1024} KiB); total received {received // 1024} KiB")
assert produced_while_stalled < chunks # the generator waited on `await send(...)`
assert received >= chunks * size
class _Collect(logging.Handler):
def __init__(self) -> None:
super().__init__()
self.messages: List[str] = []
def emit(self, record: logging.LogRecord) -> None:
self.messages.append(record.getMessage())
def test_uvicorn_logs_the_re_raised_exception(base_url: str) -> None:
# Uvicorn's own loggers do not propagate to the root logger, so attach a handler directly.
collect = _Collect()
logging.getLogger("uvicorn.error").addHandler(collect)
try:
r = httpx.get(f"{base_url}/boom", headers={"X-Request-ID": "live-1"})
assert r.status_code == 500 and r.json()["request_id"] == "live-1"
assert _wait_for(lambda: any("Exception in ASGI application" in m for m in collect.messages))
finally:
logging.getLogger("uvicorn.error").removeHandler(collect)[project]
name = "exception-handling-responses"
version = "0.1.0"
description = "Snippets for the Exceptions & Responses chapter: HTTPException, exception handlers, domain errors, Problem Details, response classes, StreamingResponse, SSE, StaticFiles"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine. On 3.12+ move to the latest releases (FastAPI 0.135+
# also ships fastapi.sse.EventSourceResponse, see the page).
requires-python = ">=3.9"
dependencies = [
"fastapi==0.128.8",
# Pinned explicitly: the versions every "real run" on the page used.
"starlette==0.49.3",
"pydantic==2.13.5",
"uvicorn[standard]==0.39.0",
# Third-party SSE response class; 3.3.0 is the last release that admits Python 3.9.
"sse-starlette==3.3.0",
# Only for the ORJSONResponse demo; 3.11.5 is the last release that admits Python 3.9.
"orjson==3.11.5",
# Lets Pydantic evaluate `str | None` annotations on Python 3.9; not needed on 3.10+.
"eval-type-backport==0.4.0; python_version < '3.10'",
]
[project.optional-dependencies]
test = [
"httpx==0.28.1",
"pytest==8.4.2",
]
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[tool.setuptools]
packages = ["app"]
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q -p no:cacheprovider"
pythonpath = ["."]
# Uvicorn 0.39 imports the legacy websockets API; not this project's concern.
filterwarnings = ["ignore::DeprecationWarning:websockets.*", "ignore::DeprecationWarning:uvicorn.*"]The Python angle
Three Python features carry this chapter. Exceptions propagate through frames, so a raise OrderNotFound in Store.get skips the rest of the route and lands in whatever catches it first; the handler table is matched against the exception's class hierarchy (type(exc).__mro__), which is why one handler for a base class covers every subclass. Generators and async generators are the body of every stream: yield hands one chunk to Starlette, and an async generator is suspended at its yield while await send(...) waits for the socket, and receives CancelledError at its next await when the task is cancelled, which is when finally: blocks close upstream resources. A sync generator is driven from the thread pool (iterate_in_threadpool), so blocking reads inside it do not freeze the event loop. contextvars.ContextVar gives each request its own value ("Context variables are natively supported in asyncio"), which is how a request id reaches log records and the 500 handler without passing it through every call. Avoid from __future__ import annotations in modules that define class-based dependencies on FastAPI 0.128.8 (a known trap from the dependency chapter); the snippet uses it only in main.py, which has none.
The concept catalogue
HTTPException: status_code, detail and headers on exceptions Must-know
In plain words: raise HTTPException(status_code=404, detail="Order not found") stops the request right there, from any depth, and the client gets that status with {"detail": "Order not found"}. Add headers= when the status needs a header (WWW-Authenticate on 401, Retry-After on 429/503).
Common misunderstanding: "I can return it." The docs: "Because it's a Python exception, you don't return it, you raise it." Returned, it is just an object: 200 with its attributes as JSON (real, test_returned_http_exception_is_serialised_with_200), or a 500 if the route is annotated -> Any (real, runs/probe1-output.txt). Second: "detail must be a string." FastAPI's HTTPException accepts "any value that can be converted to JSON as the parameter detail, not only str" (real: {"detail":{"code":"out-of-stock","sku":"A"}}); Starlette's own class only accepts strings.
Definition: HTTPException(status_code, detail=None, headers=None). With no detail, Starlette uses "the standard phrase for the status code" (real: HTTPException(418) → {"detail":"I'm a Teapot"}). FastAPI's default handler sends {"detail": exc.detail} as JSON with exc.headers, and sends no body for statuses that cannot have one (204, 304, 1xx). FastAPI 0.128.7 typed headers as a Mapping instead of a dict.
GET /me (no Authorization header) (real, snippet app)
1 route me(): authorization is None
2 raise HTTPException(401, "Missing bearer token.", headers={"WWW-Authenticate": "Bearer"})
3 ExceptionMiddleware: handler for StarletteHTTPException (MRO: fastapi.HTTPException -> starlette HTTPException)
4 http_exception_handler -> problem(401, "Unauthorized", headers=exc.headers)
5 401 www-authenticate: Bearer content-type: application/problem+json
{"type":"about:blank","title":"Unauthorized","status":401,"instance":"/me","detail":"Missing bearer token.", ...}Real scenario: 401 with WWW-Authenticate: Bearer from an auth dependency; 403 when a scope is missing; 404 from a lookup helper used by many routes; 429 with Retry-After from a rate limiter dependency; 413 from an upload size check.
| You want | Write | Client sees (default handler) |
|---|---|---|
| Not found | raise HTTPException(404, "Order not found") | 404 {"detail":"Order not found"} |
| Structured detail | HTTPException(409, detail={"code": "out-of-stock"}) | 409 {"detail":{"code":"out-of-stock"}} |
| Auth challenge | headers={"WWW-Authenticate": "Bearer"} | 401 + header |
| Back off | HTTPException(429, headers={"Retry-After": "30"}) | 429 + header |
| Standard phrase | HTTPException(418) | {"detail":"I'm a Teapot"} |
| No body | HTTPException(304) | headers only |
Fix / how to use it: raise HTTPException for plain HTTP-level outcomes (auth, method, size); for business failures raise your own domain classes and map them once (Domain error mapping); never return an exception.
FastAPI's HTTPException vs starlette.exceptions.HTTPException Must-know
In plain words: There are two HTTPException classes. FastAPI's is a subclass of Starlette's. Raise FastAPI's in your code; register your handler for Starlette's, so it also catches what Starlette raises itself (the router's 404 and 405, StaticFiles' 404).
Common misunderstanding: "@app.exception_handler(HTTPException) with the class I import from fastapi changes every 404." It changes only the ones you raise. Real (runs/probe1-output.txt): with the handler on fastapi.HTTPException, raise HTTPException(404) returned {"custom": true} but an unknown path still returned {"detail":"Not Found"}.
Definition: The docs: "FastAPI's HTTPException error class inherits from Starlette's HTTPException error class. The only difference is that FastAPI's HTTPException accepts any JSON-able data for the detail field, while Starlette's HTTPException only accepts strings for it. … when you register an exception handler, you should register it for Starlette's HTTPException." Import it as from starlette.exceptions import HTTPException as StarletteHTTPException.
handler registered for raise HTTPException (fastapi) router 404 / 405 StaticFiles 404
1 fastapi.HTTPException your handler default handler default handler
2 starlette.exceptions.HTTPException your handler (subclass) your handler your handlerReal scenario: an API that must answer every 404 in Problem Details, including typos in the URL; a 405 that must keep its allow header (real: allow: GET survives the custom handler); a StaticFiles mount without a 404.html.
| Raised by | Class | Caught by a handler for Starlette's class? |
|---|---|---|
raise HTTPException(...) from fastapi | fastapi.HTTPException | Yes (subclass) |
| Router: no route | starlette.exceptions.HTTPException(404) | Yes |
| Router: wrong method | starlette.exceptions.HTTPException(405, headers={"Allow": ...}) | Yes |
StaticFiles miss (no 404.html) | Starlette's class | Yes |
| A Starlette extension | Starlette's class | Yes |
Fix / how to use it: one handler on StarletteHTTPException (the snippet's http_exception_handler), which keeps exc.headers and builds the house format; to keep FastAPI's default body and only add logging, call fastapi.exception_handlers.http_exception_handler from inside yours ("Reuse FastAPI's exception handlers").
Custom exception classes, @app.exception_handler and add_exception_handler Must-know
In plain words: Define your own exception class (class OutOfStock(DomainError)), raise it where the problem is detected, and register a function that turns it into a response: @app.exception_handler(DomainError) above an async def handler(request, exc), or app.add_exception_handler(DomainError, handler) when you register from a function (the snippet's install_problem_handlers(app)).
Common misunderstanding: "Each exception class needs its own handler." Handlers match by class along the MRO, so one handler for the base class covers every subclass (real, test_handler_lookup_walks_the_mro: FlashSaleSoldOut(OutOfStock) → 409). Second: "A handler is safe code." If a handler raises, the new exception goes to the 500 path (real: a TypeError inside a handler produced a 500 and the log shows "During handling of the above exception, another exception occurred").
Definition: The docs: "You can add custom exception handlers with the same exception utilities from Starlette." A handler is (Request, Exception) -> Response, sync or async. Keys may be exception classes or integer status codes (real: a handler keyed 404 caught the router's 404). FastAPI's build_middleware_stack (0.128.8 source) splits the table: keys 500 and Exception go to ServerErrorMiddleware, every other key to ExceptionMiddleware.
POST /orders {"sku":"GAME-1","qty":1} (real)
1 create_order -> Store.create: UPDATE stock ... WHERE available >= 1 -> rowcount 0
2 raise OutOfStock("GAME-1: 0 left, 1 requested.", sku="GAME-1", requested=1)
3 ExceptionMiddleware: lookup type(exc).__mro__ = OutOfStock, DomainError, Exception, ...
4 DomainError -> domain_error_handler -> DOMAIN_STATUS[OutOfStock] = (409, "out-of-stock", "Not enough stock")
5 409 application/problem+json {"type":".../out-of-stock","title":"Not enough stock","status":409, ...,"sku":"GAME-1","requested":1}
6 response flows back out through RequestIdMiddleware (x-request-id added)Real scenario: domain failures (stock, credit, seat taken); third-party SDK exceptions you want to translate (a payment SDK's CardDeclined → 402/422); a library raising ValueError deep inside that you never want to leak as 500 for known inputs; one handler per bounded context in a modular monolith.
| Registration | Effect |
|---|---|
@app.exception_handler(MyError) | Decorator form, at import time |
app.add_exception_handler(MyError, fn) | Same table, callable from a setup function |
FastAPI(exception_handlers={MyError: fn}) | Same table, at construction |
Key 404 (an int) | Matches HTTPExceptions with that status |
Key Exception or 500 | Moves the handler to ServerErrorMiddleware (the 500 path) |
APIRouter | Has no exception_handler; handlers are app-wide |
Fix / how to use it: a small exception hierarchy per domain; one handler per base class; register them in one function called by the app factory; test one subclass per mapping entry.
The handler for Exception: ServerErrorMiddleware, re-raise and 500 Internal Server Error Must-know
In plain words: Anything no other handler catches becomes a 500. With a handler registered for Exception, you choose the 500 body; without one, the client gets Internal Server Error as plain text. Either way, the exception is re-raised afterwards, so the server logs it and tests can see it.
Common misunderstanding: "My 500 handler swallowed the exception." It did not: ServerErrorMiddleware ends with raise exc (Starlette 0.49.3 source, saved). Real: TestClient(app) raised RuntimeError: database password is hunter2 after the handler built its response, and Uvicorn logged ERROR: Exception in ASGI application with the traceback. Second: "Middleware will add my headers to the 500." ServerErrorMiddleware is outside every user middleware and sends the 500 with the original send; real: a header added by @app.middleware("http") was missing on the 500 (runs/probe1-output.txt), so the snippet's 500 handler sets X-Request-ID itself.
Definition: Starlette: "Errors are any other exception that occurs within the application. These cases should bubble through the entire middleware stack as exceptions." "In practical terms, the error handled used is exception_handler[500] or exception_handler[Exception]." ServerErrorMiddleware "Ensures that application exceptions may return a custom 500 page, or display an application traceback in DEBUG mode. This is always the outermost middleware layer." If the response has already started (a stream), it cannot send a 500 and only re-raises.
GET /boom X-Request-ID: lab-500 (real, Uvicorn 0.39.0 + curl)
1 route boom(): raise RuntimeError("database password is hunter2")
2 ExceptionMiddleware: no handler for RuntimeError -> re-raise
3 RequestIdMiddleware: sees the exception pass (cannot touch the response)
4 ServerErrorMiddleware: handler = unhandled_handler -> log.exception(...) -> Problem 500 + X-Request-ID
5 send 500 via the outer send; then `raise exc`
6 Uvicorn: INFO "GET /boom HTTP/1.1" 500 Internal Server Error
7 Uvicorn: ERROR Exception in ASGI application + traceback
client: {"type":"about:blank","title":"Internal Server Error","status":500,"instance":"/boom","request_id":"lab-500",
"detail":"Unexpected error. Quote the request id."}Real scenario: a support ticket quoting a request id that the on-call engineer greps in the logs; error tracking (Sentry, OpenTelemetry) installed as an outer layer that relies on the re-raise; a test suite that wants the real exception (raise_server_exceptions=True, the default) and another that wants to assert the 500 body (False).
| Setup | Client gets | Logged by |
|---|---|---|
No handler, debug=False | 500 Internal Server Error (text/plain) | Uvicorn (re-raise) |
Handler for Exception | Your body (snippet: generic Problem + request_id) | Your handler and Uvicorn |
debug=True | Traceback (HTML for browsers, text otherwise) | Uvicorn |
| Exception after the first streamed byte | Truncated body, status already 200 | Uvicorn |
TestClient(app) | The exception is raised in the test | — |
TestClient(app, raise_server_exceptions=False) | The 500 response | — |
Fix / how to use it: register one handler for Exception that logs with logger.exception and the request id and returns a generic body; never put str(exc) in it; set any header you need there.
Debug mode Important
In plain words: FastAPI(debug=True) replaces the 500 with the full traceback. Fine on a laptop, a data leak anywhere else.
Common misunderstanding: "Debug only shows the stack, not data." The traceback includes the exception message and the source lines around each frame. Real (test_debug_true_sends_the_traceback_to_the_client): the body contained Traceback and hunter2, the secret in the exception message. Second: "My Exception handler still runs in debug." Starlette: "If debug is enabled and an error occurs, then instead of using the installed 500 handler, Starlette will respond with a traceback response."
Definition: debug is passed to both ServerErrorMiddleware and ExceptionMiddleware. ServerErrorMiddleware.debug_response returns an HTML page when the request's Accept contains text/html, otherwise plain text (real: text/plain for no Accept, text/html with <title> for Accept: text/html).
FastAPI(debug=True), GET /boom (real)
1 no Accept header -> 500 text/plain "Traceback (most recent call last): ... hunter2"
2 Accept: text/html -> 500 text/html HTML page with frames and source lines
3 installed 500 handler -> not calledReal scenario: a staging environment accidentally deployed with debug=True; a DEBUG environment variable read with bool(os.getenv("DEBUG")), which is True for the string "false"; the Laravel equivalent, APP_DEBUG, of which the Laravel docs say "In your production environment, the value of APP_DEBUG should always be false."
| Environment | debug | Errors seen by the client |
|---|---|---|
| Local | True acceptable | Traceback |
| CI tests | False; use raise_server_exceptions=True | The exception in pytest |
| Staging / production | False, always | Generic Problem + request id |
Fix / how to use it: read debug from typed settings (Pydantic BaseSettings, see APIRouter & Project Structure), default False, and assert in a test that the production settings have it off.
RequestValidationError override Important
In plain words: When the request does not match the signature, FastAPI raises RequestValidationError and its default handler answers 422 with a detail list. Register your own handler for RequestValidationError to change the body (the snippet returns a Problem with an errors extension).
Common misunderstanding: "Overriding it means I also handle response validation." RequestValidationError is for input; a returned value that fails the response model raises ResponseValidationError, which is a server bug and goes to the 500 path (real: Internal Server Error, and TestClient(app) raises fastapi.exceptions.ResponseValidationError; runs/probe2-output.txt). Second: "Return exc.errors() as is." Each error carries input; the docs warn that converting the exception to a string "could be leaking a bit of information about your system". The snippet drops input (real: a request with "password":"secret" returned no secret and no input key).
Definition: "When a request contains invalid data, FastAPI internally raises a RequestValidationError. And it also includes a default exception handler for it." exc.errors() is a list of dicts with type, loc, msg, input, ctx; exc.body is the received body.
POST /orders {"sku":"","qty":99,"password":"secret"} (real)
1 Pydantic: string_too_short at body.sku, less_than_equal at body.qty (extra "password" ignored by the model)
2 raise RequestValidationError(errors)
3 validation_handler -> {"loc", "code", "detail"} per error, no input
4 422 application/problem+json "type": ".../validation", "errors": [...2 entries...]Real scenario: an API standardised on RFC 9457 across services; a mobile client that maps loc to form fields; a log line per validation failure that must never contain the submitted password.
| Concern | Where it is covered |
|---|---|
Default 422 body (type, loc, msg, input, ctx) | Request Validation |
| RFC 9457 validation body with JSON Pointers | Request Validation |
ResponseValidationError (your output is wrong) | 500 path on this page |
Not leaking input | both pages |
Fix / how to use it: one validation handler in the shared problems module, consistent with the house format; full detail and the pointer format live in the validation chapter.
Problem Details (RFC 9457) as the house format Must-know
In plain words: Pick one JSON shape for every error and send it as application/problem+json: type (a URI naming the kind of problem), title, status, detail (this occurrence), instance (where), plus your own extension members. The snippet adds request_id and safe context like sku.
Common misunderstanding: "detail is where the debugging information goes." RFC 9457: "The "detail" string, if present, ought to focus on helping the client correct the problem, rather than giving debugging information. Consumers SHOULD NOT parse the "detail" member for information; extensions are more suitable and less error-prone ways to obtain such information." Second: "Problem Details replaces status codes." status in the body is advisory; the HTTP status line is what caches, proxies and clients act on.
Definition: RFC 9457 (July 2023, "This document obsoletes RFC 7807") defines the members and the application/problem+json media type; a missing type means about:blank. The validation chapter's Problem Details section has the member table and the 422 format; this page applies the same envelope to 404/409/503/500.
the snippet's envelope (real bodies)
1 404 {"type":"https://shop.example/problems/order-not-found","title":"Order not found","status":404,
"instance":"/orders/99","request_id":"...","detail":"Order 99 does not exist.","order_id":99}
2 405 {"type":"about:blank","title":"Method Not Allowed","status":405,"instance":"/orders/1",...}
3 500 {"type":"about:blank","title":"Internal Server Error","status":500,...,"detail":"Unexpected error. Quote the request id."}Real scenario: a gateway that renders all upstream errors uniformly; a TypeScript client with one error type; a Go and a Python service that must produce the same errors (both are in this knowledge base).
| Member | Source in the snippet |
|---|---|
type | TYPE_BASE + slug from DOMAIN_STATUS, or about:blank |
title | Mapping table, or HTTPStatus(code).phrase |
status | The response status |
detail | exc.detail (written for the client) |
instance | request.url.path |
request_id (extension) | The request's ContextVar |
| Context (extension) | exc.context (sku, requested, order_id, state) |
Fix / how to use it: one problem() helper, used by every handler; stable, documented type URIs; never put stack traces, SQL or input values in any member.
Domain error mapping: OrderNotFound → 404 Not Found, OutOfStock → 409 Conflict Must-know
In plain words: Services speak the language of the business (OrderNotFound, OutOfStock, DuplicateOrder); one table in the HTTP layer says which status, type and title each one becomes. The service never imports FastAPI, so it can be used by a CLI, a worker or a test without HTTP.
Common misunderstanding: "Out of stock is a 400 or a 422." The request is well-formed; the state of the resource refuses it. RFC 9110: "The 409 (Conflict) status code indicates that the request could not be completed due to a conflict with the current state of the target resource." Second: "Translate database errors in the handler." The store should translate them, close to the SQL that knows what a UNIQUE violation means (IntegrityError → DuplicateOrder); a raw sqlite3.IntegrityError or SQLAlchemy IntegrityError reaching the handler is a 500.
Definition: a dictionary from exception class to (status, type slug, title), consulted by walking the exception's MRO; an unmapped DomainError is treated as a bug (500, logged). RFC 9110 on 404: "the origin server did not find a current representation for the target resource or is not willing to disclose that one exists". The SQL that produces each outcome:
-- app/db.py: the schema and the statements whose outcomes become domain errors
CREATE TABLE stock (sku TEXT PRIMARY KEY, available INTEGER NOT NULL CHECK (available >= 0));
CREATE TABLE orders (id INTEGER PRIMARY KEY, sku TEXT NOT NULL REFERENCES stock (sku),
qty INTEGER NOT NULL CHECK (qty > 0),
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'shipped', 'cancelled')),
note TEXT, idempotency_key TEXT UNIQUE);
-- OutOfStock (409): the conditional update touches 0 rows
UPDATE stock SET available = available - :qty WHERE sku = :sku AND available >= :qty;
-- DuplicateOrder (409): UNIQUE (idempotency_key) violation -> IntegrityError, the transaction rolls back
INSERT INTO orders (sku, qty, note, idempotency_key) VALUES (:sku, :qty, :note, :key);
-- OrderNotFound (404): no row
SELECT id, sku, qty, status, note FROM orders WHERE id = :id;
-- OrderNotCancellable (409): 0 rows because status is not 'open'
UPDATE orders SET status = 'cancelled' WHERE id = :id AND status = 'open'; POST /orders twice with Idempotency-Key: k-1 (real)
1 #1 UPDATE stock ... 5 -> 3; INSERT ... key k-1 -> id 2; COMMIT 201 location: /orders/2
2 #2 UPDATE stock ... 3 -> 0; INSERT ... key k-1 -> IntegrityError
3 with-block rolls back both statements; raise DuplicateOrder(...) from exc
4 409 {"type":".../duplicate-order","title":"Duplicate order", ...}
5 #3 qty 3 without a key -> 201 (stock was 3 again: the reservation in #2 was rolled back)Real scenario: a checkout that must say "sold out" (409) differently from "no such product" (404); an idempotent retry from a mobile client that must not double-charge; a cancel button on a shipped order; a dependency outage that should tell clients to retry (503 + Retry-After).
| Domain error | Raised when | Status | type slug | Extra |
|---|---|---|---|---|
OrderNotFound | SELECT returned no row | 404 | order-not-found | order_id |
OutOfStock | conditional UPDATE hit 0 rows | 409 | out-of-stock | sku, requested |
DuplicateOrder | UNIQUE violation | 409 | duplicate-order | — |
OrderNotCancellable | state is not open | 409 | order-not-cancellable | order_id, state |
PaymentProviderDown | upstream timeout | 503 | payment-provider-down | Retry-After header |
unmapped DomainError | mapping forgotten | 500 | unmapped-domain-error | logged as an error |
| ORM | "No row" | "Constraint violated" | Map to |
|---|---|---|---|
sqlite3 (snippet) | fetchone() is None | sqlite3.IntegrityError | OrderNotFound / DuplicateOrder |
| SQLAlchemy 2 | session.get() returns None; a required result raises NoResultFound ("A database result was required but none was found.") | sqlalchemy.exc.IntegrityError ("Wraps a DB-API IntegrityError") | same |
| SQLModel | session.get(Hero, id) is None (the SQLModel tutorial then raises HTTPException(404)) | SQLAlchemy's IntegrityError | same; prefer a domain error over HTTPException in services |
| Alembic | adds the UNIQUE constraint the mapping relies on (op.create_unique_constraint) | — | — |
Fix / how to use it: the DOMAIN_STATUS table in app/problems.py, one test per row, and raise ... from exc when translating so the original error stays in the traceback. The SQLAlchemy session and transaction patterns are in SQLAlchemy 2 & SQLModel.
Logging exceptions with request ids Must-know
In plain words: Give every request an id (take the caller's X-Request-ID if it is sane, else generate one), put it on every log line and in every error body and response header. A user quotes the id; you grep one line and find the traceback.
Common misunderstanding: "Log in every handler and every except." Log an unexpected exception once, with the traceback, at the edge (the 500 handler). Expected domain errors are INFO, not ERROR. Second: "A middleware can add the id to the 500." Not to the response (see the 500 path), but a ContextVar set by the middleware is still readable in the 500 handler (real: the log record and body carried req-123).
Definition: logging.Logger.exception(msg) "Logs a message with level ERROR on this logger … Exception info is added to the logging message. This method should only be called from an exception handler." A logging.Filter on the shop logger copies request_id_var.get() onto every record as %(request_id)s. The middleware is a pure ASGI class, not @app.middleware("http") (BaseHTTPMiddleware), so it does not wrap streaming bodies in an extra task.
GET /boom X-Request-ID: req-123 (real, caplog)
1 RequestIdMiddleware: request_id_var.set("req-123")
2 route raises RuntimeError
3 unhandled_handler: log.exception("unhandled RuntimeError on GET /boom") -> record.request_id == "req-123", exc_info set
4 log line: ERROR [req-123] shop: unhandled RuntimeError on GET /boom + traceback
5 response: 500, x-request-id: req-123, body request_id: "req-123"Real scenario: a customer support flow ("error reference: 4d48dd5a…"); correlating a FastAPI request with the payment service's logs by forwarding X-Request-ID; an OpenTelemetry trace id used as the request id.
| Level | Example | Traceback? |
|---|---|---|
INFO | domain error OutOfStock -> 409 | No |
WARNING | Upstream retry succeeded on the 2nd attempt | No |
ERROR + exc_info | unhandled RuntimeError on GET /boom | Yes, once |
Uvicorn ERROR | Exception in ASGI application (from the re-raise) | Yes |
Fix / how to use it: the snippet's observability.py puts the request id in error logs, headers and bodies; cap and validate incoming ids (the snippet accepts 1–64 characters); forward the id on outbound calls; structured (JSON) logs and log shipping are in FastAPI in Production.
The responses parameter and the error response model Important
In plain words: Handlers change what the client receives, but /docs does not know. Tell OpenAPI with responses={404: {"model": Problem, ...}} on each decorator, so generated clients get typed errors.
Common misunderstanding: "responses= changes the response." It only documents; "for those additional responses you have to make sure you return a Response like JSONResponse directly, with your status code and content" (or raise and let a handler do it). Second: the documented media type: with only model, FastAPI puts the schema under application/json; the snippet adds an explicit application/problem+json entry (real, test_openapi_documents_error_models). The validation chapter's responses section shows the full OpenAPI output.
Definition: "You can pass to your path operation decorators a parameter responses … Each of those response dicts can have a key model, containing a Pydantic model, just like response_model." The key model "is not part of OpenAPI"; FastAPI turns it into a $ref under components.schemas.
GET /orders/{order_id} in /openapi.json (real)
1 "200": OrderOut
2 "404": {"description": "Not found", "content": {"application/json": Problem, "application/problem+json": Problem}}
3 "422": FastAPI's HTTPValidationError (added automatically because the route has parameters)Real scenario: an SDK generator that emits OrderNotFoundError; a contract test that fails when an error shape changes; an API portal listing every error per operation.
| Pattern | Code |
|---|---|
| One status | responses={404: PROBLEM_RESPONSES[404]} |
| Several | responses={404: ..., 409: ...} |
| Router-wide | APIRouter(responses={...}) |
| With headers | add "headers": {"Retry-After": {...}} |
| Hide from docs | include_in_schema=False (the snippet's /boom, /health) |
Fix / how to use it: a module-level PROBLEM_RESPONSES dict, used on every route that can produce those statuses; diff /openapi.json in CI.
response_model vs return type annotation Must-know
In plain words: FastAPI validates and filters what you return against a model. You can name the model in the decorator (response_model=OrderOut) or as the function's return type annotation (-> OrderOut). Both document the response and strip fields the model does not declare.
Common misunderstanding: "The annotation is only for my editor." FastAPI reads it and uses it as the response model. Second: "If both are present, the annotation wins." The docs: "If you declare both a return type and a response_model, the response_model will take priority and be used by FastAPI." Use response_model when the function returns something else (a dict, an ORM row with extra attributes) and the annotation when the function really returns the model.
Definition: The return value is validated against the model and serialised through it; fields not declared are dropped. Real: get_order returns a dict containing internal_cost_cents, which the client never receives (test_response_model_filters_and_excludes_none). The docs: "if you want the maximum performance, use a Response Model and don't declare a response_class in the path operation decorator", because the model path serialises directly (in Rust since 0.130.0) instead of jsonable_encoder + json.dumps.
GET /orders/1 (real)
1 get_order -> {"id":1,"sku":"BOOK-1","qty":1,"status":"shipped","note":None,"internal_cost_cents":412}
2 response_model=OrderOut: validate, drop internal_cost_cents
3 response_model_exclude_none=True: drop note (None)
4 200 {"id":1,"sku":"BOOK-1","qty":1,"status":"shipped"}Real scenario: an ORM row with a password hash that must not leak; an internal cost field; a list endpoint that returns list[OrderOut]; a route that sometimes returns a RedirectResponse: -> Response or a Response subclass is handled automatically, but a union with a non-Pydantic type (the docs' -> Response | dict) fails at startup, and the docs' fix is response_model=None.
| Declaration | Validates output | Filters | Documents | Editor checks the return |
|---|---|---|---|---|
-> OrderOut | Yes | Yes | Yes | Yes |
response_model=OrderOut, returns a dict | Yes | Yes | Yes | No |
| Both | response_model wins | Yes | Yes | Partly |
response_model=None | No | No | No | Up to you |
Returns a Response | No | No | Only via response_class | — |
Fix / how to use it: annotate with the model when you return the model (the snippet's create_order); use response_model when you return raw rows (the snippet's get_order); keep the output model separate from the input model. Model design in depth: Typing & Pydantic v2.
response_model_exclude_unset and response_model_exclude_none Important
In plain words: Two decorator flags that leave fields out. response_model_exclude_unset=True drops every field that was never explicitly set (defaults stay out); response_model_exclude_none=True drops every field whose value is None.
Common misunderstanding: "They are the same." Real: Preferences(language="fa") with exclude_unset sent {"language":"fa"}, leaving out newsletter=False and timezone=None (defaults); exclude_none on GET /orders/1 dropped only note (null). Second: "Omitting a field is harmless." A client that treats "missing" differently from false or null changes behaviour; document it.
Definition: The flags are passed to Pydantic's serialisation ("as described in the Pydantic docs for exclude_defaults and exclude_none"); response_model_exclude_defaults also exists.
model Preferences(language="en", newsletter=False, timezone=None) (real)
1 stored {"language": "fa"} exclude_unset -> {"language":"fa"}
2 stored {} exclude_unset -> {}
3 Order with note=None exclude_none -> no "note" keyReal scenario: a settings endpoint that returns only what the user changed; a sparse PATCH response; a large list where nulls double the payload.
| Flag | Drops | Keeps |
|---|---|---|
response_model_exclude_unset | Fields never set | Set fields, even None |
response_model_exclude_none | Fields that are None | Defaults that are not None |
response_model_exclude_defaults | Fields equal to their default | Changed fields |
response_model_include / _exclude | Named fields | — (prefer a separate model) |
Fix / how to use it: prefer an explicit output model; use the flags for sparse documents and settings; test the exact JSON.
Response classes: response_class, JSONResponse, ORJSONResponse, PlainTextResponse, HTMLResponse, RedirectResponse Must-know
In plain words: A response class decides the Content-Type and how the body becomes bytes. Put it in the decorator (response_class=HTMLResponse) and return the content, or return an instance.
Common misunderstanding: "ORJSONResponse is the fast choice." It was. FastAPI 0.131.0 deprecated it; the reference now says "FastAPI now serializes data directly to JSON bytes via Pydantic when a return type or response model is set, which is faster and doesn't need a custom response class." On the pin (0.128.8) it is not yet deprecated (real: no warning). Note also that orjson's current README lists CPython 3.10+; 3.11.5 is the last release that installs on 3.9. Second: "RedirectResponse is a 302." Its default is 307 ("Uses a 307 status code by default").
Definition: "The main Response class, all the other responses inherit from it." Starlette "will automatically include a Content-Length header. It will also include a Content-Type header, based on the media_type and appending a charset for text types." response_class also tells OpenAPI the media type (real: /welcome is documented as text/html).
same data, different classes (real)
1 GET /welcome (HTMLResponse) content-type: text/html; charset=utf-8
2 GET /health (PlainTextResponse) "ok"
3 GET /fast/orders/1 (ORJSONResponse) application/json, {"id":1,...,"note":null} (no response_model filtering)
4 GET /legacy/orders/1 (RedirectResponse, 308) location: /orders/1, content-length: 0Real scenario: a health check for a load balancer (PlainTextResponse); an OAuth callback that redirects (303 after POST, 307/308 to keep the method); an email preview (HTMLResponse); a legacy URL kept alive with 308.
| Class | Default status | Typical code |
|---|---|---|
JSONResponse | 200 | JSONResponse(body, status_code=409, media_type="application/problem+json") |
ORJSONResponse | 200 | Deprecated (0.131.0); prefer a response model |
PlainTextResponse | 200 | response_class=PlainTextResponse + return "ok" |
HTMLResponse | 200 | response_class=HTMLResponse |
RedirectResponse | 307 | RedirectResponse(url, status_code=308) |
| Custom subclass | — | override render() (the docs' CustomORJSONResponse with OPT_INDENT_2) |
default_response_class= | — | on FastAPI() or APIRouter() for all routes |
Fix / how to use it: no response_class for JSON APIs (response model path); response_class= for other media types so the docs are right; 308 for permanent moves of non-GET endpoints.
Returning a Response directly Important
In plain words: If your function returns a Response (or any subclass), FastAPI sends it exactly as built: no model, no conversion, no exception handler.
Common misunderstanding: "Returning JSONResponse(..., status_code=404) is the same as raising." Real (test_returning_a_response_bypasses_handlers): the body was {"detail":"hand-made"} as application/json, not the house Problem, because no handler ran. Second: "The docs will show it." The docs: "A Response returned directly by your path operation function won't be documented in OpenAPI."
Definition: "if you return a Response directly (or any subclass, like JSONResponse), the data won't be automatically converted (even if you declare a response_model)". Use response_class= and return an instance to both control the bytes and document the media type.
1 return {"id": 1} -> response model -> JSON (documented)
2 return JSONResponse({...}, 404) -> sent as is (handlers skipped, not documented)
3 raise OrderNotFound(...) -> handler -> Problem (documented via responses=)Real scenario: a 304 or 204 you build by hand; bytes you already have (a cached JSON blob); a route that must set an unusual status per call.
| Want | Prefer |
|---|---|
| A different status for errors | Raise; let the handler build it |
| A different success status per call | response.status_code = ... on the injected Response |
| Pre-built bytes | Return Response(content, media_type=...) |
| Media type in docs | response_class= |
Fix / how to use it: return responses for success cases that are not JSON models; raise for failures so they share the format.
Response headers and Set-Cookie on Response Must-know
In plain words: Declare a response: Response parameter, set response.headers[...] or call response.set_cookie(...), and still return your normal value; FastAPI copies the headers and cookies onto the final response.
Common misunderstanding: "Setting headers means building the response myself." The injected "temporary response object" (the docs' words) exists exactly so you do not have to. Second: "Cookies default to secure." Starlette's set_cookie defaults are secure=False, httponly=False, samesite="lax"; set them explicitly (real: session=opaque-token; HttpOnly; Max-Age=3600; Path=/; SameSite=lax; Secure).
Definition: Response.set_cookie(key, value, max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite="lax", partitioned=False); partitioned is "Only available for Python 3.14+". delete_cookie expires one. When you return a Response yourself, set headers on that object instead. Cookie attributes and security are in Request Validation.
POST /session (real)
1 login(response): response.set_cookie("session", "opaque-token", httponly=True, secure=True, samesite="lax", max_age=3600)
2 return {"status": "signed in"}
3 final JSONResponse + set-cookie header merged from the temporal ResponseReal scenario: Location on 201; Set-Cookie after login; Cache-Control on a cacheable read; ETag; Deprecation/Sunset on an old endpoint; X-Request-ID on every response (middleware).
| Header | Where to set it in FastAPI |
|---|---|
Location | Injected Response in the create route |
Set-Cookie | response.set_cookie(...) |
Cache-Control, ETag | Route (per resource) or StaticFiles subclass |
WWW-Authenticate, Retry-After | HTTPException(headers=...) or the handler |
X-Request-ID | Middleware (+ the 500 handler) |
Content-Disposition | FileResponse(filename=...) or StreamingResponse(headers=...) |
Fix / how to use it: headers that depend on the request belong in the route; headers for every response in middleware; headers on errors in the exception or handler.
Status codes that carry meaning: 201 Created + Location header, 204 No Content, 304 Not Modified, ETag preview Must-know
In plain words: 201 says "I created it, and the Location header tells you where"; 204 says "done, nothing to send"; 304 says "your cached copy is still good" in answer to a conditional request with If-None-Match.
Common misunderstanding: "204 means empty JSON." It means no content. Real: FastAPI sent no body and no Content-Length but, on 0.128.8, a stray content-type: application/json header (asserted in test_204_has_no_body; returning a dict from a 204 route is silently dropped, runs/probe1-output.txt). Second: "304 is a redirect." It is a validation answer; RFC 9110: "there is no need for the server to transfer a representation of the target resource because the request indicates that the client … already has a valid representation".
Definition: RFC 9110: 201 "the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location header field is received, by the target URI." 204: "there is no additional content to send in the response content". A server generating 304 "MUST generate any of the following header fields that would have been sent in a 200 (OK) response", which include ETag and Cache-Control. The full conditional-request story (weak vs strong validators, If-Match for optimistic locking) belongs to REST API Design and Background Tasks, Caching & External APIs.
receipt route, ETag preview (real)
1 GET /orders/1/receipt 200 etag: "2ef6a3a9edad2da5" cache-control: private, no-cache
2 GET /orders/1/receipt If-None-Match: "2ef6a3a9edad2da5" 304, no body, same etag
3 order changes -> body bytes change -> new etag -> next conditional GET is a 200Real scenario: POST /orders → 201 with Location: /orders/2; DELETE /orders/2 → 204; a mobile app polling an order every 30 s that mostly gets 304s; PUT with If-Match to stop lost updates.
| Status | Body | Required headers | FastAPI |
|---|---|---|---|
| 200 OK | Yes | — | default |
| 201 Created | Usually the resource | Location (recommended) | status_code=201 + response.headers["Location"] |
| 202 Accepted | Status resource | Location of the job | status_code=202 |
| 204 No Content | None | — | status_code=204, return None |
| 304 Not Modified | None | ETag/Cache-Control as on the 200 | return Response(status_code=304, headers=...) |
| 409 Conflict | Problem | — | domain error mapping |
Fix / how to use it: status_code= on the decorator for the success code; Location on every 201; Response(status_code=304) with the same validators; ETag from a hash of the bytes or a row version.
FileResponse: downloads, Range requests, uploads preview Important
In plain words: FileResponse(path, filename="invoice-1.pdf") streams a file from disk asynchronously, with Content-Length, Last-Modified, ETag, Accept-Ranges: bytes, and Content-Disposition: attachment when you give a filename. A Range header gets a 206.
Common misunderstanding: "Read the file and return the bytes." That loads it all into memory and loses the validators and range support. Second: "Downloads need StreamingResponse." For files on disk, FileResponse is the right class; StreamingResponse is for bodies generated on the fly.
Definition: Starlette: "Asynchronously streams a file as the response." "File responses will include appropriate Content-Length, Last-Modified and ETag headers." "If the request includes a Range header, and the file exists, the response will be a 206 Partial Content response with the requested range of bytes. If the range is invalid, the response will be a 416 Range Not Satisfiable response." content_disposition_type is "attachment" (default) or "inline".
GET /invoices/1.pdf Range: bytes=0-7 (real, Uvicorn + curl)
1 206 Partial Content content-type: application/pdf accept-ranges: bytes
2 content-disposition: attachment; filename="invoice-1.pdf" content-range: bytes 0-7/193 content-length: 8
3 body: %PDF-1.4Real scenario: invoice and report downloads behind auth; resumable downloads of large exports; video seeking (range requests); uploads (UploadFile, spooled to disk by Starlette) that you validate and then hand to object storage. Upload parsing is in Request Validation; presigned URLs and CDN delivery are in File Uploads, S3 & CDN.
| Need | Use |
|---|---|
| A file on local disk | FileResponse(path, filename=...) |
| Show in the browser | content_disposition_type="inline" |
| A generated file (CSV, ZIP on the fly) | StreamingResponse + Content-Disposition |
| A file in S3 | Redirect (307) to a presigned URL; do not proxy the bytes |
| Upload | UploadFile → validate size/type → object storage |
Fix / how to use it: authorise first (the snippet raises OrderNotFound before building the response), then FileResponse; never build the path from user input without normalising it.
StreamingResponse: generator, async generator, chunked transfer encoding Must-know
In plain words: StreamingResponse(gen(), media_type="text/csv") sends the status and headers at once, then one chunk per yield. The total length is unknown, so HTTP/1.1 frames the body with chunked transfer encoding; the client starts reading before you finish writing.
Common misunderstanding: "Wrapping a list in iter() makes it streaming." The Before app built all 10 000 rows first and only then "streamed" them: same memory, same wait. Stream only if you produce lazily. Second: "Async generators are always better." A sync generator is iterated in the thread pool (iterate_in_threadpool, Starlette source), which is the right place for blocking reads (a file, a sync DB cursor); an async generator runs on the event loop and must only await non-blocking calls.
Definition: Starlette: "Takes an async generator or a normal generator/iterator and streams the response body." "Have in mind that file-like objects (like those created by open()) are normal iterators." RFC 9112 7.1: "Chunked enables content streams of unknown size to be transferred as a sequence of length-delimited buffers". On HTTP/2 and HTTP/3 the same stream is carried in DATA frames, and Transfer-Encoding is not used (see HTTP Evolution). On FastAPI 0.134.0+ you can also write response_class=StreamingResponse with yield directly in the path operation; the docs recommend that style because "it's much more convenient and handles cancellation behind the scenes for you".
GET /stream/ticks?n=3 (real, Uvicorn 0.39.0 + curl -si)
1 StreamingResponse.__call__: task group { stream_response(send), listen_for_disconnect(receive) }
2 send http.response.start 200 content-type: text/plain; charset=utf-8 (no content-length)
3 Uvicorn adds: transfer-encoding: chunked
4 yield b"tick 0\n" -> send body chunk (more_body=True) -> "7\r\ntick 0\n\r\n" on the wire
5 ... tick 1, tick 2
6 send body b"" (more_body=False) -> "0\r\n\r\n"; task group cancels the disconnect listenerReal scenario: a CSV export of a million orders; proxying a large upstream response without buffering it; JSON Lines (application/jsonl) for log tails; generated ZIPs; the body of every SSE endpoint.
| Producer | Runs on | Use for | Blocking calls inside? |
|---|---|---|---|
Sync generator (def gen(): yield) | Thread pool, one item at a time | File reads, sync DB cursors, CSV writer | Allowed |
Async generator (async def gen(): yield) | Event loop | httpx.AsyncClient.stream, async DB drivers, LLM SDK streams | Never |
File object (open(...)) | Thread pool | Prefer FileResponse | Allowed |
yield in the path operation (0.134.0+) | as above | Same, with FastAPI handling cancellation | as above |
StreamingResponse subclass with media_type | — | Fixed Content-Type (the docs' PNGStreamingResponse) | — |
Fix / how to use it: a generator that produces chunks of a sensible size (the snippet's CSV export flushes about 8 KiB at a time instead of one write per row); always set media_type; set Content-Disposition for downloads.
Back-pressure Must-know
In plain words: If the client reads slower than you produce, your generator simply waits. Each yield is followed by await send(...), and that await does not return while the socket's buffers are full. Memory stays bounded by the buffers, not by the size of the export.
Common misunderstanding: "A slow client makes the server buffer the whole response." Not with a generator: real (test_back_pressure_pauses_the_producer, macOS loopback, 16 KiB receive buffer): a client that read nothing for 0.5 s let the producer get only 18 of 512 64 KiB chunks ahead (1152 KiB), then the rest flowed as it read; three runs printed the same 18. Second: "So back-pressure is automatic everywhere." It breaks the moment you decouple producer and sender: a background task that pushes into an unbounded asyncio.Queue, or a list built before the first yield.
Definition: Uvicorn's HTTP protocol implements asyncio's flow-control callbacks: when the transport's write buffer passes its high-water mark, asyncio calls pause_writing(), Uvicorn sets write_paused, and its send does await self.flow.drain() until resume_writing() (Uvicorn 0.39.0 flow_control.py and httptools_impl.py, saved). With a bounded channel between tasks (anyio.create_memory_object_stream(10), as in the sse-starlette README), the producer blocks when the buffer is full, which keeps the property.
slow reader, /stream/big?chunks=512&size=65536 (real)
1 gen yields chunk 1..n; each send() writes into the transport buffer
2 kernel send/receive buffers fill (client reads nothing)
3 asyncio -> pause_writing(); next send(): await flow.drain() <- generator suspended at its yield (chunk 18)
4 0.5 s later the client starts reading; buffers empty; resume_writing() -> drain() returns
5 generator continues; all 32 MiB delivered; peak memory ~ buffers, not 32 MiBReal scenario: a mobile client on a slow network downloading a large export; an SSE consumer that stalls; a proxy that reads slowly; many slow consumers at once (each holds a connection and a suspended generator, which is cheap in memory but counts toward Uvicorn's --limit-concurrency).
| Design | Bounded memory? | Why |
|---|---|---|
| Generator yields as it reads | Yes | Producer blocked by await send |
| Bounded memory channel (size 10) | Yes | Producer blocks on a full channel |
Unbounded asyncio.Queue filled by a task | No | Producer never waits |
| Build list, then stream it | No | All in memory before the first byte |
| Read whole upstream, then return | No | Same |
Fix / how to use it: keep production inside the generator, or use a bounded channel; measure with a slow client as in the Lab; per-connection timeouts and concurrency limits are server settings (FastAPI in Production).
Client disconnect and request.is_disconnected Must-know
In plain words: When the client goes away, Starlette cancels your stream: the generator gets CancelledError at its next await, its finally: runs, and nothing more is sent. Between chunks you can also ask await request.is_disconnected() and stop politely.
Common misunderstanding: "The server notices a disconnect immediately and stops my work." Only at an await. The docs: "An async task can only be cancelled when it reaches an await. If there is no await, the generator (function with yield) can not be cancelled properly and may keep running even after cancellation is requested." A CPU loop or a blocking call keeps running. Second: "is_disconnected() is all I need." It is a check you must call; cancellation is what actually stops a generator that is waiting on upstream I/O.
Definition: Starlette's StreamingResponse.__call__ runs stream_response and listen_for_disconnect in one task group when the server's ASGI spec_version is below 2.4 (Uvicorn 0.39.0 sends "spec_version": "2.3"); listen_for_disconnect waits for http.disconnect and cancels the group. Starlette's requests docs: "In some cases such as long-polling, or streaming responses you might need to determine if the client has dropped the connection. You can determine this state with disconnected = await request.is_disconnected()."
curl -sN --max-time 0.2 "/stream/ticks?n=10000&delay=0.01" (real)
1 curl prints tick 0 .. tick 17, then closes the socket at 0.2 s
2 Uvicorn: connection_lost -> receive() returns {"type": "http.disconnect"}
3 listen_for_disconnect returns -> task group cancelled
4 generator: CancelledError at `await asyncio.sleep(delay)` -> except: log; finally: cleanup
5 log: INFO [7e8503…] shop: ticks cancelled after 18 chunks (client disconnected)
test_live.py: STREAM_EVENTS == ["ticks: cancelled after 3", "ticks: cleanup"]Real scenario: a user closes the tab during a 2-minute report; an LLM stream whose tokens cost money after the reader left; a long-poll endpoint; an SSE feed whose consumer moved to another page.
| Situation | What stops the work |
|---|---|
Generator awaiting I/O (await upstream, await sleep) | Cancellation (CancelledError), finally: runs |
| Generator between chunks | await request.is_disconnected() check |
CPU loop with no await | Nothing; add await anyio.sleep(0) or move it to a worker |
| Sync generator in the thread pool | Stops being iterated; the thread finishes its current item |
Work started in BackgroundTasks | Keeps running (runs after the response, see below) |
Fix / how to use it: an await on every iteration; try/finally around upstream resources (close the HTTP stream, the DB cursor); except CancelledError: ...; raise (never swallow it); log the cancellation at INFO.
Errors in the middle of a stream Important
In plain words: Once the first byte is sent, the status (200) and headers are on the wire. An exception after that cannot become a 404 or 500; the connection is cut and the client sees a truncated body.
Common misunderstanding: "My Exception handler will send a Problem." It cannot: ServerErrorMiddleware sends its response only if not response_started. Real (runs/midstream-error-live.txt): curl printed part 1 and exited with code 18 (partial file); httpx raised RemoteProtocolError: peer closed connection without sending complete message body (incomplete chunked read); Uvicorn logged Exception in ASGI application with an ExceptionGroup from the response's task group.
Definition: Status and headers live in http.response.start; everything after is http.response.body. A chunked body without its terminating 0\r\n\r\n is how HTTP/1.1 says "incomplete". A handled exception raised after the start is no better: Starlette's wrap_app_handling_exceptions raises RuntimeError("Caught handled exception, but response already started.") (0.49.3 source, saved).
generator: yield b"part 1\n"; raise RuntimeError("upstream died") (real)
1 200 + headers sent, chunk "part 1" sent
2 exception -> task group -> ServerErrorMiddleware: response_started is True -> no 500, re-raise
3 Uvicorn closes the connection without the final chunk
4 client: incomplete chunked readReal scenario: an export whose DB connection drops at row 600 000; an LLM provider that errors after 200 tokens; an SSE feed whose upstream broker restarts.
| Protocol | How to signal a late error |
|---|---|
| Plain stream / CSV | Truncation (clients must check completeness: row count, trailer line) |
| JSON Lines | A final {"error": ...} line your clients know |
| SSE | An event: error with a Problem-shaped data: (the snippet's chat stream) |
| Any | Validate everything you can before the first yield (auth, existence, quotas) |
Fix / how to use it: do all checks that can fail with a status before returning the StreamingResponse; inside the generator, catch errors you can describe and emit an in-band error event; let the rest truncate and be logged.
Server-Sent Events: text/event-stream, event id retry, Last-Event-ID Must-know
In plain words: SSE is a one-way stream of text events over a normal HTTP response with Content-Type: text/event-stream. Each event is a few field: value lines followed by a blank line. Browsers read it with EventSource, reconnect automatically, and send the last id they saw in Last-Event-ID.
Common misunderstanding: "SSE needs a special server." It is ordinary chunked HTTP; any StreamingResponse with the right framing and headers is SSE. Second: "Each yield is an event." Only a blank line dispatches an event; the Before app's yield json.dumps(...) produced {"n": 0}{"n": 1}{"n": 2}, which EventSource never dispatches.
Definition: WHATWG HTML 9.2: "This event stream format's MIME type is text/event-stream." Lines: "If the line is empty (a blank line) Dispatch the event"; "If the line starts with a U+003A COLON character (😃 Ignore the line" (a comment); fields event (type), data (appended with a line feed, so multi-line data is several data: lines), id (sets the last event ID), retry ("If the field value consists of only ASCII digits, then interpret the field value as an integer in base ten, and set the event stream's reconnection time to that integer"). On reconnect the browser sets the Last-Event-ID header.
EventSource("/sse/orders") (real framing, snippet)
1 : stream opened comment, ignored
2 retry: 5000 reconnect after 5 s
3 event: order / id: 0 / data: {"id": 1, "status": "paid"} -> "order" event, lastEventId "0"
4 event: order / id: 1 / data: {... "packed"} -> lastEventId "1"
5 -- connection drops --
6 browser waits 5000 ms, GET /sse/orders Last-Event-ID: 1
7 server resumes at seq 2: event: order / id: 2 / data: {... "shipped"} (real: test_last_event_id_resumes)Real scenario: order status updates on a tracking page; notifications; progress of a long job; live logs; AI chat token streams (the docs: "SSE is commonly used for AI chat streaming, live notifications, logs and observability"); protocols like MCP that, in the FastAPI docs' words, "stream SSE over POST".
| Field | Meaning | Snippet |
|---|---|---|
data: | Payload line(s); usually JSON | data: {"id": 1, "status": "paid"} |
event: | Event type (addEventListener("order", ...)); default message | event: order |
id: | Last event id; sent back as Last-Event-ID | id: 0 |
retry: | Reconnection time in ms | retry: 5000 |
: comment | Ignored; used for keep-alive | : keep-alive |
| blank line | Dispatch | \n\n |
| Content type | text/event-stream | media_type="text/event-stream" |
Fix / how to use it: the snippet's sse_frame() (one function, tested), id on every event you might need to resume from, Last-Event-ID read as a Header(), retry: once at the start, and the headers in Proxies.
SSE implementations: hand-rolled, sse-starlette EventSourceResponse, fastapi.sse Important
In plain words: Three ways to send SSE from FastAPI: write the framing yourself over StreamingResponse (the snippet's /sse/orders), use the third-party sse-starlette package's EventSourceResponse (/sse/lib), or, on FastAPI 0.135.0+, fastapi.sse.EventSourceResponse with yield in the path operation.
Common misunderstanding: "EventSourceResponse is one class." There are two with the same name: sse_starlette.EventSourceResponse (a response you construct around a generator) and fastapi.sse.EventSourceResponse (a response_class for a path operation that yields). Second: "The library output is byte-identical to mine." Real: sse-starlette 3.3.0 separates lines with \r\n by default (sep parameter), sets Cache-Control: no-store, Connection: keep-alive and X-Accel-Buffering: no, and pings every 15 s.
Definition: sse-starlette: "Production ready Server-Sent Events implementation for Starlette and FastAPI following the W3C SSE specification"; parameters include ping (default 15, "0 disables keep-alive pings"), sep, send_timeout, shutdown_event, shutdown_grace_period. FastAPI 0.135.0 docs: "To stream SSE with FastAPI, use yield in your path operation function and set response_class=EventSourceResponse"; "Each yielded item is encoded as JSON and sent in the data: field"; ServerSentEvent sets event, id, retry, comment; raw_data sends pre-formatted text such as [DONE]; and "FastAPI implements some SSE best practices out of the box": a keep-alive ping comment "every 15 seconds", Cache-Control: no-cache and X-Accel-Buffering: no.
# FastAPI 0.135.0+ only (described from the docs; not run on the 0.128.8 pin)
from collections.abc import AsyncIterable
from fastapi import FastAPI
from fastapi.sse import EventSourceResponse, ServerSentEvent
app = FastAPI()
@app.get("/orders/events", response_class=EventSourceResponse)
async def order_events() -> AsyncIterable[ServerSentEvent]:
for seq, status in enumerate(["paid", "packed", "shipped"]):
yield ServerSentEvent(data={"id": 1, "status": status}, event="order", id=str(seq))Hand-rolled (StreamingResponse) | sse-starlette 3.3.0 | fastapi.sse (0.135.0+) | |
|---|---|---|---|
| Install | nothing | sse-starlette (3.7.1 needs Python 3.11+) | FastAPI ≥ 0.135.0 |
| Framing | your sse_frame() | ServerSentEvent / dicts | ServerSentEvent, JSON-encoded data |
| Line separator | \n (snippet) | \r\n default | per the docs |
| Keep-alive pings | your loop | ping=15 | every 15 s |
Cache-Control | you set no-store (snippet) | no-store | no-cache (stored but revalidated; add no-store if no cache may keep it) |
X-Accel-Buffering: no | you set it | yes | yes |
| Disconnect handling | cancellation + your checks | built in | built in |
| Shutdown | server cancels | shutdown_event, grace period | server cancels |
| Typed data in OpenAPI | no | no | AsyncIterable[Item] documented and validated |
Fix / how to use it: on current FastAPI use fastapi.sse; on older pins (like the snippet's) use sse-starlette or a tested sse_frame(); never mix framings in one stream.
Proxies, proxy buffering, X-Accel-Buffering and keep-alive comments Must-know
In plain words: A stream that works against Uvicorn directly can arrive all at once (or time out) behind Nginx, a load balancer or a CDN, because they buffer responses and close idle connections. Tell Nginx not to buffer (X-Accel-Buffering: no), tell caches not to store it (Cache-Control: no-store; no-cache would still allow storage, see below), and send a comment line every ~15 s so the connection never looks idle.
Common misunderstanding: "My code flushes each chunk, so the client gets it." Nginx with proxy_buffering on (the default) "receives a response from the proxied server as soon as possible, saving it into the buffers"; the client sees nothing until a buffer fills or the response ends. Second: "Keep-alive comments are for the browser." They are for the middleboxes: the WHATWG spec says "Legacy proxy servers are known to, in certain cases, drop HTTP connections after a short timeout. To protect against such proxy servers, authors can include a comment line (one starting with a ':' character) every 15 seconds or so."
Definition: Nginx proxy_buffering (default on): "When buffering is disabled, the response is passed to a client synchronously, immediately as it is received." "Buffering can also be enabled or disabled by passing "yes" or "no" in the "X-Accel-Buffering" response header field." proxy_read_timeout defaults to 60 s and "is set only between two successive read operations" — the reason a 15 s ping keeps the stream alive. The WHATWG spec also warns that "HTTP chunking can have unexpected negative effects on the reliability of this protocol, in particular if the chunking is done by a different layer unaware of the timing requirements".
behind Nginx, defaults, no X-Accel-Buffering (expected, not run)
1 app sends event 1 at t=0 s, event 2 at t=5 s
2 Nginx buffers both (proxy_buffering on); client sees nothing
3 t=60 s no new bytes -> proxy_read_timeout -> Nginx closes the upstream connection
with X-Accel-Buffering: no + ": keep-alive" every 15 s:
4 each event reaches the client immediately; the ping resets the 60 s read timerReal scenario: an SSE page that "only updates when the request finishes" in production but works locally; a load balancer's idle timeout closing quiet streams; a CDN that caches the first response of an event stream for every user; Laravel's docs adding the same header: response()->stream(..., 200, ['X-Accel-Buffering' => 'no']).
| Layer | Problem | Fix |
|---|---|---|
| Nginx | proxy_buffering on | X-Accel-Buffering: no per response, or proxy_buffering off; in the location |
| Nginx | proxy_read_timeout 60s | Keep-alive comment every ~15 s, or raise the timeout for that location |
| Any cache / CDN | Stores the stream | Cache-Control: no-store (MDN: no-cache "allows caches to store a response but requires them to revalidate it before reuse"); bypass rules for text/event-stream |
| Load balancer | Idle timeout | Pings below the timeout |
| Compression (GZip middleware, proxy gzip) | Holds bytes until a block fills | Exclude text/event-stream |
| HTTP/1.1 browsers | MDN: the limit "is per browser + domain" and "set to a very low number (6)" | Share one EventSource (shared worker), or serve over HTTP/2 |
Fix / how to use it: the snippet's SSE_HEADERS plus keep-alive comments; Nginx configuration for streams is in FastAPI in Production; fan-out to many servers is in Real-time: Polling, SSE, WebSockets.
LLM token streaming Important
In plain words: A chat endpoint calls a model provider with streaming on, and forwards each token (or delta) to the browser as an SSE event as soon as it arrives, ending with a sentinel such as data: [DONE]. The user sees text appear in about a second instead of waiting for the full answer.
Common misunderstanding: "When the user closes the tab, the provider stops generating." Not unless you close the upstream stream. The snippet's chat_stream checks is_disconnected() and always calls aclose() on the token iterator in finally: (real: llm: upstream closed recorded). Second: "Errors return a 5xx." After the first token they cannot; send an event: error instead (Errors mid-stream).
Definition: the pattern is an async generator that iterates the provider SDK's async stream (OpenAI-compatible and native SDKs all expose one) and yields SSE frames; the FastAPI SSE docs show raw_data for "special "sentinel" values like [DONE]". Provider-side streaming formats, token accounting and retries are in LLM APIs in Practice; the full RAG endpoint is in FastAPI AI/RAG Project.
POST /chat/stream {"prompt":"hi"} (real, fake provider)
1 validate body, auth, quota (before the first byte: errors are still real statuses)
2 tokens = fake_llm_tokens(prompt) # stand-in for an SDK stream
3 async for token in tokens: yield "event: token\ndata: {\"delta\": \"You \"}\n\n" ...
4 yield "data: [DONE]\n\n"
5 finally: await tokens.aclose() -> "llm: upstream closed"Real scenario: a support chatbot; code completion; summarising a document while the user watches; an agent that streams tool progress as named events (event: tool, event: token).
| Step | Rule |
|---|---|
| Before streaming | Authenticate, validate, check quota and rate limits |
| While streaming | await per token, is_disconnected() check, small frames |
| On disconnect | Close the provider stream (stop paying) |
| On provider error | event: error with a Problem-shaped payload, then end |
| At the end | Sentinel ([DONE]) or event: end, plus usage in a final event if needed |
| Behind proxies | Same headers and pings as any SSE |
Fix / how to use it: the snippet's /chat/stream as the shape; swap fake_llm_tokens for the SDK's stream; keep the provider call out of BackgroundTasks (it must be tied to the client connection).
StaticFiles: mount, html=True, Cache-Control for static files, CDN Important
In plain words: app.mount("/app", StaticFiles(directory="static", html=True)) serves files from a folder under /app. With html=True, /app/ serves index.html and a missing file serves 404.html if you have one.
Common misunderstanding: "StaticFiles sets caching headers." It sets validators (ETag, Last-Modified) and answers conditional requests with 304 (real), but no Cache-Control; the snippet's CachedStaticFiles subclass adds public, max-age=31536000, immutable for fingerprinted assets and no-cache for HTML. Second: "A mount is like a router." The docs: "a mounted application is completely independent. The OpenAPI and docs from your main application won't include anything from the mounted application", and a mount at / would take every unmatched path.
Definition: StaticFiles(directory=None, packages=None, html=False, check_dir=True, follow_symlink=False); html means "Run in HTML mode. Automatically loads index.html for directories if such file exist." "Static files will respond with "404 Not found" or "405 Method not allowed" responses for requests which do not match. In HTML mode if 404.html file exists it will be shown as 404 response." Current FastAPI docs point frontends to app.frontend() (0.138.0, 2026-06-20), which "uses StaticFiles underneath, with several additional advantages for frontends, like handling client-side routing".
/app mount, html=True (real)
1 GET /app/ 200 index.html cache-control: no-cache etag: "135ff0…"
2 GET /app/ If-None-Match: "135ff0…" 304, no body
3 GET /app/assets/app.3f9a1c.css 200 cache-control: public, max-age=31536000, immutable
4 GET /app/nope.html 404 with 404.html POST /app/ 405
5 GET /app/../main.py 404 (path traversal refused)Real scenario: an admin SPA shipped with the API; a docs site; uploaded avatars in development only. In production at scale, Nginx or a CDN should serve them: they do range requests, compression, sendfile and caching at the edge without occupying Python workers.
Who serves /assets/* | Good for | Cache-Control |
|---|---|---|
StaticFiles in the app | Dev, small internal tools | add it yourself (subclass) |
Nginx in front (location /assets/) | One region, many requests | expires max; / immutable |
| CDN (CloudFront, Cloudflare, Fastly) | Global users, big files | long max-age + fingerprinted names |
| Object storage + CDN | User uploads | per object |
Fix / how to use it: fingerprinted file names (app.3f9a1c.css) with immutable, no-cache for index.html, a non-root prefix for the mount, and a CDN when traffic or file size grows. CDN setup is in File Uploads, S3 & CDN.
BackgroundTasks preview Good to know
In plain words: tasks.add_task(fn, *args) runs fn after the response is sent, in the same process: confirmation emails, audit logs, cache warm-ups.
Common misunderstanding: "A background task error becomes a 500 for the client." The response is already gone. Starlette: "in case a BackgroundTask raises an exception, it will be handled by the handle_error function, but at that point, the response was already sent … the response created by handle_error will be discarded." Second: "It is a job queue." It dies with the process and has no retries.
Definition: FastAPI: "You can define background tasks to be run after returning a response." The snippet's create_order adds send_confirmation; real: the log line confirmation sent for order 2 appears after the 201 (test_201_with_location_and_background_task).
1 POST /orders -> 201 sent (Location: /orders/2)
2 then: send_confirmation(2) -> INFO [rid] shop: confirmation sent for order 2
3 an exception here -> logged by the 500 path, client unaffectedReal scenario: "thank you" email; webhook fan-out to a few URLs; deleting a temp file after a FileResponse.
| Need | Tool |
|---|---|
| Tiny, best-effort, after the response | BackgroundTasks |
| Retries, persistence, scheduling | A job queue (Celery, ARQ, RQ, Dramatiq) |
| Tied to the client connection (LLM stream) | The streaming generator itself |
Fix / how to use it: keep tasks short and idempotent; anything that must happen goes to a queue. Full treatment: Background Tasks, Caching & External APIs.
Mechanics
One request through the stack, success and failure Important
FastAPI 0.128.8 builds the stack in FastAPI.build_middleware_stack (source saved): ServerErrorMiddleware(handler=<your Exception/500 handler>, debug=debug), then every user middleware, where the last one added is the outermost (the docs: "The last middleware added is the outermost, and the first is the innermost"; Starlette's add_middleware does self.user_middleware.insert(0, ...)), then ExceptionMiddleware(handlers=<every other handler>, debug=debug), then FastAPI's AsyncExitStackMiddleware (where yield dependencies are closed), then the router. Each APIRoute additionally wraps its own call in wrap_app_handling_exceptions, which is why the traceback of a handled exception shows starlette/_exception_handler.py twice.
POST /orders (409) and GET /boom (500), snippet app (real)
1 Uvicorn await app(scope, receive, send)
2 ServerErrorMiddleware try: await app(scope, receive, _send) (tracks response_started)
3 RequestIdMiddleware request_id_var.set(...); wraps send to add X-Request-ID
4 ExceptionMiddleware wrap_app_handling_exceptions(...)
5 AsyncExitStack, Router, APIRoute -> create_order() in the thread pool (def)
6a raise OutOfStock -> lookup handlers by MRO -> domain_error_handler -> JSONResponse 409
7a response sent through RequestIdMiddleware's send (gets X-Request-ID) -> Uvicorn: 409 Conflict
6b raise RuntimeError -> no handler -> propagates out of ExceptionMiddleware and RequestIdMiddleware
7b ServerErrorMiddleware: unhandled_handler -> 500 via the *outer* send (no middleware header) -> raise exc
8b Uvicorn: access log 500, then "ERROR: Exception in ASGI application" + tracebackHow a handler is chosen Good to know
Starlette's _lookup_exception_handler walks type(exc).__mro__ and returns the first class found in the handler table; for HTTPException it first tries the integer status code. Consequences (all real in the tests): a handler keyed 404 catches the router's 404; a handler for DomainError catches FlashSaleSoldOut(OutOfStock); a handler for fastapi.HTTPException misses the router's Starlette HTTPException; Exception is never looked up here, because FastAPI moved it to ServerErrorMiddleware.
| Exception raised | Handler table checked | Order |
|---|---|---|
HTTPException(status_code=404) | ExceptionMiddleware | key 404, then the class MRO |
OutOfStock | ExceptionMiddleware | OutOfStock, DomainError, Exception (absent), BaseException |
RequestValidationError | ExceptionMiddleware | its MRO (FastAPI installs a default) |
RuntimeError | none in ExceptionMiddleware | → ServerErrorMiddleware handler |
| Exception inside a handler | — | → ServerErrorMiddleware |
How a stream runs Good to know
StreamingResponse.__call__ reads scope["asgi"]["spec_version"]. For servers below 2.4 (Uvicorn 0.39.0 sends "2.3"), it starts a task group with stream_response(send) and listen_for_disconnect(receive); whichever finishes first cancels the other. For 2.4+ servers it only streams and turns an OSError on send into ClientDisconnect. A sync iterator is wrapped in iterate_in_threadpool, so each next() runs in a worker thread. Uvicorn's send drops body messages after a disconnect and awaits flow.drain() while writing is paused. Since FastAPI 0.118.0 the exit code of yield dependencies runs after the response is sent, so a database session from a dependency stays open while a stream uses it (details: Dependency Injection).
| Server ASGI spec | Disconnect detected by | Effect on your generator |
|---|---|---|
| 2.3 (Uvicorn 0.39.0) | listen_for_disconnect task | CancelledError at the next await |
| 2.4+ | OSError on send | ClientDisconnect raised from send |
| Any | your await request.is_disconnected() | You return early |
Exact errors, warnings and log lines Must-know
Every line below was printed by the snippet runs (FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, Uvicorn 0.39.0, sse-starlette 3.3.0, httpx 0.28.1, curl on macOS).
| Trigger | Status | Exact output |
|---|---|---|
| Unknown order | 404 | {"type":"https://shop.example/problems/order-not-found","title":"Order not found","status":404,"instance":"/orders/99",...,"detail":"Order 99 does not exist.","order_id":99} |
PUT /orders/1 | 405 | allow: GET, "title":"Method Not Allowed" |
Reused Idempotency-Key | 409 | "title":"Duplicate order","detail":"This Idempotency-Key was already used." |
GET /boom | 500 | "detail":"Unexpected error. Quote the request id." + x-request-id: lab-500 |
| Uvicorn after the 500 | — | INFO: 127.0.0.1:59214 - "GET /boom HTTP/1.1" 500 Internal Server Error then ERROR: Exception in ASGI application |
| Our 500 log line | — | ERROR [lab-500] shop: unhandled RuntimeError on GET /boom + traceback |
| No handlers, unhandled error | 500 | Internal Server Error (text/plain; charset=utf-8) |
debug=True | 500 | Traceback (most recent call last): … (text/plain; HTML with Accept: text/html) |
return HTTPException(409, ...), no annotation | 200 | {"status_code":409,"detail":"out of stock","headers":null} |
same with -> Any | 500 | PydanticSerializationError: Unable to serialize unknown type: <class 'fastapi.exceptions.HTTPException'> (server log) |
| Response model mismatch | 500 | fastapi.exceptions.ResponseValidationError |
| Bug inside a handler | 500 | During handling of the above exception, another exception occurred: … TypeError |
DELETE → 204 | 204 | no body, no content-length, content-type: application/json |
| Error after the first chunk | 200 | curl exit 18; httpx RemoteProtocolError: peer closed connection without sending complete message body (incomplete chunked read) |
Disconnect during /stream/ticks | — | INFO [7e8503…] shop: ticks cancelled after 18 chunks (client disconnected) |
| Streaming response headers | 200 | transfer-encoding: chunked, no content-length |
FileResponse + Range: bytes=0-7 | 206 | content-range: bytes 0-7/193 |
StaticFiles + If-None-Match | 304 | etag: "135ff096b8253f9d131ad581821d13db", no body |
Solving the classic problems
| Bug | Symptom | Fix | Cost |
|---|---|---|---|
| Errors returned as values | 200 on failures; caches store errors | Raise; map once | Small refactor |
return HTTPException(...) | 200 with the exception's fields, or 500 | raise | One word |
Catch-all except Exception in routes | Bugs become 400s, messages leak | Remove; let the 500 path handle it | Fewer lines |
Handler on fastapi.HTTPException | Router 404/405 in a different format | Register on Starlette's class | One import |
debug=True outside a laptop | Tracebacks and secrets in bodies | Settings default False + test | Config |
No Exception handler | text/plain 500, no request id | Generic Problem + log once | 15 lines |
| Middleware expected to add headers to 500s | Missing X-Request-ID on errors | Set it in the 500 handler | 1 line |
Domain errors raised as HTTPException in services | Services import FastAPI; CLI/workers get HTTP errors | Domain classes + mapping table | A module |
Raw IntegrityError reaches the edge | 500 for a duplicate | Translate in the store (raise DuplicateOrder from exc) | A few lines |
Errors missing from /docs | Clients cannot type errors | responses= with the error model | A dict |
| Fake streaming (list first) | Memory spike, slow first byte | Produce inside the generator | Restructure |
No await in an async generator | Cannot be cancelled; blocks the loop | await per item, or a sync generator | Small |
| No cleanup on disconnect | Upstream calls keep running (LLM cost) | try/finally + aclose() | Small |
| SSE behind Nginx arrives at the end | Buffered stream | X-Accel-Buffering: no, pings | Headers |
SSE without id | Reconnect replays or loses events | id: + Last-Event-ID | Design |
One place for every error
The After app has exactly one module that knows HTTP status codes for failures (app/problems.py). Routes raise or let the store raise; the store translates SQL outcomes; the handlers translate exceptions. Adding a failure is: a class in domain.py, a row in DOMAIN_STATUS, a test. Shared across many routers, the module is registered by the app factory (APIRouter & Project Structure).
Finding any 500 from a user's report
Request id in, request id out: the middleware accepts or creates it, the log filter stamps it on every record, the 500 handler returns it in the body and header and logs the traceback once. Support asks for the id; one grep finds the traceback. Forward it to downstream services as X-Request-ID (or use the trace id from OpenTelemetry).
Streams that survive the real world
Check everything before the first byte; produce lazily; await per chunk; finally: for cleanup; X-Accel-Buffering: no and Cache-Control: no-store for SSE; keep-alive comments below every idle timeout on the path; id: on events you might replay. Test framing with TestClient and disconnects/back-pressure against a real Uvicorn (the snippet's test_live.py).
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| Normal JSON read | Return a model (-> OrderOut) | response_model_exclude_none if sparse | Fast path, documented |
| Return raw rows | response_model=OrderOut | Separate output model | Filtering |
| Business rule refuses | Domain error → 409/404/422 | Mapping table | Services stay HTTP-free |
| Auth / method / size | HTTPException with headers | Dependency | HTTP-level outcome |
| Bug | Let it raise | Exception handler + request id | One log line |
| Created | 201 + Location | Return the resource | RFC 9110 |
| Deleted | 204 | 404 when missing | No content |
| Cacheable read | ETag + 304 | Cache-Control | Saves bandwidth |
| Non-JSON body | response_class=HTMLResponse/PlainTextResponse | Templates for HTML | Correct media type |
| File on disk | FileResponse | Range support built in | Validators, 206 |
| Generated large body | StreamingResponse | Sync generator for blocking sources | Bounded memory |
| Server → browser events | SSE (fastapi.sse 0.135+ or sse-starlette) | id, pings, proxy headers | Auto-reconnect |
| Two-way, low latency | WebSocket | Real-time | Full duplex |
| LLM tokens | SSE over POST | Close upstream on disconnect | Cost |
| Static assets, small app | StaticFiles mount | Cache-Control subclass | Simple |
| Static assets, real traffic | Nginx or CDN | Fingerprinted names | Frees workers |
| After-response chore | BackgroundTasks | Idempotent | Simple |
| Must-run job | A queue | Retries | Durable |
Which streaming transport
| Need | Plain stream | JSON Lines | SSE | WebSocket |
|---|---|---|---|---|
| Browser API | fetch + reader | fetch + split lines | EventSource | WebSocket |
| Auto-reconnect + resume | No | No | Yes (retry, Last-Event-ID) | You build it |
| Client → server messages | No | No | No (new request) | Yes |
| Typed events | No | One JSON per line | event: names | Your protocol |
| Proxy friendliness | Good | Good | Good with the headers | Needs upgrade support |
| FastAPI support | StreamingResponse | 0.134.0+ (yield) | 0.135.0+ / sse-starlette | @app.websocket |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One app, one problems.py, one mapping table, one request-id middleware. The snippet is this shape: SQLite stands in for PostgreSQL, the store translates IntegrityError and empty results into domain errors, StaticFiles serves a small admin front end, and an SSE endpoint pushes order status to the tracking page from the same process. Example: the shop's POST /orders returns 201 or a Problem 409, the tracking page subscribes to /sse/orders and resumes with Last-Event-ID after a network blip.
Modular monolith and multiple databases
Each module (orders, payments, catalog) owns its domain error classes; one shared HTTP layer owns the envelope and maps every module's base class (OrdersError, PaymentsError) through one registration function per module. type URIs are namespaced per module (.../problems/orders/out-of-stock). A second database (Redis for sessions, a search index) gets its own error translation in its adapter: a Redis timeout is a PaymentProviderDown-style dependency error (503), not a 500. Routers cannot register handlers (APIRouter has no exception_handler), so module boundaries are expressed in classes, not in routers.
Microservices
Errors cross the wire, and each hop must translate deliberately. Example flow: POST /checkout on the orders service → POST http://payments/charges (with X-Request-ID and Idempotency-Key) → payments answers 402 Problem card-declined → orders maps it to its own 409 payment-declined for the client; a payments timeout becomes 503 + Retry-After; a payments 500 becomes the orders service's 502. What does not survive the hop: the exception class, the traceback, the other service's type URIs (never forward them blindly), and the request's stream (a client stream proxied through two services needs every hop to stream, not buffer). Using the same RFC 9457 envelope in Go and Python services makes clients and gateways simpler. Idempotency design: API Idempotency.
Distributed data: replicas, caches, sharded databases, multi-region
ETags and 304s interact with replicas: an ETag computed on a lagging replica can make a client believe it is current; compute validators from a version column that travels with the row, or read from the primary for conditional requests. Caches (CDN, Nginx, shared Redis) must never store error bodies with personal data or event streams (Cache-Control: no-store on errors that include user data and on streams; no-cache only where storing is fine but every reuse must be revalidated, like index.html). SSE across many servers needs a shared event source (Redis pub/sub, Postgres LISTEN/NOTIFY, Kafka) so that a reconnect with Last-Event-ID can land on any replica and resume from a durable log, not from one process's memory. Error rates per type URI are the natural SLO metric across regions. Fan-out patterns: Real-time: Polling, SSE, WebSockets; caching: Caching.
Scaling path: 1×, 10×, 100×
| Load | What changes | Practice |
|---|---|---|
| 1× (one process) | Defaults look fine | One problems module, request ids, no debug, response models, FileResponse, a few SSE clients from the app |
| 10× (workers/replicas behind a load balancer) | Streams hold connections; per-process SSE state diverges; static files compete with API calls | Nginx or a CDN for static files; SSE events from Redis/Postgres; pings below LB idle timeouts; --limit-concurrency; error dashboards by type |
| 100× (many services, many long-lived connections) | Tens of thousands of open streams; error storms; reconnect storms | A dedicated SSE/WebSocket gateway; jittered retry:; Last-Event-ID from a durable log; Problem types as contract; load shedding with 503 + Retry-After (Load Shedding) |
Lab
All commands run from docs/snippets/python/exception-handling-responses/, with a virtual environment outside the repository. "Real" outputs were produced on CPython 3.9.6 (macOS) with the pinned versions and are saved under pipeline/sources/exception-handling-responses/runs/.
1. Install and run the tests (real)
python3 -m venv /tmp/ehr-venv && /tmp/ehr-venv/bin/pip install '.[test]'
PYTHONDONTWRITEBYTECODE=1 /tmp/ehr-venv/bin/python -m pytest -s
# real: see runs/pytest-fresh-install.txt
# produced while the client read nothing: 18/512 chunks (1152 KiB); total received 32772 KiB
# after disconnect: ['ticks: cancelled after 3', 'ticks: cleanup']
# 50 passed2. Errors through the handlers (real)
/tmp/ehr-venv/bin/uvicorn app.main:app --port 18921 # the venv from step 1 (or activate it first)
curl -si localhost:18921/orders/99 # 404 application/problem+json, type .../order-not-found
curl -si -X PUT localhost:18921/orders/1 # 405, allow: GET, title "Method Not Allowed"
curl -si -X POST localhost:18921/orders -H 'content-type: application/json' \
-H 'Idempotency-Key: lab-1' -d '{"sku":"BOOK-1","qty":2}' # 201, location: /orders/2
# same command again # 409 duplicate-order
curl -si -X DELETE localhost:18921/orders/2 # 204, no body3. The 500 path and the logs (real)
curl -si localhost:18921/boom -H 'X-Request-ID: lab-500'
# HTTP/1.1 500 Internal Server Error / x-request-id: lab-500 / content-type: application/problem+json
# {"type":"about:blank","title":"Internal Server Error","status":500,"instance":"/boom","request_id":"lab-500",...}
# server log:
# ERROR [lab-500] shop: unhandled RuntimeError on GET /boom (+ traceback)
# INFO: 127.0.0.1:59214 - "GET /boom HTTP/1.1" 500 Internal Server Error
# ERROR: Exception in ASGI application (+ traceback: the re-raise)Then restart with FastAPI(debug=True) in a scratch copy and repeat: the body becomes the traceback including hunter2 (asserted in test_before.py).
4. Streams, SSE and disconnects (real)
curl -si "localhost:18921/stream/ticks?n=3" # transfer-encoding: chunked; tick 0..2
curl -sN -i "localhost:18921/sse/orders?idle=0.2&ping=0.1"
# : stream opened / retry: 5000 / event: order id: 0..2 / : keep-alive (x2) / event: end
curl -sN -H 'Last-Event-ID: 1' localhost:18921/sse/orders # only id: 2 (test_last_event_id_resumes)
curl -sN localhost:18921/sse/lib | cat -v # sse-starlette: lines end in ^M (\r\n)
curl -sN --max-time 0.2 "localhost:18921/stream/ticks?n=10000&delay=0.01"
# server log: INFO [7e8503…] shop: ticks cancelled after 18 chunks (client disconnected)5. An exception in the middle of a stream (real)
/tmp/ehr-venv/bin/uvicorn app.midstream:app --port 18922 # app/midstream.py: yields "part 1", then raises
curl -si localhost:18922/s # 200 ... part 1 (curl exit code 18)
/tmp/ehr-venv/bin/python -c "import httpx; httpx.get('http://127.0.0.1:18922/s')"
# httpx.RemoteProtocolError: peer closed connection without sending complete message body (incomplete chunked read)6. Behind Nginx (expected, not run)
# nginx.conf (no Nginx on the build machine: expected behaviour from the Nginx docs)
location /sse/ { proxy_pass http://127.0.0.1:18921; proxy_http_version 1.1; }
# 1) /sse/orders with X-Accel-Buffering: no -> events arrive one by one
# 2) remove the header in a scratch copy -> events arrive together when the stream ends (proxy_buffering on)
# 3) /sse/orders?idle=90&ping=0 (silent 90 s; accepted by the app, real: 200)
# -> connection closed after proxy_read_timeout (60s default)
# 4) /sse/orders?idle=90&ping=15 -> stays open: each comment resets the 60 s read timerFor PHP/Laravel developers
Laravel has the same two-layer idea under different names. In Laravel 13, exception handling is configured with ->withExceptions() in bootstrap/app.php (it replaced the App\Exceptions\Handler class; the Laravel 10.x docs: "All exceptions are handled by the App\Exceptions\Handler class"): $exceptions->report(...) decides how an exception is logged, $exceptions->render(...) how it becomes a response (a custom report callback does not replace the default log: "Laravel will still log the exception using the default logging configuration" unless you call ->stop() or return false), which is FastAPI's split between logging in the 500 handler and returning a body from an exception handler. Laravel also lets the exception class carry both: "you may define report and render methods directly on your application's exceptions. When these methods exist, they will automatically be called by the framework", the closest thing to the snippet's DomainError + mapping table in one class. abort(404) is raise HTTPException(404); findOrFail throwing ModelNotFoundException is the snippet's OrderNotFound (Eloquent docs: "If the ModelNotFoundException is not caught, a 404 HTTP response is automatically sent back to the client"). The debug rule is identical: "In your production environment, the value of APP_DEBUG should always be false." Laravel decides HTML or JSON "based on the Accept header of the request" (shouldRenderJsonWhen overrides it), while FastAPI answers JSON unless you say otherwise (and only the debug traceback page looks at Accept). On the response side, response()->download() and response()->file() are FileResponse with attachment/inline; response()->stream() is StreamingResponse, and the Laravel docs send the same Nginx header: ['X-Accel-Buffering' => 'no']; "if the closure you provide to the stream method returns a Generator, Laravel will automatically flush the output buffer between strings returned by the generator, as well as disable Nginx output buffering". response()->streamJson() is JSON streaming, and response()->eventStream() "may be used to return a server-sent events (SSE) streamed response using the text/event-stream content type", with StreamedEvent for named events. The process model is the big difference: PHP-FPM serves requests from a pool of child processes whose number is capped by pm.max_children (PHP manual), so each open stream holds one of those children until it ends, while a FastAPI stream is a suspended coroutine on an event loop, so many SSE clients cost memory, not processes.
// bootstrap/app.php (Laravel 13): the mapping layer, like app/problems.py
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->render(function (OutOfStock $e, Request $request) { // OutOfStock -> 409 Problem
return response()->json([
'type' => 'https://shop.example/problems/out-of-stock', 'title' => 'Not enough stock',
'status' => 409, 'detail' => $e->getMessage(), 'instance' => $request->path(),
], 409, ['Content-Type' => 'application/problem+json']);
});
$exceptions->report(function (Throwable $e) { // log once, with context
Log::error($e->getMessage(), ['request_id' => request()->header('X-Request-ID')]);
})->stop(); // without stop(): logged twice
})
// routes/api.php: streaming and SSE, like app/streaming.py
Route::get('/export/orders.csv', fn () => response()->streamDownload(function () {
foreach (Order::lazy() as $o) { echo "{$o->id},{$o->sku},{$o->qty}\n"; } // sync generator in FastAPI
}, 'orders.csv', ['Content-Type' => 'text/csv']));
Route::get('/sse/orders', fn () => response()->eventStream(function () {
foreach (OrderStatus::forOrder(1) as $s) {
yield new StreamedEvent(event: 'order', data: $s->toJson()); // event: order / data: ...
}
}));| Laravel 13 | FastAPI |
|---|---|
->withExceptions() in bootstrap/app.php (old App\Exceptions\Handler) | install_problem_handlers(app) |
$exceptions->render(fn (OutOfStock $e) => ...) | app.add_exception_handler(DomainError, handler) |
$exceptions->report(...)->stop() (or return false) | log.exception(...) in the Exception handler, once |
render() / report() on the exception | Mapping table keyed by class |
abort(404) | raise HTTPException(404) |
findOrFail → ModelNotFoundException → 404 | Store.get → OrderNotFound → 404 |
APP_DEBUG=false | FastAPI(debug=False) |
shouldRenderJsonWhen | Always JSON (your handlers) |
response()->json($data, 201)->header('Location', ...) | status_code=201 + response.headers["Location"] |
->cookie(...) / cookie() helper | response.set_cookie(...) |
response()->download($path, $name) | FileResponse(path, filename=name) |
response()->stream(fn () => ..., 200, ['X-Accel-Buffering' => 'no']) | StreamingResponse(gen(), headers={"X-Accel-Buffering": "no"}) |
response()->streamJson([...]) | JSON Lines with yield (0.134.0+) |
response()->eventStream(...) + StreamedEvent | fastapi.sse.EventSourceResponse (0.135.0+) or sse-starlette |
public/ served by Nginx | StaticFiles mount, or Nginx/CDN |
Queued jobs (dispatch()) | a real queue; BackgroundTasks for small after-response chores |
The Go angle
Go has no exceptions for expected failures: functions return an error value, and the HTTP boundary decides the status. The Go 1.13 errors blog describes the tools that play the role of FastAPI's handler lookup: "In Go 1.13, the fmt.Errorf function supports a new %w verb. When this verb is present, the error returned by fmt.Errorf will have an Unwrap method returning the argument of %w", and "The errors.Is function compares an error to a value" along the whole chain, so a store can return fmt.Errorf("get order %d: %w", id, ErrOrderNotFound) and the handler can still ask errors.Is(err, ErrOrderNotFound). That is the snippet's MRO walk, done on the wrapping chain instead of the class hierarchy. A panic is Go's unhandled exception: the net/http server recovers it per connection and logs http: panic serving %v: %v with the stack (server.go), the counterpart of ServerErrorMiddleware's re-raise, and a recovery middleware writes the 500 body. Streaming is explicit: write to the ResponseWriter and call Flush() ("Flush sends any buffered data to the client", the http.Flusher interface), or http.NewResponseController(w).Flush(), added in Go 1.20 as "a clearer, more discoverable way to add per-handler controls". For incoming requests "the context is canceled when the client's connection closes" (request.go), which is request.is_disconnected() plus cancellation in one value. http.ServeContent "handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests" (fs.go). The chapters: Errors, panic, recover, defer and net/http: Server, Client.
// Go 1.22+: the mapping table and an SSE stream, like app/problems.py and app/streaming.py
var (
ErrOrderNotFound = errors.New("order not found")
ErrOutOfStock = errors.New("out of stock")
)
func writeProblem(w http.ResponseWriter, r *http.Request, err error) {
status, slug := http.StatusInternalServerError, "" // default: the 500 path
switch {
case errors.Is(err, ErrOrderNotFound): // walks the %w chain, like the MRO lookup
status, slug = http.StatusNotFound, "order-not-found"
case errors.Is(err, ErrOutOfStock):
status, slug = http.StatusConflict, "out-of-stock"
default:
slog.Error("unhandled", "err", err, "request_id", r.Header.Get("X-Request-ID")) // log once
}
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]any{"type": "https://shop.example/problems/" + slug,
"title": http.StatusText(status), "status": status, "instance": r.URL.Path})
}
func orderEvents(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Accel-Buffering", "no")
rc := http.NewResponseController(w)
for seq, status := range []string{"paid", "packed", "shipped"} {
select {
case <-r.Context().Done(): // client disconnect: the context is cancelled
return
default:
}
fmt.Fprintf(w, "event: order\nid: %d\ndata: {\"status\":%q}\n\n", seq, status)
rc.Flush() // like each yield in StreamingResponse
}
}| Concern | FastAPI | Go net/http |
|---|---|---|
| Expected failure | raise OrderNotFound | return fmt.Errorf("...: %w", ErrOrderNotFound) |
| Matching | Handler lookup by class MRO | errors.Is / errors.As along the %w chain |
| Mapping to HTTP | One handler + table | One writeProblem function |
| Unexpected failure | Exception → ServerErrorMiddleware → 500 + re-raise | panic → recovered by the server, logged as http: panic serving ...; recovery middleware writes 500 |
| Headers on errors | HTTPException(headers=...) | w.Header().Set(...) before WriteHeader |
| Streaming | StreamingResponse(generator) | Write + Flush |
| Disconnect | Cancellation + is_disconnected() | r.Context().Done() |
| Back-pressure | await send blocks the generator | Write blocks the goroutine |
| Static files | StaticFiles | http.FileServer(http.Dir(...)) |
| File download | FileResponse (Range, ETag) | http.ServeContent (Range, If-None-Match, If-Modified-Since) |
Common misconceptions
| Belief | Reality |
|---|---|
An Exception handler swallows the exception | ServerErrorMiddleware re-raises after sending the 500; Uvicorn logs it, TestClient raises it |
return HTTPException(...) works | 200 with the exception's fields, or a 500 with -> Any (real) |
A handler for fastapi.HTTPException catches the router's 404 | Register Starlette's class; FastAPI's is a subclass |
| Middleware adds headers to every response | Not to the 500 from ServerErrorMiddleware; set them in the handler |
debug=True only adds a stack trace | It sends source lines and messages (secrets) and bypasses your 500 handler |
| Out of stock is a 400/422 | A valid request refused by current state: 409 Conflict |
response_model and -> Model conflict | response_model wins when both are present |
204 means {} | No body; FastAPI 0.128.8 still adds content-type: application/json (real) |
ORJSONResponse is the fast way | Deprecated in 0.131.0; a response model is serialised in Rust |
StreamingResponse(iter(big_list)) saves memory | The list is already in memory |
| A slow client makes the server buffer everything | await send blocks the generator (18 of 512 chunks, real) |
| A disconnect stops the work instantly | Only at the next await; CPU loops keep running |
| An error mid-stream returns a 500 | Status is already 200; the body is truncated (curl exit 18, real) |
Every yield is an SSE event | Only a blank line dispatches an event |
| SSE works the same behind Nginx | proxy_buffering on holds it; send X-Accel-Buffering: no |
StaticFiles sets caching | Validators and 304 yes, Cache-Control no |
| Background task errors reach the client | The response is already sent; the error is only logged |
Cheat sheet
| Topic | Remember |
|---|---|
| Raise, don't return | raise HTTPException(404, detail=..., headers=...) |
| Register on | starlette.exceptions.HTTPException |
| Custom errors | Domain classes + one handler per base class (MRO) |
| 500 | add_exception_handler(Exception, h) → ServerErrorMiddleware, then re-raise |
| 500 headers | Set in the handler; middleware cannot |
| Debug | False outside a laptop; it bypasses your 500 handler |
| Format | RFC 9457, application/problem+json, type/title/status/detail/instance + extensions |
| Mapping | Service raises meaning; one table → status/type/title |
| Logs | logger.exception once, with the request id from a ContextVar |
| Docs | responses={404: {"model": Problem}} |
| Output | -> Model or response_model=; exclude_unset / exclude_none |
| Status | 201 + Location, 204 no body, 304 with the same validators |
| Classes | HTMLResponse, PlainTextResponse, RedirectResponse (307), FileResponse, StreamingResponse |
| Stream | Lazy generator, await per chunk, finally: cleanup, checks before the first byte |
| SSE | text/event-stream, id/event/retry/data, blank line, : ping, Last-Event-ID |
| Proxies | X-Accel-Buffering: no, Cache-Control: no-store (not no-cache: that one stores and revalidates), ping < idle timeouts |
| Static | StaticFiles(html=True) under a prefix; Cache-Control yourself; CDN at scale |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why should you raise an HTTPException instead of returning it, and what happens if you return it? Must-know
Answer
Answer: Raising stops the request from any depth and hands the exception to the handler, which sends its status, detail and headers. Returned, it is an ordinary object: with no return annotation FastAPI serialises its attributes and sends 200 {"status_code":409,"detail":"out of stock","headers":null}; with -> Any serialisation fails and the client gets a 500 (both real). See HTTPException.
2 — You registered @app.exception_handler(HTTPException) with the class imported from fastapi, but typos in URLs still return {"detail":"Not Found"}. Why, and what is the fix? Must-know
Answer
Answer: The router (and StaticFiles) raise Starlette's HTTPException, the parent class; a handler for the FastAPI subclass does not match the parent. Register the handler for starlette.exceptions.HTTPException: it then catches yours (subclass) and the router's 404/405, and must keep exc.headers (for example allow on 405). See FastAPI's vs Starlette's HTTPException.
3 — What exactly happens when a route raises RuntimeError and you have a handler for Exception? Must-know
Answer
Answer: ExceptionMiddleware has no handler, so the exception propagates through every user middleware to ServerErrorMiddleware, the outermost layer, which calls your handler, sends its response with the outer send (so user middleware cannot add headers) and then re-raises. Uvicorn logs Exception in ASGI application with the traceback; TestClient(app) raises the exception in the test unless raise_server_exceptions=False. See The handler for Exception.
4 — How do you map a service's OrderNotFound and OutOfStock to HTTP without the service importing FastAPI? Must-know
Answer
Answer: Define a domain hierarchy (DomainError → OrderNotFound, OutOfStock), raise it in the service/store (translating SQL outcomes there: no row → OrderNotFound, IntegrityError → DuplicateOrder), and register one handler for DomainError that looks the class up (along its MRO) in a table giving status, type URI and title: 404 for not found, 409 Conflict for state conflicts. Unmapped subclasses become a logged 500. See Domain error mapping.
5 — A client streams a large CSV export but reads very slowly. Does the server buffer the whole file in memory? Must-know
Answer
Answer: Not if the generator produces lazily. Each yield is followed by await send(...), and Uvicorn's flow control makes that await block (pause_writing → drain()) while the socket buffers are full, so the generator is suspended. Measured: a client that read nothing for 0.5 s let the producer get 18 of 512 64 KiB chunks ahead. It breaks with fake streaming (a list built first) or an unbounded queue between producer and sender. See Back-pressure.
6 — Write the bytes of an SSE event of type order with id 7 and JSON data, and explain how a browser resumes after a disconnect. Important
Answer
Answer: event: order\nid: 7\ndata: {"status":"paid"}\n\n with Content-Type: text/event-stream; the blank line dispatches it. EventSource remembers the last id, waits the retry: reconnection time and sends a new request with Last-Event-ID: 7; the server reads that header and continues after 7 (real: Last-Event-ID: 1 → only event 2). See Server-Sent Events.
7 — Your SSE endpoint works locally but behind Nginx all events arrive at the end, and quiet streams die after a minute. What do you change? Important
Answer
Answer: Nginx buffers proxied responses by default (proxy_buffering on): send X-Accel-Buffering: no (or disable buffering in that location). Its proxy_read_timeout (60 s default) closes connections with no bytes between reads: send a comment line such as : keep-alive every ~15 s, which the WHATWG spec recommends for proxies. Add Cache-Control: no-store so caches do not store the stream (no-cache permits storage and only forces revalidation). See Proxies.
8 — How does a streaming endpoint notice that the client left, and what must the generator do? Important
Answer
Answer: With Uvicorn 0.39.0 (ASGI spec 2.3) Starlette runs a disconnect listener next to the stream and cancels the task group on http.disconnect; the generator gets CancelledError at its next await. Between chunks you can also call await request.is_disconnected(). The generator must await regularly, clean up in finally: (close upstream streams, cursors) and re-raise CancelledError. Real: ticks cancelled after 18 chunks (client disconnected). See Client disconnect.
9 — What does the client see if an exception happens after the first chunk of a stream, and how do you report such errors? Important
Answer
Answer: The status and headers are already sent (200), so no handler can change them: the connection closes without the final chunk (curl exit 18; httpx RemoteProtocolError ... incomplete chunked read). Do all checks that can fail with a status before the first yield, and report later errors in-band (an SSE event: error, a final JSON Lines error record). See Errors in the middle of a stream.
10 — response_model, return annotation, response_model_exclude_unset, response_model_exclude_none: what does each do, and which wins if both model declarations are present? Important
Answer
Answer: Both response_model= and -> Model validate, filter and document the output; if both are present, response_model takes priority. exclude_unset drops fields never explicitly set (defaults); exclude_none drops fields whose value is None. Real: preferences with only language set returned {"language":"fa"}; an order with a null note had no note key. See response_model.
11 — Which status, body and headers do 201, 204 and 304 need, and how does FastAPI produce each? Good to know
Answer
Answer: 201 Created: usually the resource plus a Location header (decorator status_code=201, response.headers["Location"]). 204 No Content: no body (decorator status_code=204, return None; 0.128.8 still adds content-type: application/json). 304 Not Modified: no body, the same validators as the 200 (ETag, Cache-Control), returned as Response(status_code=304, headers=...) when If-None-Match matches. See Status codes.
12 — When is StaticFiles the right tool, and what must you add yourself? Good to know
Answer
Answer: For development and small internal tools: mount it under a prefix (/app) with html=True for index.html/404.html. It sends ETag/Last-Modified and answers 304, but no Cache-Control; add it (immutable for fingerprinted assets, no-cache for HTML) with a subclass. At real traffic or for global users, let Nginx or a CDN serve the files. See StaticFiles.
Glossary
| Term | Meaning |
|---|---|
HTTPException | FastAPI's exception for HTTP errors: status_code, detail (any JSON), headers |
starlette.exceptions.HTTPException | The parent class; detail is a string; raised by the router and StaticFiles |
detail | The error message or payload of an HTTPException; also an RFC 9457 member |
status_code | The HTTP status of a response or exception |
| Headers on exceptions | HTTPException(headers=...): sent with the error response (WWW-Authenticate, Retry-After) |
| Custom exception class | Your own Exception subclass for a domain failure |
exception_handler | Decorator registering (request, exc) -> Response for a class or status code |
add_exception_handler | The same registration as a method call |
Handler for Exception | The 500 handler; FastAPI hands it to ServerErrorMiddleware |
ServerErrorMiddleware | Outermost Starlette layer: 500 response or debug traceback, then re-raise |
ExceptionMiddleware | Inner layer that runs every other handler |
| Re-raise | ServerErrorMiddleware raises the exception again after responding, so servers log it |
| 500 Internal Server Error | "the server encountered an unexpected condition" (RFC 9110) |
| Debug mode | FastAPI(debug=True): tracebacks in 500 responses; never in production |
RequestValidationError | Raised when input does not match the signature; default 422 |
ResponseValidationError | Raised when your output does not match the response model; a 500 |
| 422 | Unprocessable Content: input understood but invalid |
| Problem Details | RFC 9457 error format: type, title, status, detail, instance + extensions |
| RFC 9457 | July 2023 standard for Problem Details; obsoletes RFC 7807 |
application/problem+json | The media type of a Problem Details JSON body |
| Domain error mapping | One table from domain exception classes to status, type and title |
OrderNotFound | The snippet's domain error for a missing order (404) |
| 404 Not Found | No current representation of the target resource |
| 409 Conflict | Request conflicts with the current state of the resource |
| Request id | Per-request identifier in logs, headers (X-Request-ID) and error bodies |
ContextVar | Per-task variable from contextvars; carries the request id |
responses parameter | Decorator argument documenting extra statuses in OpenAPI |
| Error response model | A Pydantic model (Problem) used in responses= |
response_model | Decorator argument: validate, filter, document the output |
| Return type annotation | -> Model; used as the response model when no response_model is given |
response_model_exclude_unset | Omit fields that were never set |
response_model_exclude_none | Omit fields whose value is None |
response_class | The response class for a route (media type in docs and on the wire) |
JSONResponse | JSON body via json.dumps; default class when no model is used |
ORJSONResponse | JSON via orjson; deprecated in FastAPI 0.131.0 |
| orjson | Fast JSON library in Rust; 3.11.5 is the last release for Python 3.9 |
PlainTextResponse / HTMLResponse | Text and HTML response classes |
RedirectResponse | Redirect with Location; 307 by default |
FileResponse | Streams a file with Content-Length, Last-Modified, ETag, Range |
| Set-Cookie on Response | response.set_cookie(...) on the injected or returned response |
| 201 Created / Location header | New resource created; Location names it |
| 204 No Content | Success with no body |
| 304 Not Modified | Conditional request: the client's copy is current |
| ETag | Validator of a representation; compared with If-None-Match |
StreamingResponse | Body from a generator or async generator, sent as it is produced |
| Generator / async generator | def/async def functions with yield; the producer of a stream |
| Chunked transfer encoding | HTTP/1.1 framing for bodies of unknown length (RFC 9112 7.1) |
| Back-pressure | A slow reader pauses the producer through await send |
| Client disconnect | The client closed the connection; the stream is cancelled |
request.is_disconnected | Coroutine that reports whether the client has gone |
| Server-Sent Events | One-way event stream over HTTP (WHATWG HTML 9.2) |
text/event-stream | SSE media type |
| Event id / retry | id: sets the last event id; retry: sets the reconnection time in ms |
Last-Event-ID | Request header with the last id the browser received |
| sse-starlette | Third-party SSE package; EventSourceResponse, ServerSentEvent |
EventSourceResponse | SSE response class (sse-starlette, or fastapi.sse in 0.135.0+) |
| Proxy buffering | A reverse proxy collecting the response before forwarding it |
X-Accel-Buffering | Response header that turns Nginx buffering on or off per response |
| Keep-alive comments | : ... lines sent periodically so idle streams are not closed |
| LLM token streaming | Forwarding model output deltas to the client as SSE events |
StaticFiles | Starlette app serving a directory; mounted under a path |
mount | Attach an independent ASGI app under a path prefix |
html=True | StaticFiles HTML mode: index.html for directories, 404.html for misses |
| Cache-Control for static files | immutable + long max-age for fingerprinted assets, no-cache for HTML |
| CDN | Edge caches that serve static files close to users |
BackgroundTasks | Functions run after the response, in the same process |
X-Request-ID | Conventional header carrying the request id |
| Laravel exception Handler | Laravel's exception configuration: withExceptions(), render, report |
render / report (Laravel) | Turn an exception into a response / log it |
| Go error wrapping errors.Is | fmt.Errorf("...: %w", err) builds a chain; errors.Is matches a sentinel anywhere along it |
References
- FastAPI, "Handling Errors": https://fastapi.tiangolo.com/tutorial/handling-errors/
- FastAPI, "Response Model - Return Type": https://fastapi.tiangolo.com/tutorial/response-model/
- FastAPI, "Response Status Code": https://fastapi.tiangolo.com/tutorial/response-status-code/
- FastAPI, "Static Files": https://fastapi.tiangolo.com/tutorial/static-files/
- FastAPI, "Background Tasks": https://fastapi.tiangolo.com/tutorial/background-tasks/
- FastAPI, "Server-Sent Events (SSE)": https://fastapi.tiangolo.com/tutorial/server-sent-events/
- FastAPI, "Stream JSON Lines": https://fastapi.tiangolo.com/tutorial/stream-json-lines/
- FastAPI, "Request Files": https://fastapi.tiangolo.com/tutorial/request-files/
- FastAPI, "Middleware": https://fastapi.tiangolo.com/tutorial/middleware/
- FastAPI, "Additional Responses in OpenAPI": https://fastapi.tiangolo.com/advanced/additional-responses/
- FastAPI, "Additional Status Codes": https://fastapi.tiangolo.com/advanced/additional-status-codes/
- FastAPI, "Custom Response - HTML, Stream, File, others": https://fastapi.tiangolo.com/advanced/custom-response/
- FastAPI, "Return a Response Directly": https://fastapi.tiangolo.com/advanced/response-directly/
- FastAPI, "Response Headers": https://fastapi.tiangolo.com/advanced/response-headers/
- FastAPI, "Response Cookies": https://fastapi.tiangolo.com/advanced/response-cookies/
- FastAPI, "Response - Change Status Code": https://fastapi.tiangolo.com/advanced/response-change-status-code/
- FastAPI, "Stream Data": https://fastapi.tiangolo.com/advanced/stream-data/
- FastAPI, "Advanced Middleware": https://fastapi.tiangolo.com/advanced/middleware/
- FastAPI, "Lifespan Events": https://fastapi.tiangolo.com/advanced/events/
- FastAPI, "Advanced Dependencies": https://fastapi.tiangolo.com/advanced/advanced-dependencies/
- FastAPI reference, "Custom Response Classes": https://fastapi.tiangolo.com/reference/responses/
- FastAPI reference, "Exceptions": https://fastapi.tiangolo.com/reference/exceptions/
- FastAPI reference, "Static Files": https://fastapi.tiangolo.com/reference/staticfiles/
- FastAPI, "Release Notes": https://fastapi.tiangolo.com/release-notes/
- Starlette, "Responses": https://www.starlette.dev/responses/
- Starlette, "Exceptions": https://www.starlette.dev/exceptions/
- Starlette, "Middleware": https://www.starlette.dev/middleware/
- Starlette, "Requests": https://www.starlette.dev/requests/
- Starlette, "Static Files": https://www.starlette.dev/staticfiles/
- Starlette, "Release Notes": https://www.starlette.dev/release-notes/
- Uvicorn, "Settings": https://www.uvicorn.dev/settings/
- sse-starlette README: https://raw.githubusercontent.com/sysid/sse-starlette/main/README.md
- PyPI JSON, sse-starlette: https://pypi.org/pypi/sse-starlette/json
- PyPI JSON, orjson: https://pypi.org/pypi/orjson/json
- PyPI JSON, FastAPI: https://pypi.org/pypi/fastapi/json
- PyPI JSON, Starlette: https://pypi.org/pypi/starlette/json
- orjson README: https://raw.githubusercontent.com/ijl/orjson/master/README.md
- WHATWG HTML, "Server-sent events": https://html.spec.whatwg.org/multipage/server-sent-events.html
- MDN, "Using server-sent events": https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
- MDN, "Cache-Control": https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control
- MDN, "ETag": https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/ETag
- MDN, "Transfer-Encoding": https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Transfer-Encoding
- MDN, "304 Not Modified": https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/304
- RFC 9457, Problem Details for HTTP APIs: https://www.rfc-editor.org/rfc/rfc9457.txt
- RFC 9110, HTTP Semantics: https://www.rfc-editor.org/rfc/rfc9110.txt
- RFC 9112, HTTP/1.1: https://www.rfc-editor.org/rfc/rfc9112.txt
- Nginx,
ngx_http_proxy_module: https://nginx.org/en/docs/http/ngx_http_proxy_module.html - Python,
logging: https://docs.python.org/3/library/logging.html - Python,
contextvars: https://docs.python.org/3/library/contextvars.html - AnyIO, "Streams": https://anyio.readthedocs.io/en/stable/streams.html
- SQLAlchemy 2.0, "Core Exceptions": https://docs.sqlalchemy.org/en/20/core/exceptions.html
- SQLAlchemy 2.0, "ORM API Features for Querying": https://docs.sqlalchemy.org/en/20/orm/queryguide/api.html
- SQLModel, "Read One Model with FastAPI": https://sqlmodel.tiangolo.com/tutorial/fastapi/read-one/
- Alembic, "Operation Reference": https://alembic.sqlalchemy.org/en/latest/ops.html
- Laravel 13.x, "Error Handling": https://laravel.com/docs/13.x/errors
- Laravel 13.x, "HTTP Responses": https://laravel.com/docs/13.x/responses
- Laravel 13.x, "File Storage": https://laravel.com/docs/13.x/filesystem
- Go blog, "Working with Errors in Go 1.13": https://go.dev/blog/go1.13-errors
- Go source,
net/http/server.go: https://go.dev/src/net/http/server.go - Go source,
net/http/request.go: https://go.dev/src/net/http/request.go - Go source,
net/http/responsecontroller.go: https://go.dev/src/net/http/responsecontroller.go - Go source,
net/http/fs.go: https://go.dev/src/net/http/fs.go - Go 1.20 release notes: https://go.dev/doc/go1.20
- Laravel 13.x, "Eloquent: Getting Started": https://laravel.com/docs/13.x/eloquent
- Laravel 10.x, "Error Handling" (the
App\Exceptions\Handlerera): https://laravel.com/docs/10.x/errors - PHP manual, "FastCGI Process Manager (FPM)" configuration: https://www.php.net/manual/en/install.fpm.configuration.php
- Go source,
errors/wrap.go: https://go.dev/src/errors/wrap.go