Questions 61–80 of 100 · 0 of 20 on this page marked learned
61.fastapi-0061Easyfresher
How do multiple body parameters work in FastAPI, and what do Body() and embed=True change?
With one Pydantic model parameter, FastAPI expects the JSON body to be that model directly. With several model parameters it expects an object keyed by parameter name. Body(embed=True) forces the keyed form for a single model, and Body() lets singular values such as int or str come from the body instead of the query string. Embedding makes payloads extensible without breaking clients.
Full answer
Rules FastAPI follows:
One body model: def create(student: Student) expects {"name": "...", ...}.
Several body models: def enrol(student: Student, course: Course) expects {"student": {...}, "course": {...}}.
A scalar annotated with Body() is taken from the body, not the query: priority: Annotated[int, Body()] adds a key priority next to the models.
student: Annotated[Student, Body(embed=True)] expects {"student": {...}} even with a single model.
Parameters that are plain scalars without Body() are query parameters; parameters with the same name as a path variable are path parameters.
Why embed: starting with {"student": {...}} leaves room to add sibling keys later ("notify": true) without changing the shape clients send. Starting with the bare model and later adding a second body parameter changes the format for all clients, which is a breaking change.
Related tools:
Body(examples=[...]) documents payload examples in /docs.
Body(media_type="application/json") is the default; for form data use Form(), for files File() and UploadFile. A request body cannot mix JSON Body parameters with Form fields, because HTTP bodies carry one encoding.
GET requests technically allow bodies but many clients, proxies and caches do not handle them, so use POST (or query parameters) for searches.
The generated OpenAPI shows a combined schema for multiple body parameters. In tests, send the same keyed structure with client.post(url, json={...}).
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'student': 'Asha'}
{'student': 'Asha'}
422
{'student': 'Asha', 'course': 'DBMS', 'priority': 1}
{'student': 'Asha', 'course': 'DBMS', 'priority': 3}
['body', 'student']
Key points
One model: bare object; several models: keyed by parameter name
Body(embed=True) forces the keyed form
Body() makes a scalar come from the JSON body
Embedding keeps payloads extensible
Do not mix JSON body and Form fields
Common mistakes
Sending a bare object when several body parameters expect keys
Forgetting Body() and sending a scalar in the query string
Mixing Form fields with JSON body parameters
Changing from one to several body parameters and breaking clients
Using GET with a body
Follow-ups
How would you add a second body parameter without breaking existing clients?
How do you document request examples?
Can a request body mix JSON and files?
Tips
State the three shapes
Explain why embed helps
Mention Form vs JSON
62.fastapi-0062Easyfresher
What does ConfigDict do in a Pydantic v2 model, and how do extra='forbid', str_strip_whitespace, frozen and populate_by_name help in APIs?
model_config = ConfigDict(...) sets model-wide behaviour in Pydantic v2 (it replaces the v1 inner class Config). Useful options for APIs are extra="forbid" (reject unknown fields), str_strip_whitespace=True (trim strings), frozen=True (immutable, hashable instances), populate_by_name=True (accept both alias and field name), from_attributes=True (read ORM objects), and strict=True (no type coercion).
extra: "ignore" (default; unknown keys are silently dropped), "forbid" (422 on unknown keys, which catches client typos like nmae), "allow" (keep extras; avoid for input models).
str_strip_whitespace, str_to_lower, str_to_upper, str_min_length: normalise strings before constraints are checked.
frozen=True: instances cannot be modified (raises on assignment) and become hashable; good for value objects and config.
populate_by_name=True (or validate_by_name in newer releases): accept roll_no as well as the alias rollNo.
from_attributes=True: validate from objects with attributes (ORM rows).
validate_assignment=True: re-validate when attributes are set after creation (small performance cost).
strict=True: no coercion: "17" is rejected for an int. Usually too strict for query strings and form data, but good for JSON-only internal APIs.
use_enum_values, json_schema_extra (add examples to the OpenAPI schema), alias_generator=to_camel (convert snake_case fields to camelCase JSON).
protected_namespaces: fields beginning with model_ trigger warnings, so rename them or configure it.
Share config via a base class (class APIModel(BaseModel): model_config = ConfigDict(...)) and inherit it, so every schema has the same behaviour. In v1 this was class Config:, which still works but is deprecated.
python
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from pydantic.alias_generators import to_camel
class APIModel(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True, str_min_length=1,
alias_generator=to_camel, populate_by_name=True)
class StudentIn(APIModel):
full_name: str
roll_no: str = Field(pattern=r"^[A-Z]+-\d+$")
print(StudentIn.model_validate({"fullName": " Asha Rao ", "rollNo": "BCA-17"}))
print(StudentIn(full_name="Ravi", roll_no="BCA-2")) # populate_by_name allows Python names
print(StudentIn(full_name="Ravi", roll_no="BCA-2").model_dump(by_alias=True))
for bad in ({"fullName": "Asha", "rollNo": "BCA-1", "nmae": "typo"}, {"fullName": " ", "rollNo": "BCA-1"}):
try:
StudentIn.model_validate(bad)
except ValidationError as exc:
print([(e["loc"], e["type"]) for e in exc.errors()])
class Point(BaseModel):
model_config = ConfigDict(frozen=True)
x: int
y: int
p = Point(x=1, y=2)
print({p: "origin-ish"}[Point(x=1, y=2)])
try:
p.x = 5
except ValidationError as exc:
print(exc.errors()[0]["type"])
class Strict(BaseModel):
model_config = ConfigDict(strict=True)
age: int
try:
Strict(age="17")
except ValidationError as exc:
print(exc.errors()[0]["type"])
Standalone script. Run it with `python file.py`; it uses Pydantic only.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
full_name='Asha Rao' roll_no='BCA-17'
full_name='Ravi' roll_no='BCA-2'
{'fullName': 'Ravi', 'rollNo': 'BCA-2'}
[(('nmae',), 'extra_forbidden')]
[(('fullName',), 'string_too_short')]
origin-ish
frozen_instance
int_type
Key points
model_config = ConfigDict(...) replaces v1 class Config
extra='forbid' catches unknown fields and client typos
str_strip_whitespace normalises input
frozen makes instances immutable and hashable
Share configuration through a base model
Common mistakes
Leaving extra at 'ignore' on input models and silently dropping typos
Using strict=True for query or form data where everything arrives as strings
Using the deprecated class Config in new code
Naming fields with a model_ prefix without configuring protected_namespaces
Follow-ups
How does alias_generator=to_camel help a JavaScript client?
What does validate_assignment cost?
When is frozen useful?
Tips
Name 5 options
Explain extra='forbid'
Mention the base-class pattern
63.fastapi-0063Easyfresher
How do you set response headers, cookies and a different status code from inside a FastAPI path function?
Add a parameter typed Response (from fastapi) to the function, then set response.headers[...], call response.set_cookie(...) or delete_cookie(), and change response.status_code. FastAPI merges these into the final response while still serialising your return value with response_model. To control the whole response, return a Response subclass (JSONResponse, RedirectResponse) yourself.
Full answer
Two approaches:
Temporal Response parameter (keeps automatic JSON conversion and response_model filtering):
Return a response object: JSONResponse(content=..., status_code=202, headers={...}). This bypasses response_model validation and serialisation, so you must provide JSON-ready data (use jsonable_encoder for models and datetimes).
Cookies:
set_cookie(key, value, max_age, expires, path, domain, secure, httponly, samesite). Authentication cookies should be httponly=True (not readable by JavaScript), secure=True (HTTPS only) and samesite="lax" or "strict".
delete_cookie("session") sends an expired cookie (use the same path and domain).
Sign or encrypt cookies that carry data; browsers let users edit them.
Headers:
Use for Location on 201 responses, Cache-Control, ETag, Retry-After, Deprecation and Sunset, and custom X- headers. Header names are case-insensitive.
response.headers.append(...) for repeated headers; Set-Cookie can appear several times.
Status codes: set a default in the decorator (status_code=201) and override per request with response.status_code = 202 for conditional outcomes (for example 200 for update and 201 for create in an upsert).
Redirects: RedirectResponse(url, status_code=303) after form posts. CORS headers should come from CORSMiddleware, not by hand.
python
from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
app = FastAPI()
EXISTING = {"BCA-1"}
@app.put("/students/{roll_no}", status_code=200)
def upsert(roll_no: str, response: Response):
if roll_no not in EXISTING:
EXISTING.add(roll_no)
response.status_code = 201
response.headers["Location"] = f"/students/{roll_no}"
return {"roll_no": roll_no}
@app.post("/login")
def login(response: Response):
response.set_cookie("session", "abc123", httponly=True, secure=True, samesite="lax", max_age=3600)
response.headers["Cache-Control"] = "no-store"
return {"ok": True}
@app.post("/logout")
def logout(response: Response):
response.delete_cookie("session")
return {"ok": True}
@app.get("/accepted")
def accepted():
return JSONResponse({"queued": True}, status_code=202, headers={"Retry-After": "5"})
c = TestClient(app)
r = c.put("/students/BCA-1")
print(r.status_code, r.headers.get("location"))
r = c.put("/students/BCA-9")
print(r.status_code, r.headers.get("location"))
r = c.post("/login")
print(r.headers["set-cookie"].split("; ")[0], "|", [a for a in ("HttpOnly", "Secure", "SameSite=lax") if a in r.headers["set-cookie"]], "|", r.headers["cache-control"])
print(c.post("/logout").headers["set-cookie"].split(";")[0], "(expired)")
r = c.get("/accepted")
print(r.status_code, r.headers["retry-after"], r.json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
200 None
201 /students/BCA-9
session=abc123 | ['HttpOnly', 'Secure', 'SameSite=lax'] | no-store
session="" (expired)
202 5 {'queued': True}
Key points
Add a Response parameter to set headers, cookies and status
Returning a Response subclass bypasses response_model
Auth cookies: httponly, secure, samesite
delete_cookie must match path and domain
Set the default status in the decorator; override per request when needed
Common mistakes
Setting auth cookies without httponly, secure and samesite
Returning JSONResponse and expecting response_model to filter it
Deleting cookies with a different path or domain than they were set with
Setting CORS headers by hand instead of using CORSMiddleware
Follow-ups
How would you implement an upsert that returns 200 or 201?
How do you sign cookies?
What does jsonable_encoder do?
Tips
Show both approaches
List cookie flags
Mention Location on 201
64.fastapi-0064Easyfresher
How does FastAPI convert path, query and body values to Python types such as int, bool, UUID, date and datetime?
FastAPI reads the type hints on your function and Pydantic parses the raw strings or JSON values into those types: int and float from numeric strings, bool from true, 1, yes, on (and their opposites), UUID from canonical strings, date and datetime from ISO 8601, Decimal from numbers or strings, Enum from values, and lists or sets from repeated keys or arrays. Invalid values return 422, so your function only sees valid typed data.
Full answer
Because the signature says what the data should be, FastAPI does parsing, validation and documentation in one step:
UUID: accepts 36-character hyphenated strings (and a few other UUID forms); invalid text gives 422.
date and datetime: ISO 8601 (2026-12-04, 2026-12-04T10:30:00+05:30). A Z or offset yields an aware datetime; no offset yields a naive one. Store and compare UTC in your system, convert at the edges.
bool in query strings: true, false, 1, 0, yes, no, on, off (case-insensitive).
int and float: numeric strings are accepted in lax mode; "1.5" for an int is rejected, while 1.0 as a JSON number is accepted for int.
Decimal: use for money. When the value passes through a response model, Pydantic v2 serialises it as a JSON string ("199.90"), which keeps it exact. A bare Decimal inside a returned dict with no response model goes through jsonable_encoder and becomes a float (199.9), so declare a response model for money fields.
time, timedelta (ISO 8601 durations such as PT1H), bytes, Path, Enum, Literal, HttpUrl, EmailStr (needs email-validator).
Union types try members in "smart" order; avoid unions of overlapping scalars (int | str), which can surprise.
Return values are converted back to JSON: dates to ISO strings, UUID to string, Enum to its value. The function receives real Python objects, so you can compare dates, do arithmetic with Decimal and use uuid.version.
Gotchas: float binary rounding for money, naive vs aware datetimes in comparisons (TypeError), and time zones: ISO strings without offsets are ambiguous.
python
from datetime import date, datetime, timedelta
from decimal import Decimal
from enum import Enum
from uuid import UUID
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class Mode(str, Enum):
online = "online"
campus = "campus"
class Price(BaseModel):
amount: Decimal
@app.get("/price", response_model=Price)
def price_with_model():
return {"amount": Decimal("199.90")}
@app.get("/events/{event_id}")
def event(event_id: UUID, day: date, at: datetime | None = None, urgent: bool = False,
price: Decimal = Decimal("0"), length: timedelta = timedelta(hours=1), mode: Mode = Mode.online):
return {
"uuid_version": event_id.version,
"weekday": day.strftime("%A"),
"aware": at is not None and at.tzinfo is not None,
"urgent": urgent,
"price_type": type(price).__name__,
"minutes": length.total_seconds() / 60,
"mode": mode,
"price": price,
"day": day,
}
c = TestClient(app)
uid = "12345678-1234-4234-8234-123456789abc"
r = c.get(f"/events/{uid}", params={"day": "2026-12-04", "at": "2026-12-04T10:30:00+05:30", "urgent": "yes",
"price": "199.90", "length": "PT90M", "mode": "campus"})
print(r.json())
print(c.get(f"/events/{uid}", params={"day": "2026-12-04", "urgent": "off"}).json()["urgent"])
for bad in ({"day": "04-12-2026"}, {"day": "2026-12-04", "urgent": "maybe"}):
err = c.get(f"/events/{uid}", params=bad).json()["detail"][0]
print(err["loc"], err["type"])
print(c.get("/price").text)
print(c.get("/events/not-a-uuid", params={"day": "2026-12-04"}).json()["detail"][0]["type"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'uuid_version': 4, 'weekday': 'Friday', 'aware': True, 'urgent': True, 'price_type': 'Decimal', 'minutes': 90.0, 'mode': 'campus', 'price': 199.9, 'day': '2026-12-04'}
False
['query', 'day'] date_from_datetime_parsing
['query', 'urgent'] bool_parsing
{"amount":"199.90"}
uuid_parsing
Key points
Type hints drive parsing, validation and docs
bool accepts true/false/1/0/yes/no/on/off
datetime with an offset is aware; without it is naive
Decimal for money; a response model keeps it exact as a string
Invalid values give 422 before your code runs
Common mistakes
Using float for money, or returning Decimal values without a response model so they become floats
Comparing naive and aware datetimes
Accepting ISO strings without offsets and assuming a time zone
Using unions of overlapping scalar types such as int | str
Doing manual parsing that duplicates what the signature already does
Follow-ups
How do you accept a custom date format?
How do you validate time zones?
What does smart union mode do?
Tips
Give 5 types and their accepted inputs
Mention naive vs aware
Mention Decimal for money
65.fastapi-0065Easyfresher
What is ASGI, how do Starlette and FastAPI relate to it, and what does an ASGI application look like?
ASGI (Asynchronous Server Gateway Interface) is the standard between Python async web servers (Uvicorn, Hypercorn, Daphne) and applications. An ASGI app is an async callable app(scope, receive, send): the server passes a dict describing the connection and two awaitable channels for messages. Starlette is a toolkit that implements routing, requests, responses, middleware and WebSockets on ASGI, and FastAPI subclasses Starlette to add typed parameters, validation, dependency injection and OpenAPI.
Full answer
WSGI (Flask, classic Django) handles one request per call synchronously and has no WebSocket support. ASGI is its async successor: it supports concurrent requests, WebSockets, long-lived connections, and server-sent events.
scope["type"] is "http", "websocket" or "lifespan" (start-up and shutdown events).
receive() yields incoming messages (http.request with body chunks, websocket.receive, http.disconnect).
send(message) writes response messages.
Layers:
Server: Uvicorn parses HTTP, manages sockets, and calls the app. (Gunicorn can run Uvicorn workers.)
Middleware: wrappers that take an ASGI app and return an ASGI app (CORS, GZip, sessions). Starlette's BaseHTTPMiddleware is a convenience; pure ASGI middleware is faster and more flexible.
Starlette: Request, Response, Router, Mount, WebSocket, StaticFiles, BackgroundTask, lifespan handling.
FastAPI: builds Starlette routes from typed functions, validates with Pydantic, resolves Depends, and generates OpenAPI.
Implications: a FastAPI() instance is itself an ASGI app, so it can be mounted inside another app, wrapped by middleware or called directly in tests; sync def endpoints run in a thread pool, async def endpoints run on the event loop; and anything blocking inside async def stalls all requests on that worker.
python
import asyncio
from fastapi import FastAPI
async def raw_asgi_app(scope, receive, send):
assert scope["type"] == "http"
await send({"type": "http.response.start", "status": 200, "headers": [(b"content-type", b"text/plain")]})
await send({"type": "http.response.body", "body": b"hello from a raw ASGI app"})
app = FastAPI()
@app.get("/students")
def students():
return ["Asha"]
async def call(asgi_app, path):
scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", "scheme": "http",
"path": path, "raw_path": path.encode(), "query_string": b"", "headers": [], "server": ("testserver", 80),
"client": ("127.0.0.1", 1234), "root_path": ""}
sent = []
async def receive():
return {"type": "http.request", "body": b"", "more_body": False}
async def send(message):
sent.append(message)
await asyncio.wait_for(asgi_app(scope, receive, send), timeout=5)
start = sent[0]
body = b"".join(m.get("body", b"") for m in sent[1:])
return start["status"], body
print(asyncio.run(call(raw_asgi_app, "/")))
print(asyncio.run(call(app, "/students"))) # FastAPI is itself an ASGI callable
print(asyncio.run(call(app, "/nope")))
from starlette.routing import Mount
app.router.routes.append(Mount("/legacy", app=raw_asgi_app)) # mount a raw ASGI app inside FastAPI
print(asyncio.run(call(app, "/legacy/")))
Standalone script. Run it with `python file.py`; it calls the ASGI apps directly with a hand-built scope, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
(200, b'hello from a raw ASGI app')
(200, b'["Asha"]')
(404, b'{"detail":"Not Found"}')
(200, b'hello from a raw ASGI app')
Key points
ASGI is the async server-application interface: app(scope, receive, send)
Scope types: http, websocket, lifespan
Starlette provides the toolkit; FastAPI adds typing, validation, DI and OpenAPI
A FastAPI app is an ASGI callable and can be wrapped or mounted
Blocking inside async def stalls the event loop
Common mistakes
Confusing WSGI and ASGI servers
Running blocking code inside async def and freezing the event loop
Thinking FastAPI replaces the server: Uvicorn or similar is still required
Using BaseHTTPMiddleware for performance-critical paths without considering pure ASGI
Follow-ups
What is the lifespan scope for?
How does Uvicorn differ from Gunicorn?
What are the downsides of BaseHTTPMiddleware?
Tips
Write the three-argument signature
Describe the layers
Say what blocking does
66.fastapi-0066Easyfresher
What is the difference between a return type annotation, response_model, and returning a Response directly in FastAPI?
A return annotation (-> StudentPublic) is the modern way to declare the response model: FastAPI validates and filters the returned data and documents the schema from it. The response_model parameter does the same and takes priority when both exist, which helps when the function returns a richer type than the API exposes. Returning a Response object (JSONResponse, HTMLResponse, FileResponse) bypasses validation and serialisation entirely and is used for custom bodies, streams and files.
Full answer
Three mechanisms, increasing control and decreasing automation:
Return annotation: def read() -> StudentPublic:. FastAPI treats it as the response model (since 0.89), so type checkers and the API contract agree.
response_model=StudentPublic: explicit; use when the function returns something else (an ORM object, a dict, a StudentInDB subclass) that must be filtered down. If both are present, response_model wins, which makes patterns like returning StudentInDB while publishing StudentPublic possible, with -> StudentInDB for type checkers.
Return a Response subclass: no validation, no filtering, no docs inference. Provide response_class or responses= so OpenAPI still describes it, or set response_model=None to disable inference from the annotation (needed when the annotation is Response | dict).
What happens in 1 and 2: FastAPI validates the return value against the model (a bug in your function becomes a 500 ResponseValidationError, not silent bad output), removes extra fields (hiding secrets), serialises with Pydantic's JSON encoder (dates, UUIDs, Decimals handled), and publishes the JSON schema.
Use direct responses for: FileResponse and StreamingResponse, RedirectResponse, custom status and headers in one go, HTMLResponse, and performance-sensitive cases where you pre-serialised JSON bytes.
Cost note: validation and serialisation of big payloads takes time. For very hot endpoints, return exactly the right shape and measure whether skipping the model matters, but do not trade away filtering for sensitive data.
Responses for other status codes (404, 409) are documented with responses={404: {"model": ErrorOut}}; they are not enforced at runtime.
python
from fastapi import FastAPI
from fastapi.responses import JSONResponse, PlainTextResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
class StudentPublic(BaseModel):
name: str
class StudentInDB(StudentPublic):
password_hash: str
@app.get("/annotated")
def annotated() -> StudentPublic:
return StudentPublic(name="Asha")
@app.get("/filtered", response_model=StudentPublic)
def filtered() -> StudentInDB: # the response_model wins: the hash is removed
return StudentInDB(name="Ravi", password_hash="x1y2")
@app.get("/direct", response_model=None)
def direct() -> JSONResponse | dict:
return JSONResponse({"name": "Kiran", "password_hash": "not filtered"}, status_code=202)
@app.get("/text", response_class=PlainTextResponse)
def text():
return "plain text body"
@app.get("/buggy", response_model=StudentPublic)
def buggy():
return {"nickname": "no name field"}
c = TestClient(app, raise_server_exceptions=False)
for path in ("annotated", "filtered", "direct", "text"):
r = c.get(f"/{path}")
print(path, r.status_code, r.text.strip())
print("buggy", c.get("/buggy").status_code)
schemas = c.get("/openapi.json").json()["components"]["schemas"]
print(sorted(schemas))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
annotated 200 {"name":"Asha"}
filtered 200 {"name":"Ravi"}
direct 202 {"name":"Kiran","password_hash":"not filtered"}
text 200 plain text body
buggy 500
['StudentPublic']
Key points
Return annotation acts as the response model
response_model wins and can filter a richer return type
Returning a Response bypasses validation and filtering
Response validation failures are 500 server errors
Document extra statuses with responses=; they are not enforced
Common mistakes
Returning ORM objects with private fields and no response model
Expecting responses={404: ...} to validate or enforce error bodies
Returning a Response and forgetting that nothing is filtered
Leaving the annotation as Response | dict without response_model=None
Follow-ups
What happens if the function returns data that does not match response_model?
How do you document multiple response statuses?
When would you skip response validation for speed?
Tips
Rank the three mechanisms
Explain filtering benefit
Mention response_model=None
67.fastapi-0067Easyfresher
How do APIKeyHeader, HTTPBearer and HTTPBasic work in FastAPI, and how do they appear in the OpenAPI docs?
FastAPI provides security scheme classes in fastapi.security. APIKeyHeader reads a key from a header, HTTPBearer reads Authorization: Bearer <token>, and HTTPBasic reads username and password. Use them as dependencies: they extract the credential (and return 401 or 403 when missing), you verify it, and they register the scheme in OpenAPI so the /docs page gets an Authorize button. They only read credentials; verification is your code, and secrets must be compared in constant time.
Full answer
Pattern:
python
api_key = APIKeyHeader(name="X-API-Key", auto_error=False)
def require_key(key: Annotated[str | None, Security(api_key)]):
if key is None or not secrets.compare_digest(key, EXPECTED):
raise HTTPException(status_code=401, detail="Invalid API key", headers={"WWW-Authenticate": "ApiKey"})
Schemes:
APIKeyHeader, APIKeyQuery, APIKeyCookie: simple keys for service-to-service calls. Prefer headers; query keys leak into logs.
HTTPBearer: returns HTTPAuthorizationCredentials with .scheme and .credentials (the token). Combine with JWT validation or an opaque token lookup.
HTTPBasic: HTTPBasicCredentials with .username and .password; the client sends them base64-encoded (not encrypted), so use only over HTTPS and compare with secrets.compare_digest to avoid timing leaks.
OAuth2PasswordBearer: for the OAuth2 password flow with a token URL (covered separately).
Behaviour details:
auto_error=True (default) makes a missing credential raise automatically. Current FastAPI answers 401 with a WWW-Authenticate header (APIKey, Bearer or Basic); older releases answered 403 for API keys and Bearer, so check your version when writing tests. Set auto_error=False when you want to handle it yourself or chain several schemes.
Using Security() instead of Depends() records scopes for OAuth2, and both register the scheme in OpenAPI.
Apply to a whole router with dependencies=[Depends(require_key)].
/docs shows an Authorize dialog; the credential is stored in the browser page and sent on "Try it out".
Security basics: store only hashed API keys (like passwords), support rotation, scope keys to least privilege, rate-limit failures, and never log credentials.
python
import secrets
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Security
from fastapi.security import APIKeyHeader, HTTPAuthorizationCredentials, HTTPBasic, HTTPBasicCredentials, HTTPBearer
from fastapi.testclient import TestClient
app = FastAPI()
api_key = APIKeyHeader(name="X-API-Key", auto_error=False)
bearer = HTTPBearer(auto_error=False)
basic = HTTPBasic(auto_error=False)
KEY, TOKEN = "k-123", "t-456"
def key_guard(key: Annotated[str | None, Security(api_key)]):
if key is None or not secrets.compare_digest(key, KEY):
raise HTTPException(status_code=401, detail="Invalid API key")
return "service"
def bearer_guard(creds: Annotated[HTTPAuthorizationCredentials | None, Security(bearer)]):
if creds is None or not secrets.compare_digest(creds.credentials, TOKEN):
raise HTTPException(status_code=401, detail="Invalid token", headers={"WWW-Authenticate": "Bearer"})
return "token-user"
def basic_guard(creds: Annotated[HTTPBasicCredentials | None, Security(basic)]):
ok = creds is not None and secrets.compare_digest(creds.username, "teacher") and secrets.compare_digest(creds.password, "pw")
if not ok:
raise HTTPException(status_code=401, detail="Bad credentials", headers={"WWW-Authenticate": "Basic"})
return creds.username
@app.get("/key")
def by_key(who: Annotated[str, Depends(key_guard)]):
return {"who": who}
@app.get("/bearer")
def by_bearer(who: Annotated[str, Depends(bearer_guard)]):
return {"who": who}
@app.get("/basic")
def by_basic(who: Annotated[str, Depends(basic_guard)]):
return {"who": who}
c = TestClient(app)
print(c.get("/key", headers={"X-API-Key": KEY}).json(), c.get("/key").status_code)
print(c.get("/bearer", headers={"Authorization": f"Bearer {TOKEN}"}).json(), c.get("/bearer", headers={"Authorization": "Bearer bad"}).status_code)
print(c.get("/basic", auth=("teacher", "pw")).json(), c.get("/basic", auth=("teacher", "no")).headers["www-authenticate"])
print(sorted(c.get("/openapi.json").json()["components"]["securitySchemes"]))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'who': 'service'} 401
{'who': 'token-user'} 401
{'who': 'teacher'} Basic
['APIKeyHeader', 'HTTPBasic', 'HTTPBearer']
Key points
Security classes extract credentials; your code verifies them
APIKeyHeader, HTTPBearer and HTTPBasic cover common schemes
Use secrets.compare_digest for secret comparison
They add an Authorize button to /docs via OpenAPI
Store API keys hashed and support rotation
Common mistakes
Comparing secrets with == instead of compare_digest
Putting API keys in query strings
Storing API keys in plain text
Sending Basic credentials over plain HTTP
Assuming the security class verifies the credential
Follow-ups
How do you support several auth schemes on one endpoint?
How does OAuth2PasswordBearer differ from HTTPBearer?
How would you rotate API keys without downtime?
Tips
Say extraction vs verification
Mention compare_digest
Mention OpenAPI Authorize
68.fastapi-0068Mediummid
How do field_serializer, computed_field and model_serializer shape output in Pydantic v2 and FastAPI responses?
field_serializer customises how one field is written (for example formatting a datetime or masking an email), computed_field adds a derived property to the output and JSON schema, and model_serializer takes over serialisation of the whole model. Each can apply in all modes or only mode="json". FastAPI uses them when serialising response models, so API output can differ from internal representation without extra code in endpoints.
Full answer
Validation turns input into Python objects; serialisation turns objects into output. v2 gives hooks for the second half.
computed_field on a @property adds full_name to model_dump(), JSON output and the OpenAPI schema (marked read-only in serialisation mode). The return annotation is used for the schema.
field_serializer receives the value (and optionally info); when_used can be "always", "json", "json-unless-none" or "unless-none". Use it for presentation concerns such as masking, rounding and date formats.
model_serializer replaces the whole dump: return a dict (plain mode) or wrap the default (mode="wrap", receiving a handler) to add or drop keys conditionally.
serialization_alias and Field(exclude=True) remove or rename fields without functions.
In FastAPI, response models separate this from storage: the database model holds raw data, the response model formats it. Cautions: serializers run on every response, so keep them cheap; do not hide security-critical data only with a serializer on a shared model (use a separate response model); and remember response_model_exclude_unset interacts with computed fields (they are always included).
Because FastAPI documents the response model, clients see computed fields in generated types. Serialisers do not affect validation, so round trips (response fed back as request) need matching input models.
python
from datetime import date
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, computed_field, field_serializer, model_serializer
app = FastAPI()
class StudentOut(BaseModel):
first: str
last: str
email: str
born: date
internal_note: str = ""
@computed_field
@property
def full_name(self) -> str:
return f"{self.first} {self.last}"
@field_serializer("email")
def mask_email(self, value: str) -> str:
name, _, domain = value.partition("@")
return f"{name[0]}***@{domain}"
@field_serializer("born", when_used="json")
def born_as_text(self, value: date) -> str:
return value.strftime("%d %b %Y")
@model_serializer(mode="wrap")
def drop_empty_notes(self, handler):
data = handler(self)
if not data.get("internal_note"):
data.pop("internal_note", None)
return data
@app.get("/student", response_model=StudentOut)
def student():
return {"first": "Asha", "last": "Rao", "email": "asha@example.com", "born": date(2009, 3, 4)}
s = StudentOut(first="Ravi", last="Iyer", email="ravi@example.com", born=date(2008, 1, 9))
print(s.model_dump())
print(s.model_dump(mode="json"))
c = TestClient(app)
print(c.get("/student").json())
schema = c.get("/openapi.json").json()["components"]["schemas"]["StudentOut"]
print(sorted(schema["properties"]), schema["properties"]["full_name"].get("readOnly"))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'first': 'Ravi', 'last': 'Iyer', 'email': 'r***@example.com', 'born': datetime.date(2008, 1, 9), 'full_name': 'Ravi Iyer'}
{'first': 'Ravi', 'last': 'Iyer', 'email': 'r***@example.com', 'born': '09 Jan 2008', 'full_name': 'Ravi Iyer'}
{'first': 'Asha', 'last': 'Rao', 'email': 'a***@example.com', 'born': '04 Mar 2009', 'full_name': 'Asha Rao'}
['born', 'email', 'first', 'full_name', 'internal_note', 'last'] True
Key points
field_serializer formats or masks one field
computed_field adds derived output and schema
model_serializer controls the whole dump; wrap mode adds or removes keys
when_used limits a serializer to JSON mode
Use separate response models for security-critical hiding
Common mistakes
Hiding secrets with a serializer on a model that is also used elsewhere
Expensive work inside serializers that run on every response
Expecting serializers to change validation of incoming data
Forgetting that computed fields appear in the schema and clients rely on them
Follow-ups
How does model_serializer(mode='wrap') differ from plain mode?
How do you exclude a field only in responses?
How do computed fields appear in OpenAPI?
Tips
Name the three tools
Explain when_used
Separate storage and response models
69.fastapi-0069Mediummid
How do you build reusable validated types in Pydantic v2 with Annotated, AfterValidator and BeforeValidator?
Annotated[base_type, Validator(...)] attaches validation to a type instead of a model, so the same rule is reused across fields and models. AfterValidator runs after Pydantic's own parsing (receives the typed value), BeforeValidator runs before it (receives raw input and can normalise), PlainValidator replaces parsing, and WrapValidator surrounds it. Raise ValueError or AssertionError to report failure.
Full answer
Instead of repeating @field_validator in every model, define the rule once:
python
def normalise_roll(v: str) -> str:
return v.strip().upper()
def check_roll(v: str) -> str:
if not re.fullmatch(r"[A-Z]{2,4}-\d{1,5}", v):
raise ValueError("roll number must look like BCA-123")
return v
RollNo = Annotated[str, BeforeValidator(str.strip), AfterValidator(normalise_roll), AfterValidator(check_roll)]
Then roll_no: RollNo anywhere, including list items (list[RollNo]), query parameters and Annotated[..., Query()] function parameters in FastAPI.
Validator kinds:
BeforeValidator(func): runs first with the raw value (could be int, None, a list). Good for coercions like "split comma-separated string into a list" or stripping.
AfterValidator(func): runs after the standard validation, so func can rely on the type being correct. Most checks belong here.
PlainValidator(func): replaces the built-in parsing (no type check); use rarely.
WrapValidator(func): receives (value, handler), can call handler(value) inside try/except or skip it.
Order: validators in an Annotated run in a defined order: Before and Wrap validators from right to left, After validators left to right (check the documentation for the exact order when mixing). Test the combination.
Errors: raising ValueError produces a value_error entry in the 422 body with the message; PydanticCustomError("code", "message {x}", {"x": 1}) gives custom type codes. AssertionError also works, although asserts disappear under python -O, so prefer ValueError.
Compared with field_validator: the Annotated form travels with the type (shared rules), while field_validator lives in the model (model-specific rules or rules needing other fields via info.data). Combine both. Reusable types also keep OpenAPI constraints if you use Field(pattern=...) inside the Annotated metadata, which a function validator cannot express.
python
import re
from typing import Annotated
from fastapi import FastAPI, Query
from fastapi.testclient import TestClient
from pydantic import AfterValidator, BaseModel, BeforeValidator, ValidationError
def check_roll(v: str) -> str:
if not re.fullmatch(r"[A-Z]{2,4}-\d{1,5}", v):
raise ValueError("roll number must look like BCA-123")
return v
def split_csv(v):
return [p.strip() for p in v.split(",") if p.strip()] if isinstance(v, str) else v
RollNo = Annotated[str, BeforeValidator(str.strip), AfterValidator(str.upper), AfterValidator(check_roll)]
RollNos = Annotated[list[RollNo], BeforeValidator(split_csv)]
class Enrolment(BaseModel):
roll_no: RollNo
friends: RollNos = []
print(Enrolment(roll_no=" bca-17 "))
print(Enrolment(roll_no="BCA-1", friends="ca-2, ca-3"))
try:
Enrolment(roll_no="17-BCA")
except ValidationError as exc:
print([(e["loc"], e["type"], e["msg"]) for e in exc.errors()])
app = FastAPI()
@app.get("/lookup")
def lookup(roll_no: Annotated[RollNo, Query()], others: Annotated[RollNos, Query()] = []):
return {"roll_no": roll_no, "others": others}
c = TestClient(app)
print(c.get("/lookup", params={"roll_no": " bca-9"}).json())
print(c.get("/lookup", params={"roll_no": "bad"}).json()["detail"][0]["msg"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
roll_no='BCA-17' friends=[]
roll_no='BCA-1' friends=['CA-2', 'CA-3']
[(('roll_no',), 'value_error', 'Value error, roll number must look like BCA-123')]
{'roll_no': 'BCA-9', 'others': []}
Value error, roll number must look like BCA-123
Key points
Annotated types attach validation to a type for reuse
Before runs on raw input; After on the typed value
Raise ValueError (not assert) to fail
Works for list items, models and FastAPI parameters
Use Field constraints in Annotated when you want them in OpenAPI
Common mistakes
Repeating the same field_validator in many models
Using assert for validation
Putting checks that assume a type in a Before validator
Expecting a function validator to add constraints to the OpenAPI schema
Follow-ups
What is the order of multiple validators in Annotated?
How do you raise a custom error type?
When would you use WrapValidator?
Tips
Contrast Before and After
Show a reusable type used in several places
Mention OpenAPI limitation
70.fastapi-0070Mediummid
How do you replace dependencies such as the database, current user or external clients in FastAPI tests with app.dependency_overrides?
app.dependency_overrides is a dict mapping an original dependency callable to a replacement. Inside a test, set overrides[get_db] = fake_get_db (and clear it afterwards) so endpoints use test doubles without patching modules. Overrides apply to the whole dependency tree, including sub-dependencies, are keyed by the exact function object, and should be reset with a fixture so tests stay independent.
Full answer
Because FastAPI resolves Depends(get_current_user) at request time, tests can swap what runs without touching endpoint code:
The key must be the same function object used in Depends(...). Overriding a function re-imported under another name does nothing.
The replacement may have its own dependencies and its own signature (parameters are resolved normally), including yield for setup and teardown.
Typical overrides: database session (test database or transaction), authenticated user (skip real login), settings (get_settings), outbound clients (fake payment gateway), time or ID generators.
In pytest, wrap in a fixture so cleanup always happens:
python
@pytest.fixture
def client():
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
Overrides replace the dependency but not its decorators (like lru_cache on get_settings; clear caches if needed), and router-level dependencies=[Depends(x)] are overridden the same way.
Security dependencies (OAuth2PasswordBearer) can be overridden to bypass tokens: override the dependency that returns the user, and keep a few tests that go through real authentication.
For parallel test runs, remember dependency_overrides is global to the app object; create the app with a factory (create_app()) per test or process.
Alternatives: unittest.mock.patch works but couples tests to import paths; dependency overrides are the supported mechanism and keep tests independent of how modules are laid out.
python
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
app = FastAPI()
class RealMailer:
def send(self, to, text):
raise RuntimeError("real SMTP must not be called in tests")
def get_mailer():
return RealMailer()
def get_current_user() -> dict:
raise HTTPException(status_code=401, detail="Not authenticated")
@app.post("/receipts/{roll_no}")
def send_receipt(roll_no: str, user: Annotated[dict, Depends(get_current_user)],
mailer: Annotated[RealMailer, Depends(get_mailer)]):
mailer.send(f"{roll_no}@example.com", "fee received")
return {"sent_by": user["name"], "to": roll_no}
class FakeMailer:
def __init__(self):
self.outbox = []
def send(self, to, text):
self.outbox.append((to, text))
c = TestClient(app)
print("no override:", c.post("/receipts/BCA-1").status_code)
fake = FakeMailer()
app.dependency_overrides[get_current_user] = lambda: {"name": "teacher"}
app.dependency_overrides[get_mailer] = lambda: fake
print(c.post("/receipts/BCA-1").json(), fake.outbox)
app.dependency_overrides.clear()
print("after clear:", c.post("/receipts/BCA-1").status_code)
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
no override: 401
{'sent_by': 'teacher', 'to': 'BCA-1'} [('BCA-1@example.com', 'fee received')]
after clear: 401
Key points
dependency_overrides maps original dependency to replacement
Key must be the exact function used in Depends
Replacement can have its own dependencies and yield
Use a fixture to clear overrides after each test
Keep a few tests that use real authentication
Common mistakes
Forgetting to clear overrides, leaking state into other tests
Overriding a function object that is not the one used in Depends
Overriding authentication everywhere and never testing the real login path
Sharing one app object across parallel tests with different overrides
Follow-ups
How do you test a dependency that uses yield?
How do you override a router-level dependency?
Why prefer overrides to mock.patch?
Tips
Show the dict and the fixture
Say key equals function object
Mention tests with real auth
71.fastapi-0071Mediummid
How do Alembic migrations work with SQLAlchemy in a FastAPI project: autogenerate, upgrade, downgrade, and what must you review?
Alembic keeps a chain of revision scripts, each with upgrade() and downgrade(), and records the current revision in the alembic_version table. alembic revision --autogenerate compares your SQLAlchemy metadata with the live database and drafts operations; you must review them because autogenerate misses renames, some constraints and data changes. alembic upgrade head applies pending revisions, and downgrade moves back. SQLite needs batch mode for many ALTERs.
Full answer
Workflow:
alembic init migrations creates alembic.ini and migrations/env.py. In env.py set target_metadata = Base.metadata and read the database URL from your settings, not from the ini file.
Change models, then alembic revision --autogenerate -m "add email". Alembic connects, reflects the database, diffs it against target_metadata, and writes versions/<rev>_add_email.py with op.add_column(...) etc.
Review the file: autogenerate cannot detect table or column renames (it sees drop and add, which loses data), often misses changes to server defaults, check constraints and enum types, and never moves data.
alembic upgrade head applies revisions; alembic downgrade -1 reverts one; alembic current, alembic history and alembic upgrade head --sql (offline SQL for DBAs) help operations.
Rules of thumb:
The database must be at the latest revision before generating a new one, or Alembic reports "Target database is not up to date".
Revisions form a linear chain through down_revision; two branches create multiple heads and alembic merge is needed.
Import all models in env.py (or in the package it imports) so that Base.metadata is complete.
Write real downgrade() functions or consciously raise in them; test upgrade and downgrade in CI against a clean database.
SQLite supports few ALTER statements. Set render_as_batch=True in context.configure so Alembic emits batch_alter_table, which recreates the table.
Zero-downtime changes follow expand and contract: add nullable column, deploy code that writes it, backfill in batches, then add constraints (on PostgreSQL use NOT VALID then VALIDATE, and create indexes CONCURRENTLY outside a transaction).
Run migrations as a deploy step, not at app start-up with several replicas racing.
Naming conventions for constraints (MetaData(naming_convention=...)) make later drops and renames predictable.
python
import contextlib
import io
import os
import sqlite3
import sys
import tempfile
from pathlib import Path
from alembic import command
from alembic.config import Config
work = Path(tempfile.mkdtemp())
sys.path.insert(0, str(work))
db_path = work / "app.db"
(work / "models.py").write_text("""import os
from sqlalchemy import Column, Integer, MetaData, String, Table
def build_metadata():
md = MetaData()
columns = [Column("id", Integer, primary_key=True), Column("name", String(40), nullable=False)]
if os.environ.get("SCHEMA_STAGE") == "2":
columns.append(Column("email", String(80)))
Table("student", md, *columns)
return md
""")
cfg = Config(str(work / "alembic.ini"))
cfg.set_main_option("script_location", str(work / "migrations"))
cfg.set_main_option("sqlalchemy.url", f"sqlite:///{db_path}")
quiet = contextlib.redirect_stdout(io.StringIO()) # Alembic prints temporary paths; keep the output stable
with quiet:
command.init(cfg, str(work / "migrations"))
(work / "migrations" / "env.py").write_text("""import models
from alembic import context
from sqlalchemy import create_engine
config = context.config
engine = create_engine(config.get_main_option("sqlalchemy.url"))
with engine.connect() as connection:
context.configure(connection=connection, target_metadata=models.build_metadata(), render_as_batch=True)
with context.begin_transaction():
context.run_migrations()
""")
def columns():
with sqlite3.connect(db_path) as conn:
return [row[1] for row in conn.execute("PRAGMA table_info(student)")]
with quiet:
command.revision(cfg, message="create student", autogenerate=True, rev_id="0001")
command.upgrade(cfg, "head")
print("after 0001:", columns())
os.environ["SCHEMA_STAGE"] = "2" # the model gained a column
with quiet:
command.revision(cfg, message="add email", autogenerate=True, rev_id="0002")
print(sorted(p.name for p in (work / "migrations" / "versions").glob("0*.py")))
generated = (work / "migrations" / "versions" / "0002_add_email.py").read_text()
print([line.strip() for line in generated.splitlines() if "add_column" in line or "batch_alter_table" in line or "drop_column" in line])
with quiet:
command.upgrade(cfg, "head")
print("after 0002:", columns())
with quiet:
command.downgrade(cfg, "-1")
print("after downgrade:", columns())
Standalone script. Run it with `python file.py`; it uses Alembic's command API with a temporary SQLite database. Requires `pip install alembic sqlalchemy`.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0, alembic 1.20.1):
after 0001: ['id', 'name']
['0001_create_student.py', '0002_add_email.py']
["with op.batch_alter_table('student', schema=None) as batch_op:", "batch_op.add_column(sa.Column('email', sa.String(length=80), nullable=True))", "with op.batch_alter_table('student', schema=None) as batch_op:", "batch_op.drop_column('email')"]
after 0002: ['id', 'name', 'email']
after downgrade: ['id', 'name']
Key points
Revision chain with upgrade and downgrade; alembic_version tracks state
Autogenerate drafts; review for renames, defaults and data
Database must be current before generating the next revision
SQLite needs batch mode; set render_as_batch
Run migrations as a deploy step; test both directions
Common mistakes
Trusting autogenerate without reading the generated file
Renaming a column in the model and shipping the drop and add that autogenerate produces
Generating a revision while the database is behind the latest revision
Running migrations from every app replica at start-up
Skipping batch mode on SQLite and getting unsupported ALTER errors
Follow-ups
How do you handle two developers creating revisions from the same parent?
How do you run a data migration safely?
How do you create an index concurrently on PostgreSQL?
Tips
Describe the workflow in four steps
Name autogenerate blind spots
Mention expand and contract
72.fastapi-0072Mediummid
How do you avoid the N+1 query problem with SQLAlchemy relationships in FastAPI, and how do nested response models interact with lazy loading?
By default SQLAlchemy loads related rows lazily: touching student.class_room inside a list loop issues one query per row. When a response model reads those attributes during serialisation, the hidden queries multiply. Fix it by choosing a loader strategy in the query: selectinload (a second query using IN, best for collections), joinedload (a JOIN, good for many-to-one), or lazy="raise" to catch accidental lazy loads. Always verify with a query counter.
Full answer
The problem in FastAPI: your endpoint returns ORM objects and the response model includes class_room: ClassRoomOut. Serialisation touches student.class_room for each student after your function returned, so each access lazy-loads. 100 students become 101 queries. With async sessions it is worse: lazy loading raises MissingGreenlet.
Fixes (sqlalchemy.orm):
selectinload(Student.marks): runs one extra SELECT ... WHERE student_id IN (...), avoiding row multiplication. Best for one-to-many and many-to-many collections.
joinedload(Student.class_room): adds a LEFT OUTER JOIN to the main query. Good for many-to-one and one-to-one; with collections it multiplies rows (use .unique() on results).
subqueryload (older), contains_eager (when you already joined and filtered), raiseload("*") or lazy="raise" to turn accidental lazy loads into errors during development.
Load only needed columns with load_only(...) when rows are wide.
Practice:
Decide per endpoint which relations the response needs; put the options in the query in the repository or service, not in model defaults (a global lazy="joined" hurts other queries).
Return a response model matching what you loaded; do not include relations you did not load.
Count queries in tests: SQLAlchemy's before_cursor_execute event, or a fixture that asserts at most N statements, protects against regressions.
Paginate before joining collections; a LIMIT with a joined collection applies to joined rows unless SQLAlchemy wraps it in a subquery (it does for joinedload with limits, at some cost).
Use from_attributes=True models so Pydantic reads loaded attributes.
Know the identity map: a lazy many-to-one load first checks the session's identity map, so repeated parents are fetched once (the snippet shows 2 room queries for 6 students), while collection lazy loads such as student.marks always query once per parent.
For aggregates (counts per class) use SQL GROUP BY instead of loading collections.
python
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict
from sqlalchemy import ForeignKey, create_engine, event, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, joinedload, mapped_column, relationship, selectinload, sessionmaker
from sqlalchemy.pool import StaticPool
class Base(DeclarativeBase):
pass
class ClassRoom(Base):
__tablename__ = "class_room"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
students: Mapped[list["Student"]] = relationship(back_populates="class_room")
class Student(Base):
__tablename__ = "student"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
class_room_id: Mapped[int] = mapped_column(ForeignKey("class_room.id"))
class_room: Mapped[ClassRoom] = relationship(back_populates="students")
marks: Mapped[list["Mark"]] = relationship()
class Mark(Base):
__tablename__ = "mark"
id: Mapped[int] = mapped_column(primary_key=True)
student_id: Mapped[int] = mapped_column(ForeignKey("student.id"))
score: Mapped[int]
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
SessionLocal = sessionmaker(engine)
statements = []
event.listen(engine, "before_cursor_execute", lambda conn, cur, stmt, *a: statements.append(stmt))
with SessionLocal() as s:
rooms = [ClassRoom(name="10A"), ClassRoom(name="10B")]
s.add_all(rooms)
s.flush()
for i in range(6):
st = Student(name=f"S{i}", class_room_id=rooms[i % 2].id)
st.marks = [Mark(score=50 + i), Mark(score=60 + i)]
s.add(st)
s.commit()
class RoomOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
name: str
class MarkOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
score: int
class StudentOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
name: str
class_room: RoomOut
marks: list[MarkOut]
def get_db():
with SessionLocal() as db:
yield db
DB = Annotated[Session, Depends(get_db)]
app = FastAPI()
@app.get("/lazy", response_model=list[StudentOut])
def lazy(db: DB):
return db.scalars(select(Student)).all() # class_room is loaded per row while serialising
@app.get("/eager", response_model=list[StudentOut])
def eager(db: DB):
return db.scalars(select(Student).options(joinedload(Student.class_room), selectinload(Student.marks))).unique().all()
c = TestClient(app)
for path in ("lazy", "eager"):
statements.clear()
r = c.get(f"/{path}")
selects = [s for s in statements if s.lstrip().upper().startswith("SELECT")]
print(path, r.status_code, len(r.json()), "students ->", len(selects), "SELECT statements")
Standalone script. Run it with `python file.py`; it uses an in-memory SQLite database through a shared StaticPool.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
lazy 200 6 students -> 9 SELECT statements
eager 200 6 students -> 2 SELECT statements
Key points
Lazy loading during serialisation causes N+1 queries
selectinload for collections; joinedload for many-to-one
lazy='raise' turns accidental lazy loads into errors
Set loader options per query, not globally
Count queries in tests
Common mistakes
Letting the response model lazy-load relations during serialisation
Setting lazy='joined' on a relationship globally
Using joinedload on collections without unique()
Never counting queries in tests
Loading whole collections just to count them
Follow-ups
How do you detect N+1 queries in production?
Why does lazy loading fail in async sessions?
When is joinedload better than selectinload?
Tips
Explain why serialisation triggers lazy loads
Name three loader options
Mention query counting in tests
73.fastapi-0073Mediummid
How does FastAPI cache dependency results per request, and how do use_cache, router-level and application-level dependencies work?
Within one request, FastAPI calls each dependency once and reuses the result everywhere the same callable appears in the dependency tree (use_cache=True is the default). Depends(fn, use_cache=False) forces a fresh call. Dependencies can also be attached to a decorator (dependencies=[...]), to an APIRouter or include_router call, or to the whole FastAPI app: they run for every matching route and their return values are ignored.
Full answer
Per-request caching: if get_db is needed by get_current_user and by the endpoint, FastAPI calls get_db once and passes the same session to both. This keeps one session and one transaction per request, and avoids repeated work (decoding a JWT twice).
use_cache=False makes FastAPI call the dependency again each time it is declared (for counters, random IDs or fresh timestamps per use). The cache lives only for the current request; shared state across requests must be explicit (module-level objects, lru_cache, or app.state).
Attaching dependencies that do not return anything useful for the endpoint (checks, audits, rate limits):
Router: APIRouter(dependencies=[Depends(require_login)]) applies to every route in it, and include_router(router, dependencies=[...]) adds more at inclusion time.
Application: FastAPI(dependencies=[Depends(log_request)]) applies to all routes (including those in routers).
Order: application dependencies run first, then router, then path decorator, then parameters of the function; yield dependencies exit in reverse order. Exceptions raised in a dependency stop the chain and return the error response.
Caveats: decorator-level dependencies cannot inject values into the function; declare the dependency also as a parameter when you need its value (it is still cached). Global dependencies do not apply to mounted sub-apps. Sync dependencies run in the thread pool, async ones on the event loop; mixing is fine but blocking work in async dependencies stalls the loop.
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
['app-level', 'get_db', 'current_user', 'router-level', 'audit', 'endpoint']
{'a': 5, 'b': 5, 'c': 6} ['app-level', 'get_db', 'current_user', 'router-level', 'stamp', 'stamp']
Key points
Dependencies are cached per request by default
use_cache=False forces a fresh call
dependencies=[...] on a route, router or app runs without injecting values
Order: app, router, path decorator, then function parameters
Mounted sub-apps do not inherit global dependencies
Common mistakes
Expecting dependencies to run again for each use within one request
Expecting decorator-level dependencies to provide values to the function
Assuming global dependencies apply to mounted sub-apps
Sharing mutable state between requests through default arguments
Doing blocking work in async dependencies
Follow-ups
How do yield dependencies and caching interact?
In what order do dependencies exit?
How would you apply authentication to every route except health checks?
Tips
Explain per-request caching
List the three attachment levels
State the run order
74.fastapi-0074Mediummid
How do you return RFC 9457 problem details (application/problem+json) from a FastAPI application with custom exception handlers?
RFC 9457 (which replaces RFC 7807) defines a JSON error format with type, title, status, detail and instance, served as application/problem+json, plus extension members such as errors. In FastAPI you register exception handlers for HTTPException, RequestValidationError and your own domain exceptions, and return a JSONResponse with the problem media type. Clients then parse one stable shape for all failures.
Full answer
Default FastAPI errors are inconsistent: {"detail": "text"} for HTTPException and {"detail": [ ... ]} for validation. A standard envelope simplifies clients and monitoring.
Problem object members:
type: a URI identifying the problem kind (stable; may link to docs). about:blank means "see the HTTP status".
title: short, human-readable and the same for all instances of the type.
status: the HTTP status code (repeated in the body).
detail: explanation specific to this occurrence.
instance: URI of this occurrence (the request path or an error ID to quote to support).
Extensions: errors (list of field problems), trace_id, balance, etc.
Register for starlette.exceptions.HTTPException (not only FastAPI's subclass) so errors from routing, such as 404 and 405, are also covered. Add a catch-all for Exception that logs and returns a generic 500 problem without internal messages. Use media_type="application/problem+json" and include Content-Language if you localise.
Also document errors in OpenAPI with responses={404: {"model": Problem, "content": {"application/problem+json": {}}}} so generated clients know the shape. Never leak stack traces, SQL or input values with secrets, and keep type URIs stable because clients switch on them.
python
from fastapi import FastAPI, HTTPException
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
from starlette.exceptions import HTTPException as StarletteHTTPException
app = FastAPI()
BASE = "https://schoolabe.example/problems/"
def problem(status, title, type_="about:blank", detail=None, instance=None, **extra):
body = {"type": type_, "title": title, "status": status, "detail": detail, "instance": instance, **extra}
return JSONResponse({k: v for k, v in body.items() if v is not None}, status_code=status,
media_type="application/problem+json")
class FeeWindowClosed(Exception):
pass
@app.exception_handler(StarletteHTTPException)
async def http_problem(request, exc):
return problem(exc.status_code, "HTTP error", detail=str(exc.detail), instance=request.url.path)
@app.exception_handler(RequestValidationError)
async def validation_problem(request, exc):
errors = [{"field": ".".join(str(p) for p in e["loc"][1:]), "code": e["type"], "message": e["msg"]} for e in exc.errors()]
return problem(422, "Validation failed", BASE + "validation", "One or more fields are invalid.", request.url.path, errors=errors)
@app.exception_handler(FeeWindowClosed)
async def closed(request, exc):
return problem(409, "Fee window closed", BASE + "fee-window-closed", "Fees cannot be paid after 31 March.", request.url.path)
@app.exception_handler(Exception)
async def unexpected(request, exc):
return problem(500, "Internal error", detail="Something went wrong.", instance=request.url.path)
class Payment(BaseModel):
amount: int = Field(gt=0)
@app.post("/pay/{mode}")
def pay(mode: str, payment: Payment):
if mode == "late":
raise FeeWindowClosed()
if mode == "boom":
raise RuntimeError("secret internal detail")
if mode == "missing":
raise HTTPException(status_code=404, detail="No such student")
return {"ok": True}
c = TestClient(app, raise_server_exceptions=False)
for mode, body in (("ok", {"amount": 0}), ("late", {"amount": 5}), ("missing", {"amount": 5}), ("boom", {"amount": 5})):
r = c.post(f"/pay/{mode}", json=body)
print(r.status_code, r.headers["content-type"], r.json())
print(c.get("/nope").json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
422 application/problem+json {'type': 'https://schoolabe.example/problems/validation', 'title': 'Validation failed', 'status': 422, 'detail': 'One or more fields are invalid.', 'instance': '/pay/ok', 'errors': [{'field': 'amount', 'code': 'greater_than', 'message': 'Input should be greater than 0'}]}
409 application/problem+json {'type': 'https://schoolabe.example/problems/fee-window-closed', 'title': 'Fee window closed', 'status': 409, 'detail': 'Fees cannot be paid after 31 March.', 'instance': '/pay/late'}
404 application/problem+json {'type': 'about:blank', 'title': 'HTTP error', 'status': 404, 'detail': 'No such student', 'instance': '/pay/missing'}
500 application/problem+json {'type': 'about:blank', 'title': 'Internal error', 'status': 500, 'detail': 'Something went wrong.', 'instance': '/pay/boom'}
{'type': 'about:blank', 'title': 'HTTP error', 'status': 404, 'detail': 'Not Found', 'instance': '/nope'}
Key points
Problem details: type, title, status, detail, instance plus extensions
Serve with application/problem+json
Handle Starlette HTTPException so 404 and 405 are covered
Add a catch-all that hides internals
Document error models in OpenAPI
Common mistakes
Handling only FastAPI's HTTPException and missing routing errors
Leaking exception messages, SQL or stack traces in detail
Changing type URIs after clients depend on them
Not documenting error shapes in OpenAPI
Logging nothing in the catch-all handler
Follow-ups
How does RFC 9457 differ from RFC 7807?
How do you attach a trace ID to every error?
How would you localise titles and details?
Tips
List the standard members
Say which exception classes to handle
Mention the media type
75.fastapi-0075Mediummid
How should a FastAPI app hash and verify passwords with pwdlib (Argon2), upgrade old hashes on login and avoid user-enumeration timing leaks?
Use a purpose-built password hashing library such as pwdlib with Argon2id (bcrypt as a legacy option), never fast hashes like SHA-256. Store only the encoded hash, verify with PasswordHash.verify(), and call verify_and_update() on login to detect hashes that use older algorithms or parameters and replace them. Hash a dummy password when the user does not exist so response time does not reveal valid usernames. passlib is unmaintained and has issues with new bcrypt releases, which is why pwdlib is recommended.
Full answer
Requirements for password storage: slow, salted, memory-hard where possible, and upgradeable.
python
password_hash = PasswordHash((Argon2Hasher(), BcryptHasher())) # first hasher is used for new hashes
hashed = password_hash.hash("s3cret") # "$argon2id$v=19$m=65536,t=3,p=4$..."
password_hash.verify("s3cret", hashed) # True or False
ok, new_hash = password_hash.verify_and_update("s3cret", old_bcrypt_hash)
PasswordHash.recommended() returns an Argon2id configuration with safe defaults.
Each hash embeds the algorithm, parameters and a random salt, so no separate salt column is needed and identical passwords produce different hashes.
verify_and_update() returns (valid, updated_hash_or_None). If valid and the stored hash uses a legacy algorithm or weaker parameters, updated_hash is a fresh hash to save. This enables gradual migration from bcrypt (or a weaker cost) to Argon2 without forcing resets.
Login endpoint hygiene:
Look up the user; if none exists, still run a verification against a precomputed dummy hash so that unknown users cost the same time as wrong passwords. Return the same message ("Invalid credentials") for both.
Rate-limit attempts per account and IP, and add lockout or delays.
Run hashing off the event loop: it is CPU-heavy and blocking. Use a sync def endpoint (thread pool) or await anyio.to_thread.run_sync(password_hash.verify, ...). Hashing in async def freezes other requests.
Enforce minimum length (12 or more) and check against breached-password lists; avoid arbitrary composition rules; allow long passphrases (Argon2 and bcrypt have limits: bcrypt truncates at 72 bytes).
Never log or return passwords or hashes; do not email them.
Tune Argon2 cost so a hash takes roughly 50 to 250 ms on production hardware and re-evaluate yearly.
python
from typing import Annotated
from fastapi import Depends, FastAPI, Form, HTTPException
from fastapi.testclient import TestClient
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher
legacy = PasswordHash((BcryptHasher(),))
password_hash = PasswordHash((Argon2Hasher(), BcryptHasher())) # Argon2id for new hashes, bcrypt still verifies
DUMMY_HASH = password_hash.hash("dummy-password-for-timing")
USERS = {"asha": {"hash": password_hash.hash("correct horse battery")},
"ravi": {"hash": legacy.hash("old-bcrypt-password")}}
app = FastAPI()
@app.post("/login")
def login(username: Annotated[str, Form()], password: Annotated[str, Form()]): # sync def: runs in the thread pool
user = USERS.get(username)
stored = user["hash"] if user else DUMMY_HASH # same work for unknown users
valid, updated = password_hash.verify_and_update(password, stored)
if not user or not valid:
raise HTTPException(status_code=401, detail="Invalid credentials")
if updated:
user["hash"] = updated # transparent upgrade to Argon2id
return {"user": username}
print(USERS["asha"]["hash"].startswith("$argon2id$"), USERS["ravi"]["hash"].startswith("$2b$"))
print(USERS["asha"]["hash"] != password_hash.hash("correct horse battery")) # random salt: hashes differ
c = TestClient(app)
print(c.post("/login", data={"username": "asha", "password": "correct horse battery"}).json())
print(c.post("/login", data={"username": "asha", "password": "wrong"}).json())
print(c.post("/login", data={"username": "nobody", "password": "x"}).json())
print(c.post("/login", data={"username": "ravi", "password": "old-bcrypt-password"}).json())
print("ravi upgraded:", USERS["ravi"]["hash"].startswith("$argon2id$"))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install "pwdlib[argon2,bcrypt]"`.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0, pwdlib 0.4.2):
True True
True
{'user': 'asha'}
{'detail': 'Invalid credentials'}
{'detail': 'Invalid credentials'}
{'user': 'ravi'}
ravi upgraded: True
Key points
Use Argon2id via pwdlib; never fast hashes
Hashes embed algorithm, parameters and salt
verify_and_update upgrades legacy hashes on login
Run a dummy verification for unknown users; same error message
Hash off the event loop; rate-limit logins
Common mistakes
Using SHA-256 or MD5 for passwords
Running hashing inside async def and blocking the event loop
Returning different messages or timings for unknown users
Truncation surprises with bcrypt's 72-byte limit
Using the unmaintained passlib in new projects
Follow-ups
How do you choose Argon2 parameters?
How do you force a password reset after a breach?
What is a pepper and does it help?
Tips
Say slow, salted, upgradeable
Describe verify_and_update
Mention the dummy hash for timing
76.fastapi-0076Mediummid
How do you structure pytest fixtures for a FastAPI app with a real database so each test starts clean using rolled-back transactions?
Create the engine and schema once per session, then for each test open a connection, begin an outer transaction, bind a Session to it in a mode that turns commits into savepoints (join_transaction_mode="create_savepoint"), override get_db to yield that session, and roll back the outer transaction after the test. Endpoints can call commit() freely, and no data survives between tests, which is faster and more reliable than truncating tables.
Full answer
Goals: tests that are isolated, fast and use the same database engine as production behaviour requires (PostgreSQL in CI, SQLite only for simple cases).
Layering of fixtures:
engine (scope="session"): create the engine, Base.metadata.create_all() (or run Alembic migrations to test them too).
With create_savepoint, an application session.commit() releases a SAVEPOINT instead of committing the outer transaction, so the final rollback undoes everything. This is the SQLAlchemy 2.0 replacement for the older "nested transaction plus event listener" recipe.
3. client: override the dependency and yield a TestClient:
python
app.dependency_overrides[get_db] = lambda: session
with TestClient(app) as c: yield c
app.dependency_overrides.clear()
Practical points:
Factories or small helper fixtures create data (make_student(name="Asha")) so tests state only what they need.
SQLite via pysqlite needs a known workaround for savepoints to work (set isolation_level = None on connect and emit BEGIN in a begin event, as in the snippet); PostgreSQL needs nothing special.
If code under test uses threads (sync endpoints run in a thread pool), the session and connection are shared across threads: use a driver and pool that allow it (SQLite needs check_same_thread=False with StaticPool; PostgreSQL connections are fine when used sequentially).
Behaviour that depends on real commits (triggers on commit, on_commit hooks, isolation levels, concurrent transactions) needs separate tests with real commits and cleanup.
Seed static reference data once per session, not per test.
Use pytest markers for slow database tests and run them in parallel with pytest-xdist using one database per worker.
Keep a few end-to-end tests that run migrations on a clean database to catch drift between models and migrations.
python
import contextlib
import io
import sys
import tempfile
import textwrap
from pathlib import Path
import pytest
work = Path(tempfile.mkdtemp())
(work / "app_under_test.py").write_text(textwrap.dedent("""
from typing import Annotated
from fastapi import Depends, FastAPI
from pydantic import BaseModel
from sqlalchemy import create_engine, event, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, sessionmaker
from sqlalchemy.pool import StaticPool
class Base(DeclarativeBase):
pass
class Student(Base):
__tablename__ = "student"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
@event.listens_for(engine, "connect")
def no_implicit_begin(dbapi_connection, record):
dbapi_connection.isolation_level = None # pysqlite recipe: stop the driver from managing BEGIN
@event.listens_for(engine, "begin")
def emit_begin(conn):
conn.exec_driver_sql("BEGIN") # so SAVEPOINT and ROLLBACK behave properly
SessionLocal = sessionmaker(engine)
def get_db():
with SessionLocal() as db:
yield db
app = FastAPI()
class StudentIn(BaseModel):
name: str
@app.post("/students", status_code=201)
def create(s: StudentIn, db: Annotated[Session, Depends(get_db)]):
row = Student(name=s.name)
db.add(row)
db.commit() # the endpoint commits for real
return {"id": row.id, "name": row.name}
@app.get("/students")
def listing(db: Annotated[Session, Depends(get_db)]):
return [r.name for r in db.scalars(select(Student).order_by(Student.id))]
"""))
(work / "conftest.py").write_text(textwrap.dedent("""
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from app_under_test import Base, app, engine, get_db
@pytest.fixture(scope="session", autouse=True)
def schema():
Base.metadata.create_all(engine)
@pytest.fixture
def db_session():
connection = engine.connect()
outer = connection.begin()
session = Session(bind=connection, join_transaction_mode="create_savepoint")
yield session
session.close()
outer.rollback()
connection.close()
@pytest.fixture
def client(db_session):
app.dependency_overrides[get_db] = lambda: db_session
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
"""))
(work / "test_students.py").write_text(textwrap.dedent("""
def test_create_and_list(client):
assert client.post("/students", json={"name": "Asha"}).status_code == 201
assert client.get("/students").json() == ["Asha"]
def test_starts_empty_again(client):
assert client.get("/students").json() == []
def test_commit_inside_endpoint_is_rolled_back(client):
client.post("/students", json={"name": "Ravi"})
client.post("/students", json={"name": "Kiran"})
assert client.get("/students").json() == ["Ravi", "Kiran"]
def test_still_empty(client):
assert client.get("/students").json() == []
"""))
class Counter:
def __init__(self):
self.outcomes = []
def pytest_runtest_logreport(self, report):
if report.when == "call":
self.outcomes.append((report.nodeid.split("::")[1], report.outcome))
sys.path.insert(0, str(work))
counter = Counter()
with contextlib.redirect_stdout(io.StringIO()): # hide pytest timing line so the output is stable
code = pytest.main(["-q", "-p", "no:cacheprovider", "--rootdir", str(work), str(work)], plugins=[counter])
print("exit code:", int(code))
for name, outcome in counter.outcomes:
print(f"{name}: {outcome}")
Standalone script. Run it with `python file.py`; it writes a small test project to a temporary folder and runs pytest on it. Requires `pip install pytest sqlalchemy`.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0, pytest 9.2.0):
exit code: 0
test_create_and_list: passed
test_starts_empty_again: passed
test_commit_inside_endpoint_is_rolled_back: passed
test_still_empty: passed
join_transaction_mode='create_savepoint' turns commit() into a savepoint release
Override get_db to yield the test session
Behaviour tied to real commits needs separate tests
Use one database per xdist worker
Common mistakes
Truncating tables between tests, which is slow and order-dependent
Using a different database engine in tests than in production for behaviour that differs
Forgetting to clear dependency overrides
Testing commit-dependent behaviour inside a rolled-back transaction
Leaking data between tests through session-scoped fixtures
Follow-ups
How do you run these tests in parallel?
How do you test code that depends on real commits, such as on_commit hooks?
How would you run Alembic migrations as part of the fixtures?
Tips
Describe the outer transaction and savepoint
Show the dependency override
Mention limits
77.fastapi-0077Mediummid
When should you use FastAPI BackgroundTasks, asyncio.create_task or a real task queue, and what are the failure modes of each?
BackgroundTasks runs a function after the response is sent, in the same process: good for short, non-critical work such as sending an email or writing an audit line. asyncio.create_task schedules a coroutine to run independently on the event loop; keep a reference or it can be garbage-collected. Neither survives a crash or deploy, retries on failure, or spreads work across machines, so durable, long or important jobs belong in a queue (Celery, ARQ, RQ, Dramatiq) with persistence, retries and monitoring.
Full answer
Comparison:
BackgroundTasks
asyncio.create_task
Task queue
Starts
after the response is sent
as soon as the loop is free
when a worker picks it up
Runs in
same process (sync functions in thread pool)
same event loop
separate worker processes or machines
Survives restart
no
no
yes (broker-persisted)
Retries
no
no
yes
Result tracking
no
manual
yes
Good for
small, fast, non-critical work
fire-and-forget I/O alongside a request
long, important, heavy or scheduled work
Details and failure modes:
BackgroundTasks run after the response is sent but the connection is still held by the worker; heavy tasks reduce capacity. An exception in a background task happens after the 200 was sent: the client never learns about it, and you only see it in logs (log explicitly).
Sync background functions run in the thread pool; async def ones run on the event loop (CPU work there blocks everything).
asyncio.create_task(coro()) returns a Task that the event loop holds only weakly: store it in a set and remove it on completion, or it may be garbage-collected mid-run. Unhandled exceptions are logged at garbage collection time ("Task exception was never retrieved") unless you add a done-callback. Tasks are cancelled at shutdown.
On deploy or crash, in-process tasks vanish silently. Graceful shutdown may wait for them, but only if you track them.
Queues add infrastructure, but give durability, retries with backoff, rate limiting, scheduling, priorities, visibility (dashboards) and separate scaling.
Rules of thumb: if losing the job would be a bug (sending a receipt, charging, syncing), use a queue and make the job idempotent. If losing it is acceptable (cache warm-up, analytics ping), BackgroundTasks is fine. Enqueue after the database commit (or use an outbox) so workers never see missing rows.
Standalone script. Run it with `python file.py`; it drives the ASGI app directly so the order of events is visible.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
endpoint returns
response sent: 200
cache warmed by create_task
audit written for BCA-1 (after response)
response sent: 200
failing job started
error after the response was sent: mail server down
Key points
BackgroundTasks run after the response, in the same process
create_task needs a held reference and error handling
None of the in-process options survive restarts or retry
Important or long jobs belong in a queue with idempotent tasks
Exceptions in background tasks never reach the client
Common mistakes
Using BackgroundTasks for work that must not be lost
Starting create_task without keeping a reference or handling exceptions
Running CPU-heavy work in async background functions and blocking the loop
Queuing a job before the database commit
Assuming the client sees background errors
Follow-ups
How would you make a queued job idempotent?
What happens to BackgroundTasks on graceful shutdown?
How does the outbox pattern relate?
Tips
Use the comparison table
Name failure modes
Give a decision rule
78.fastapi-0078Mediummid
How do you handle large file uploads in FastAPI safely: chunked reading, size limits, temporary files and early rejection?
UploadFile wraps a SpooledTemporaryFile, so large uploads spill to disk instead of memory, but reading the whole file with await file.read() loads it into RAM. Read in fixed-size chunks, count bytes, and abort with 413 when a limit is exceeded, deleting the partial file. Reject early by checking Content-Length (which can be wrong or missing) and enforce limits at the proxy as well. Validate type by content, never trust filename or content type, and store with generated names.
Full answer
Why care: unlimited uploads allow memory exhaustion, disk filling and slow-client attacks.
Pattern:
python
@app.post("/upload")
async def upload(file: UploadFile):
size = 0
target = UPLOAD_DIR / f"{uuid4().hex}.bin"
try:
with open(target, "wb") as out:
while chunk := await file.read(1024 * 1024):
size += len(chunk)
if size > MAX_BYTES:
raise HTTPException(413, "File too large")
out.write(chunk)
except HTTPException:
target.unlink(missing_ok=True)
raise
Points:
UploadFile is a spooled temp file: kept in memory up to a threshold (1 MB by default in Starlette), then on disk. await file.read(n) reads asynchronously in a thread. file.size is available once the form is parsed.
Multipart parsing happens before your function runs, so the whole body has already been received (and spooled) by the time you count bytes. For true early rejection use the proxy limit (client_max_body_size in nginx), a pure ASGI middleware that counts bytes of the stream, and recent Starlette limits such as max_part_size and max_files.
Content-Length check: cheap first line of defence, but clients can lie or use chunked encoding.
Do not use file.filename in paths (traversal) or trust content_type. Sniff magic bytes or use a library, restrict extensions, and generate server-side names.
Blocking disk writes inside async def stall the loop for large chunks; use a thread (anyio.to_thread.run_sync) or aiofiles for heavy loads, or declare the endpoint def.
For very large files, use direct-to-object-storage uploads with pre-signed URLs, so the API never touches the bytes. Resumable protocols (tus, S3 multipart) handle flaky networks.
Scan for malware if files are shared with other users, and serve downloads with Content-Disposition: attachment and the correct type.
python
import tempfile
from pathlib import Path
from uuid import uuid4
from fastapi import FastAPI, HTTPException, UploadFile
from fastapi.testclient import TestClient
UPLOAD_DIR = Path(tempfile.mkdtemp())
MAX_BYTES = 2 * 1024 * 1024
CHUNK = 256 * 1024
app = FastAPI()
@app.post("/upload")
async def upload(file: UploadFile):
size = 0
target = UPLOAD_DIR / f"{uuid4().hex}.bin" # never use file.filename in a path
try:
with open(target, "wb") as out:
while chunk := await file.read(CHUNK):
size += len(chunk)
if size > MAX_BYTES:
raise HTTPException(status_code=413, detail=f"Limit is {MAX_BYTES} bytes")
out.write(chunk)
except HTTPException:
target.unlink(missing_ok=True) # remove the partial file
raise
return {"stored_bytes": size, "original_name_ignored": file.filename}
c = TestClient(app)
small = c.post("/upload", files={"file": ("../../etc/passwd", b"x" * 500_000, "text/plain")})
print(small.status_code, small.json())
big = c.post("/upload", files={"file": ("big.bin", b"y" * (3 * 1024 * 1024), "application/octet-stream")})
print(big.status_code, big.json())
print("files left on disk:", len(list(UPLOAD_DIR.iterdir())))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
200 {'stored_bytes': 500000, 'original_name_ignored': '../../etc/passwd'}
413 {'detail': 'Limit is 2097152 bytes'}
files left on disk: 1
Key points
UploadFile spools to disk, but read() without a size loads everything
Count bytes in chunks and return 413 over the limit; delete partial files
Enforce limits at the proxy; Content-Length can lie
Never trust filename or content type; generate names
Large files: pre-signed uploads straight to object storage
Common mistakes
Calling await file.read() with no size on large files
Using file.filename to build a path
Trusting content_type for validation
Leaving partial files behind after an aborted upload
Relying only on Content-Length
Follow-ups
How do pre-signed uploads work?
How would you count bytes in a pure ASGI middleware before parsing?
How do you verify the real file type?
Tips
Show the chunk loop
State where limits belong
Mention generated filenames
79.fastapi-0079Mediummid
How do you customise request and response handling for a group of routes with a custom APIRoute class, for example to accept gzip-compressed bodies?
Subclass fastapi.routing.APIRoute and override get_route_handler(). The returned function wraps the original handler, so it can replace the Request (to decompress or cache the body), time the call, or transform the Response. Assign it with APIRouter(route_class=MyRoute) or app.router.route_class, so it applies to chosen routers only. It runs inside routing, after middleware and before dependencies and validation of that route.
Full answer
Middleware wraps the whole app; an APIRoute subclass wraps individual routes inside the router, with access to FastAPI-level data (the matched route, dependencies, response model).
Skeleton:
python
class GzipRequest(Request):
async def body(self) -> bytes:
if not hasattr(self, "_body"):
body = await super().body()
if "gzip" in self.headers.getlist("content-encoding"):
body = gzip.decompress(body)
self._body = body
return self._body
class GzipRoute(APIRoute):
def get_route_handler(self):
original = super().get_route_handler()
async def handler(request: Request) -> Response:
return await original(GzipRequest(request.scope, request.receive))
return handler
router = APIRouter(route_class=GzipRoute)
Use cases:
Decompressing request bodies (clients that gzip large JSON) or verifying signatures on the raw body before parsing.
Logging request and response bodies (carefully) or timing per route, adding a header such as X-Process-Time.
Custom exception translation for a router group, or tenant context set from the matched route.
Caching the request body so multiple dependencies can read it.
Considerations:
Overriding body() on a Request subclass must keep working with request.json() and form parsing, since FastAPI reads the body through it.
Guard against decompression bombs: limit the decompressed size (zlib.decompressobj().decompress(data, max_length)), and cap the compressed size.
The route class applies to routes created after it is set. Routes added through include_router keep the class of their original router.
Keep route classes small. Middleware is simpler when you do not need route-level knowledge; dependencies are better for per-request inputs; a route class is the right tool when you must replace the Request or Response objects themselves.
python
import gzip
import json
from fastapi import APIRouter, FastAPI, Request, Response
from fastapi.routing import APIRoute
from fastapi.testclient import TestClient
from pydantic import BaseModel
from typing import Callable
MAX_DECOMPRESSED = 1_000_000
class GzipRequest(Request):
async def body(self) -> bytes:
if not hasattr(self, "_body"):
body = await super().body()
if "gzip" in self.headers.getlist("content-encoding"):
import zlib
d = zlib.decompressobj(16 + zlib.MAX_WBITS)
body = d.decompress(body, MAX_DECOMPRESSED) # cap the output size
if d.unconsumed_tail:
raise ValueError("decompressed body too large")
self._body = body
return self._body
class GzipRoute(APIRoute):
def get_route_handler(self) -> Callable:
original = super().get_route_handler()
async def handler(request: Request) -> Response:
response = await original(GzipRequest(request.scope, request.receive))
response.headers["X-Handled-By"] = "GzipRoute"
return response
return handler
app = FastAPI()
router = APIRouter(route_class=GzipRoute)
class Batch(BaseModel):
names: list[str]
@router.post("/batch")
async def batch(data: Batch):
return {"count": len(data.names)}
app.include_router(router)
@app.post("/plain")
async def plain(data: Batch):
return {"count": len(data.names)}
c = TestClient(app)
payload = json.dumps({"names": [f"S{i}" for i in range(1000)]}).encode()
compressed = gzip.compress(payload)
print(len(payload), "->", len(compressed), "bytes")
r = c.post("/batch", content=compressed, headers={"content-encoding": "gzip", "content-type": "application/json"})
print(r.status_code, r.json(), r.headers.get("x-handled-by"))
print(c.post("/batch", content=payload, headers={"content-type": "application/json"}).json())
r = c.post("/plain", content=compressed, headers={"content-encoding": "gzip", "content-type": "application/json"})
print("route without the custom class:", r.status_code)
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
7901 -> 2044 bytes
200 {'count': 1000} GzipRoute
{'count': 1000}
route without the custom class: 400
Key points
Subclass APIRoute and wrap the handler in get_route_handler()
Assign with APIRouter(route_class=...) to scope it to a router
Use it to replace the Request or Response objects
Guard against decompression bombs
Prefer middleware or dependencies when route-level access is not needed
Common mistakes
Using a route class where middleware or a dependency is enough
Decompressing request bodies without a size cap
Forgetting the route class applies per router, not globally
Breaking request.json() by overriding body() incorrectly
Follow-ups
How does a route class differ from middleware?
How would you log request bodies safely?
How do you apply a route class to all routers?
Tips
Show get_route_handler
Name two use cases
Mention decompression limits
80.fastapi-0080Mediummid
How do you design liveness, readiness and startup health endpoints in FastAPI, and how do they interact with shutdown?
Liveness answers "is the process alive and not deadlocked?" and should be cheap with no dependencies; if it fails the platform restarts the container. Readiness answers "can this instance serve traffic now?" and checks critical dependencies (database, cache) with short timeouts; if it fails the instance is removed from the load balancer without a restart. Mark the app not ready during shutdown so the load balancer drains it before the server stops.
Full answer
Probes serve different decisions:
Liveness (/livez): returns 200 if the event loop responds. Do not check the database here: a database outage would make the platform restart all pods, making things worse.
Readiness (/readyz): returns 200 only if the instance can do useful work: start-up finished, database reachable (SELECT 1 with a 1 to 2 second timeout), required caches or queues available. Return 503 with a JSON body listing which checks failed.
Startup probe (platform feature): gives slow start-ups (cache warming, migrations) more time before liveness begins.
Implementation notes:
Keep a state object set in lifespan: ready=True after resources open, ready=False at shutdown start. The readiness endpoint reads it.
Run dependency checks with timeouts (asyncio.wait_for) so a hanging database does not hang the probe, and cache results for a few seconds to avoid hammering dependencies on busy clusters.
Use include_in_schema=False and keep health endpoints out of authentication, access logs noise and rate limits.
Return minimal information publicly; detailed dependency status can leak internals. Use an internal port or authenticated route for diagnostics.
Health must be fast; do not run heavy queries.
Graceful shutdown sequence on deploy: SIGTERM arrives; mark not ready; the load balancer stops sending new requests (allow a delay equal to probe interval times failure threshold); in-flight requests finish within the server's graceful timeout (--timeout-graceful-shutdown in Uvicorn); lifespan shutdown closes pools; process exits. Configure the platform's termination grace period to exceed these timers.
Also expose build version and git SHA in a separate /version endpoint to help debugging rollouts.
python
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI, Response
from fastapi.testclient import TestClient
state = {"ready": False, "db_up": True}
async def check_database():
await asyncio.sleep(0)
if not state["db_up"]:
raise ConnectionError("database unreachable")
@asynccontextmanager
async def lifespan(app: FastAPI):
state["ready"] = True # resources are open
yield
state["ready"] = False # begin draining
app = FastAPI(lifespan=lifespan)
@app.get("/livez", include_in_schema=False)
async def livez():
return {"status": "alive"} # no dependency checks here
@app.get("/readyz", include_in_schema=False)
async def readyz(response: Response):
checks = {"startup": "ok" if state["ready"] else "not ready"}
if state["ready"]:
try:
await asyncio.wait_for(check_database(), timeout=1)
checks["database"] = "ok"
except (ConnectionError, asyncio.TimeoutError) as exc:
checks["database"] = f"failed: {exc}"
if any(v != "ok" for v in checks.values()):
response.status_code = 503
return {"checks": checks}
c = TestClient(app)
print("before startup:", c.get("/readyz").status_code, c.get("/readyz").json())
with TestClient(app) as running:
print("running:", running.get("/readyz").status_code, running.get("/livez").json())
state["db_up"] = False
r = running.get("/readyz")
print("database down:", r.status_code, r.json(), "| still alive:", running.get("/livez").status_code)
state["db_up"] = True
print("after shutdown:", state["ready"])
print("hidden from docs:", [p for p in c.get("/openapi.json").json()["paths"]])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
before startup: 503 {'checks': {'startup': 'not ready'}}
running: 200 {'status': 'alive'}
database down: 503 {'checks': {'startup': 'ok', 'database': 'failed: database unreachable'}} | still alive: 200
after shutdown: False
hidden from docs: []
Key points
Liveness is cheap and dependency-free; readiness checks dependencies
Failing liveness restarts; failing readiness only removes from traffic
Mark not ready at shutdown to drain traffic
Use timeouts and brief caching for dependency checks
Keep health routes out of the schema and out of auth
Common mistakes
Checking the database in the liveness probe and causing restart storms
No timeout on dependency checks so probes hang
Not marking the instance unready before shutdown
Exposing detailed internals on public health routes
Heavy queries inside health checks
Follow-ups
How long should the termination grace period be?
What does a startup probe add?
How would you check a message broker without overloading it?