Questions 41–60 of 100 · 0 of 20 on this page marked learned
41.fastapi-0041Hardsenior
How would you add rate limiting to a FastAPI API that runs on several servers?
Rate limits need a shared counter, so with several servers store state in Redis (or use the API gateway's limiter). Implement a fixed window, sliding window or token bucket keyed by user ID, API key or client IP, apply it as a dependency or middleware, and return 429 with Retry-After and rate-limit headers. Use stricter limits on sensitive endpoints such as login and OTP, and keep coarse limits at the edge (CDN, gateway) for floods.
Full answer
Why: protect the service and the database from abuse and accidents (a buggy client loop), share capacity fairly, and slow down brute-force attacks on login or OTP endpoints.
Where to enforce:
Edge (CDN, WAF, API gateway, Nginx limit_req): cheapest, stops floods before they reach Python.
Application: needed for limits by user, plan or endpoint, which the edge cannot see.
Algorithms:
Fixed window: count requests per key per minute (INCR key; EXPIRE key 60). Simple; allows bursts at window edges (up to twice the limit across a boundary).
Sliding window log or counter: smoother, more memory or math.
Token bucket: tokens refill at a steady rate up to a burst size; each request takes one. Allows short bursts but enforces the average. Popular for APIs.
Shared state: in-process dictionaries only work with one process. With several workers or servers, use Redis with atomic operations (INCR plus EXPIRE in a pipeline, or a Lua script for token buckets) so all instances see the same counts.
Keys: authenticated user ID or API key first; client IP for anonymous traffic (behind a proxy, take the IP from trusted forwarded headers only, or attackers rotate fake IPs). Consider limits per endpoint group: login 5 per minute per account and per IP, search 60 per minute per user.
Response: status 429, Retry-After seconds, and informational headers (RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset, standardised in the IETF RateLimit header drafts; older APIs use X-RateLimit-*).
In FastAPI, a dependency is the natural fit: it can read the current user and be attached per route or per router. Libraries such as slowapi or fastapi-limiter provide ready implementations.
Fail-open or fail-closed: if Redis is down, decide deliberately. Many APIs fail open for normal endpoints (availability) and fail closed for login (security).
python
import time
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException, Response
from fastapi.testclient import TestClient
class FakeRedis:
"""Mimics the two Redis commands a fixed-window limiter needs (INCR and EXPIRE)."""
def __init__(self):
self.data, self.expiry = {}, {}
def incr(self, key):
if key in self.expiry and self.expiry[key] <= time.time():
self.data.pop(key, None); self.expiry.pop(key, None)
self.data[key] = self.data.get(key, 0) + 1
return self.data[key]
def expire(self, key, seconds, nx=True):
if not (nx and key in self.expiry):
self.expiry[key] = time.time() + seconds
def ttl(self, key):
return max(0, int(self.expiry.get(key, time.time()) - time.time()))
redis = FakeRedis() # use redis.asyncio.Redis in production
class RateLimit:
def __init__(self, limit: int, window: int, scope: str):
self.limit, self.window, self.scope = limit, window, scope
def __call__(self, response: Response, x_api_key: Annotated[str, Header()]):
window_id = int(time.time() // self.window)
key = f"rl:{self.scope}:{x_api_key}:{window_id}"
count = redis.incr(key)
redis.expire(key, self.window)
remaining = max(0, self.limit - count)
response.headers["RateLimit-Limit"] = str(self.limit)
response.headers["RateLimit-Remaining"] = str(remaining)
if count > self.limit:
# headers set on `response` are dropped when an exception is raised, so repeat them here
raise HTTPException(status_code=429, detail="Too many requests",
headers={"Retry-After": str(max(1, redis.ttl(key))),
"RateLimit-Limit": str(self.limit), "RateLimit-Remaining": "0"})
app = FastAPI()
@app.post("/login", dependencies=[Depends(RateLimit(limit=3, window=60, scope="login"))])
def login():
return {"ok": True}
@app.get("/timetable", dependencies=[Depends(RateLimit(limit=100, window=60, scope="read"))])
def timetable():
return {"monday": ["Maths", "DBMS"]}
c = TestClient(app)
key = {"X-API-Key": "app-123"}
for _ in range(4):
r = c.post("/login", headers=key)
print(r.status_code, r.headers.get("ratelimit-remaining"), r.headers.get("retry-after") is not None)
print(c.get("/timetable", headers=key).status_code, "(separate limit)")
print(c.post("/login", headers={"X-API-Key": "other-app"}).status_code, "(separate key)")
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. FakeRedis mirrors INCR and EXPIRE so the example runs without a Redis server; swap in redis.asyncio for real use.
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 2 False
200 1 False
200 0 False
429 0 True
200 (separate limit)
200 (separate key)
Key points
Use shared state (Redis) when running several processes
Key by user or API key; IP only from trusted proxies
429 with Retry-After and RateLimit headers
Edge limits for floods; app limits for per-user rules
Common mistakes
Keeping counters in process memory with several workers or servers
Keying anonymous limits on X-Forwarded-For from untrusted clients
Returning 429 without Retry-After
Setting headers on the injected Response and expecting them on an HTTPException response
Using one global limit for login and for cheap read endpoints
Not deciding what happens when Redis is unavailable
Follow-ups
How would you implement a token bucket atomically in Redis?
How would you rate limit by subscription plan?
Should the limiter fail open or closed if Redis is down?
Tips
Mention shared state first, it is the core of the multi-server question
Compare at least two algorithms
Cover headers, keys and failure mode
42.fastapi-0042Hardsenior
How do you stream responses from FastAPI, for example large CSV exports or live progress with Server-Sent Events?
StreamingResponse sends chunks from a generator as they are produced, so large exports start immediately and use constant memory. For live server-to-client updates, Server-Sent Events use the text/event-stream format over normal HTTP; recent FastAPI versions provide EventSourceResponse and ServerSentEvent in fastapi.sse, where the endpoint yields events. Handle client disconnects, add heartbeats, and disable proxy buffering for streams.
Full answer
Streaming large responses
Building a 300 MB CSV in memory and then returning it is slow to start and can crash a worker. Stream instead:
python
def rows():
yield "roll_no,marks\n"
for r in iterate_from_db_in_batches():
yield f"{r.roll_no},{r.marks}\n"
return StreamingResponse(rows(), media_type="text/csv",
headers={"Content-Disposition": 'attachment; filename="marks.csv"'})
Sync generators are iterated in the thread pool; async generators on the event loop.
The status code and headers are sent before the body, so errors halfway through cannot change the status. Validate inputs before starting.
The database cursor must stay open while streaming. With yield dependencies in current FastAPI (exit after the response, scope="request"), the session lives until the stream ends.
Server-Sent Events (SSE)
SSE is a one-way stream from server to browser over HTTP, with automatic reconnection in the browser's EventSource API. Good for progress bars, notifications, and streaming LLM tokens. Wire format: lines like event: progress, data: {...}, id: 7, separated by blank lines.
Recent FastAPI releases include fastapi.sse.EventSourceResponse: set it as response_class and yield dicts, models or ServerSentEvent(data=..., event=..., id=...) objects; FastAPI encodes them (data as JSON). On older versions use StreamingResponse with media_type="text/event-stream" and format lines yourself, or the sse-starlette package.
Operational details:
Proxies buffer by default; send X-Accel-Buffering: no for Nginx or disable buffering, or clients see nothing until the end.
Send periodic heartbeat comments (: ping) so idle connections are not closed by load balancers.
Check await request.is_disconnected() in long loops to stop work for clients that left.
Each open stream holds a connection; plan limits per worker.
Choose WebSockets when the client must also send messages frequently; SSE is simpler for server-to-client only.
python
import asyncio
from collections.abc import AsyncIterable
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
from fastapi.sse import EventSourceResponse, ServerSentEvent
from fastapi.testclient import TestClient
app = FastAPI()
def marks_csv():
yield "roll_no,marks\n"
for roll in range(1, 6): # in real code: read the database in batches
yield f"R{roll:03d},{50 + roll * 7}\n"
@app.get("/exports/marks.csv")
def export_marks():
return StreamingResponse(marks_csv(), media_type="text/csv",
headers={"Content-Disposition": 'attachment; filename="marks.csv"'})
@app.get("/reports/{report_id}/progress", response_class=EventSourceResponse)
async def progress(report_id: int, request: Request) -> AsyncIterable[ServerSentEvent]:
for step, pct in enumerate((25, 50, 75, 100), start=1):
if await request.is_disconnected():
break
await asyncio.sleep(0.01) # work happens here
yield ServerSentEvent(data={"report": report_id, "percent": pct}, event="progress", id=str(step))
yield ServerSentEvent(data="done", event="complete")
c = TestClient(app)
with c.stream("GET", "/exports/marks.csv") as r:
print(r.headers["content-type"], r.headers["content-disposition"])
print([chunk for chunk in r.iter_text()][:3])
with c.stream("GET", "/reports/42/progress") as r:
print(r.headers["content-type"])
print(r.read().decode().strip())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. fastapi.sse needs a recent FastAPI release (verified on 0.165); older versions can use StreamingResponse with media_type='text/event-stream'.
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):
text/csv; charset=utf-8 attachment; filename="marks.csv"
['roll_no,marks\n', 'R001,57\n', 'R002,64\n']
text/event-stream; charset=utf-8
event: progress
data: {"report": 42, "percent": 25}
id: 1
event: progress
data: {"report": 42, "percent": 50}
id: 2
event: progress
data: {"report": 42, "percent": 75}
id: 3
event: progress
data: {"report": 42, "percent": 100}
id: 4
event: complete
data: "done"
Key points
StreamingResponse sends generator chunks with constant memory
Status and headers go first; validate before streaming
Building huge responses in memory instead of streaming
Expecting to change the status code after streaming has started
Forgetting proxy buffering, so SSE events arrive all at once
Not handling client disconnects and doing work for nobody
Choosing WebSockets for purely server-to-client updates where SSE is simpler
Follow-ups
How would you stream an LLM response token by token to a browser?
What happens if the database fails halfway through a CSV stream?
SSE or WebSockets for a live attendance dashboard, and why?
Tips
Show both a file stream and SSE
Mention the headers-first limitation
Cover the proxy and heartbeat operational details
43.fastapi-0043Hardsenior
How do you broadcast WebSocket messages to all clients in a room when the app runs on several workers or servers?
A connection lives in one worker process, so an in-memory list of sockets only reaches clients connected to that worker. Put a shared message bus between workers, usually Redis pub/sub or streams (or NATS, Kafka): each worker subscribes to a channel per room, publishes incoming messages to the bus, and forwards bus messages to its own local sockets. Handle slow clients, reconnects and lost messages explicitly.
Full answer
Why a plain connection manager is not enough
A common tutorial class keeps active_connections: list[WebSocket] and loops over it. With 4 workers, a client on worker 1 sends a message and only the clients on worker 1 receive it. Sticky sessions do not fix this; users in the same room land on different workers.
Pattern
Each worker keeps a local registry: room -> set of WebSockets.
When a client sends a message, the worker publishes it to the bus (PUBLISH room:10A payload), instead of sending directly.
Each worker runs one subscriber task (started in lifespan) listening to the bus. For every message it sends to the local sockets of that room.
Local clients on the publishing worker also receive through the bus, so ordering and logic stay the same everywhere.
Choosing the bus
Redis pub/sub: simple and fast, but fire-and-forget. A worker that is disconnected or slow misses messages.
Redis Streams, NATS JetStream, Kafka: persisted, so a reconnecting client or worker can replay from an ID. Needed for chat history or exactly-once-ish delivery.
A database LISTEN/NOTIFY works for small systems.
Details that matter in production
Slow consumers: sending to one stalled socket must not block others. Use a bounded per-connection queue and drop or disconnect when full.
Auth and authorisation per room, checked before accept and on every publish.
Heartbeats (ping/pong) to remove dead sockets; remove sockets in finally.
Reconnect with a last-seen message ID from the client.
Connection limits per worker and a memory budget per socket.
Presence ("who is online") needs shared state with TTLs, not local lists.
Proxies need upgrade headers and long idle timeouts.
Libraries (broadcaster, fastapi-websocket-pubsub) wrap this pattern, but knowing the shape matters more than the package.
python
import asyncio
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.testclient import TestClient
class Bus:
"""In-process stand-in for Redis pub/sub, shared by several 'workers' in this demo."""
def __init__(self):
self.subscribers = []
async def publish(self, room, message):
for worker in self.subscribers:
await worker.deliver(room, message)
class Worker:
def __init__(self, name, bus):
self.name, self.bus = name, bus
self.rooms: dict[str, set[WebSocket]] = {}
bus.subscribers.append(self)
async def deliver(self, room, message):
for ws in list(self.rooms.get(room, ())):
await ws.send_json({"via": self.name, "message": message})
def make_app(self):
app = FastAPI()
@app.websocket("/ws/{room}")
async def chat(ws: WebSocket, room: str):
await ws.accept()
self.rooms.setdefault(room, set()).add(ws)
try:
while True:
text = await ws.receive_text()
await self.bus.publish(room, text) # not a local loop
except WebSocketDisconnect:
pass
finally:
self.rooms[room].discard(ws)
return app
bus = Bus()
w1, w2 = Worker("worker-1", bus), Worker("worker-2", bus)
c1, c2 = TestClient(w1.make_app()), TestClient(w2.make_app())
with c1.websocket_connect("/ws/10A") as a, c2.websocket_connect("/ws/10A") as b:
a.send_text("Quiz starts at 10")
print("client on worker-1 got:", a.receive_json())
print("client on worker-2 got:", b.receive_json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. A Python object replaces Redis so the flow is visible without a server: swap Bus.publish for redis.publish and run one subscriber task per worker in lifespan.
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):
client on worker-1 got: {'via': 'worker-1', 'message': 'Quiz starts at 10'}
client on worker-2 got: {'via': 'worker-2', 'message': 'Quiz starts at 10'}
Key points
Sockets live in one process; local lists cannot cross workers
Publish to a shared bus; every worker forwards to its local sockets
Redis pub/sub is fire-and-forget; streams or Kafka persist
Protect against slow consumers with bounded queues
Presence and replay need shared state
Common mistakes
Keeping a per-process connection list and expecting it to reach all users
Using Redis pub/sub and assuming no message is ever lost
Letting one slow client block the broadcast loop
Skipping authorisation on publish, not only on connect
Not cleaning up sockets on disconnect
Follow-ups
How would a reconnecting client receive the messages it missed?
How would you implement presence (who is online) across workers?
When would you choose Server-Sent Events plus a normal POST instead?
Tips
Say plainly why a single-process manager breaks
Describe the publish/subscribe loop step by step
Cover delivery guarantees and slow consumers
44.fastapi-0044Hardsenior
What does app.mount() do in FastAPI, and when do you use sub-applications, static files or mounted WSGI apps?
app.mount("/prefix", other_app) delegates every request under that path prefix to another ASGI application, which has its own routes, middleware, exception handlers and OpenAPI docs. It is used for StaticFiles, for versioned or independent sub-APIs (with separate docs), and for WSGIMiddleware around Flask or Django. Mounted apps are invisible to the parent's OpenAPI schema and do not share its dependencies, middleware or lifespan.
Full answer
include_router and mount solve different problems.
include_router: adds routes to the same app. One OpenAPI schema, shared middleware, shared dependencies and exception handlers.
mount: hands over a path prefix to a completely separate ASGI app.
Common uses
Static files: app.mount("/static", StaticFiles(directory="static"), name="static"). Served directly by Starlette without going through FastAPI's route machinery. In production, a CDN or the proxy usually serves them.
Sub-APIs: admin_api = FastAPI(title="Admin API") mounted at /admin-api gets its own /docs at /admin-api/docs, its own middleware (stricter auth) and its own exception handlers. Useful when two audiences need separate documentation, or when a team owns a self-contained module.
Legacy apps: from a2wsgi import WSGIMiddleware (the old fastapi.middleware.wsgi is deprecated) wraps a Flask or Django WSGI app so it can live under /legacy during a gradual migration. WSGI code runs in a thread pool.
Behaviours to know
Prefix handling: the mounted app routes on the path after the prefix (/users), while Starlette records the prefix in request.scope["root_path"] (here /admin-api) so generated URLs and docs stay correct. request.url.path still shows the full path. Behind a proxy that strips a prefix, set FastAPI(root_path="/api") so docs find openapi.json.
The parent's OpenAPI does not include mounted routes. Each mounted FastAPI app documents itself.
Middleware on the parent wraps mounted apps too (it is outside), but dependencies and exception handlers registered on the parent do not apply inside the mounted app.
Lifespan events of mounted apps do not run; only the main app's lifespan does. Start shared resources in the parent.
Mount order matters: a mount at / swallows everything declared after it, so put catch-all mounts (for example a single-page app) last.
python
import tempfile
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.testclient import TestClient
static_dir = Path(tempfile.mkdtemp())
(static_dir / "logo.txt").write_text("CAMPUS LOGO")
app = FastAPI(title="Campus API")
admin_api = FastAPI(title="Admin API")
@app.get("/students")
def students():
return ["Asha", "Ravi"]
@admin_api.get("/users")
def users(request: Request):
return {"path_seen_by_subapp": request.url.path, "root_path": request.scope["root_path"]}
def legacy_wsgi_app(environ, start_response): # a tiny WSGI app standing in for Flask
body = f"legacy page at {environ['PATH_INFO']}".encode()
start_response("200 OK", [("Content-Type", "text/plain"), ("Content-Length", str(len(body)))])
return [body]
from a2wsgi import WSGIMiddleware
app.mount("/admin-api", admin_api)
app.mount("/static", StaticFiles(directory=static_dir), name="static")
app.mount("/legacy", WSGIMiddleware(legacy_wsgi_app))
c = TestClient(app)
print(c.get("/students").json())
print(c.get("/admin-api/users").json())
print(c.get("/static/logo.txt").text)
print(c.get("/legacy/old/report").text)
print("parent schema paths:", sorted(c.get("/openapi.json").json()["paths"]))
print("sub-app schema paths:", sorted(c.get("/admin-api/openapi.json").json()["paths"]))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install a2wsgi`.
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):
['Asha', 'Ravi']
{'path_seen_by_subapp': '/admin-api/users', 'root_path': '/admin-api'}
CAMPUS LOGO
legacy page at /old/report
parent schema paths: ['/students']
sub-app schema paths: ['/users']
Key points
include_router merges routes; mount delegates a prefix to another ASGI app
Mounted apps have their own docs, middleware and handlers
WSGI apps mount through WSGIMiddleware (a2wsgi)
Parent middleware wraps mounts; parent dependencies do not
Mounted lifespan does not run; put catch-all mounts last
Common mistakes
Expecting mounted routes to appear in the parent's OpenAPI schema
Expecting parent dependencies or exception handlers to apply inside a mounted app
Mounting a catch-all app at / before other routes
Relying on a mounted app's lifespan to start resources
Using the deprecated fastapi.middleware.wsgi.WSGIMiddleware instead of a2wsgi
Follow-ups
How do you serve the API under /api behind a proxy that strips the prefix?
How would you migrate a Flask app into FastAPI gradually?
When is a second FastAPI app better than a second router?
Tips
Contrast mount with include_router first
List what is and is not shared with the parent
Mention root_path behind proxies
45.fastapi-0045Hardsenior
How do you model request bodies that can be one of several shapes using discriminated unions in Pydantic v2 and FastAPI?
Declare a union of models that each have a Literal tag field and tell Pydantic which field decides the type with Field(discriminator="kind") (or Annotated with Discriminator for callables). Pydantic reads the tag first and validates only the matching model, so errors are precise, validation is faster than trying each member, and OpenAPI gets a oneOf with a discriminator mapping. Without a discriminator, plain unions try members in order in smart mode and give confusing multi-branch errors.
Full answer
Real APIs often accept polymorphic payloads: a notification can be an email, an SMS or a push message; a payment can be a card, UPI or bank transfer. Each has different fields.
Plain union
python
payment: CardPayment | UpiPayment
Pydantic tries each member and reports errors from all of them when none match, which is hard to read. It may also pick the wrong member when shapes overlap.
Discriminated union
python
class Card(BaseModel):
kind: Literal["card"]
number: str
class Upi(BaseModel):
kind: Literal["upi"]
vpa: str
class Order(BaseModel):
payment: Annotated[Card | Upi, Field(discriminator="kind")]
How it works: Pydantic looks at kind, selects exactly one model and validates against it. Benefits:
Clear errors: {"kind": "upi"} without vpa reports only the missing vpa, not errors for Card too.
An unknown tag gives one error listing the allowed tags (union_tag_invalid).
Faster validation in the Rust core, with no trial and error.
OpenAPI emits oneOf plus discriminator.mapping, so generated clients create proper tagged types.
Variants
Callable discriminators: Discriminator(func) with Tag("card") handles cases where the shape, not a field, decides the type, or where the tag is nested.
Nested discriminated unions work too.
Models can share a base class holding common fields.
Design advice: use a stable, explicit tag from the start. Adding a new variant later is then a non-breaking change for clients that handle unknown kinds gracefully. Handling the parsed value is a clean match statement on the model type.
python
from typing import Annotated, Literal
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class Card(BaseModel):
kind: Literal["card"]
number: str = Field(min_length=12, max_length=19)
class Upi(BaseModel):
kind: Literal["upi"]
vpa: str = Field(pattern=r"^[\w.-]+@[\w]+$")
class NetBanking(BaseModel):
kind: Literal["netbanking"]
bank_code: str
Payment = Annotated[Card | Upi | NetBanking, Field(discriminator="kind")]
class FeePayment(BaseModel):
roll_no: str
amount: int = Field(gt=0)
payment: Payment
@app.post("/fees")
def pay(data: FeePayment):
match data.payment:
case Card():
how = "card ending " + data.payment.number[-4:]
case Upi():
how = "UPI " + data.payment.vpa
case NetBanking():
how = "bank " + data.payment.bank_code
return {"roll_no": data.roll_no, "paid_with": how}
c = TestClient(app)
base = {"roll_no": "BCA-17", "amount": 1500}
print(c.post("/fees", json={**base, "payment": {"kind": "upi", "vpa": "asha@okbank"}}).json())
print(c.post("/fees", json={**base, "payment": {"kind": "card", "number": "4111111111111111"}}).json())
err = c.post("/fees", json={**base, "payment": {"kind": "upi"}}).json()["detail"]
print([(e["loc"], e["type"]) for e in err])
err = c.post("/fees", json={**base, "payment": {"kind": "cash"}}).json()["detail"]
print([(e["loc"], e["type"]) for e in err])
print(c.get("/openapi.json").json()["components"]["schemas"]["FeePayment"]["properties"]["payment"]["discriminator"])
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', 'paid_with': 'UPI asha@okbank'}
{'roll_no': 'BCA-17', 'paid_with': 'card ending 1111'}
[(['body', 'payment', 'upi', 'vpa'], 'missing')]
[(['body', 'payment'], 'union_tag_invalid')]
{'propertyName': 'kind', 'mapping': {'card': '#/components/schemas/Card', 'netbanking': '#/components/schemas/NetBanking', 'upi': '#/components/schemas/Upi'}}
Key points
Literal tag field plus Field(discriminator=...)
Pydantic validates only the matching member
Errors are precise; validation is faster
OpenAPI shows oneOf with a discriminator mapping
Callable Discriminator and Tag cover shape-based cases
Common mistakes
Using a plain union where shapes overlap and getting the wrong member
Leaving out the Literal tag and relying on guesswork
Changing tag values and breaking clients
Doing isinstance chains instead of match on the parsed model
Follow-ups
How would you add a new payment kind without breaking old clients?
When do you need a callable Discriminator with Tag?
How do generated TypeScript clients use the discriminator mapping?
Tips
Contrast plain and discriminated unions with the error output
Mention OpenAPI oneOf and client generation
Show a match statement on the parsed type
46.fastapi-0046Hardsenior
How would you structure a large FastAPI codebase, and how do you keep routers, services and persistence separate and testable?
Organise by feature (domain packages such as students, fees, auth), and inside each feature separate the HTTP layer (router, request and response schemas), the service layer (business rules, no FastAPI imports) and the persistence layer (SQLAlchemy models and queries). Dependencies wire the layers together, so tests can replace storage with fakes. Keep transactions at the service boundary, domain exceptions mapped by handlers, and configuration in one settings object.
Full answer
A flat main.py with 80 endpoints and SQL inside route functions becomes impossible to test and change. The usual remedy is layering plus feature folders.
Router: validation via schemas, status codes, dependencies for auth. No business rules, no SQL.
Service: rules such as "a student cannot enrol in two overlapping courses". Takes plain arguments and a repository, raises domain exceptions, knows nothing about HTTP.
Repository: all queries for one aggregate. Returns ORM objects or domain objects.
Unit tests call the service with a fake repository (no database, no HTTP).
Integration tests hit routers with TestClient and a test database.
Services are reusable from CLI scripts, background workers and other routers.
A change in storage affects one layer.
Judgement calls
Do not build layers for trivial CRUD; a small app can have routers calling the session directly. Add the service layer when rules appear.
Avoid circular imports between features: depend on interfaces or pass IDs; shared concepts go in core.
The unit of work: one request, one session, one commit at the service boundary.
Use an app factory (create_app(settings)) so tests build isolated apps.
Keep Pydantic schemas separate from ORM models; they change for different reasons.
python
from typing import Annotated, Protocol
from fastapi import APIRouter, Depends, FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel
# students/exceptions.py
class AlreadyEnrolled(Exception):
pass
# students/service.py (no FastAPI imports)
class EnrolmentRepo(Protocol):
def courses_of(self, roll_no: str) -> set[str]: ...
def add(self, roll_no: str, course: str) -> None: ...
class EnrolmentService:
def __init__(self, repo: EnrolmentRepo):
self.repo = repo
def enrol(self, roll_no: str, course: str) -> list[str]:
if course in self.repo.courses_of(roll_no):
raise AlreadyEnrolled(f"{roll_no} is already in {course}")
self.repo.add(roll_no, course)
return sorted(self.repo.courses_of(roll_no))
# students/repository.py
class InMemoryRepo:
def __init__(self):
self.data: dict[str, set[str]] = {}
def courses_of(self, roll_no):
return set(self.data.get(roll_no, ()))
def add(self, roll_no, course):
self.data.setdefault(roll_no, set()).add(course)
_repo = InMemoryRepo()
def get_service() -> EnrolmentService: # dependency wires the layers together
return EnrolmentService(_repo)
# students/schemas.py and router.py
class EnrolIn(BaseModel):
course: str
router = APIRouter(prefix="/students", tags=["students"])
@router.post("/{roll_no}/enrol")
def enrol(roll_no: str, body: EnrolIn, service: Annotated[EnrolmentService, Depends(get_service)]):
return {"roll_no": roll_no, "courses": service.enrol(roll_no, body.course)}
# main.py
def create_app() -> FastAPI:
app = FastAPI()
app.include_router(router)
@app.exception_handler(AlreadyEnrolled)
async def already(request: Request, exc: AlreadyEnrolled):
return JSONResponse(status_code=409, content={"detail": str(exc)})
return app
app = create_app()
c = TestClient(app)
print(c.post("/students/BCA-17/enrol", json={"course": "DBMS"}).json())
print(c.post("/students/BCA-17/enrol", json={"course": "DBMS"}).status_code)
fake = InMemoryRepo() # unit test: no HTTP, no database
print(EnrolmentService(fake).enrol("X-1", "Maths"))
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', 'courses': ['DBMS']}
409
['Maths']
Key points
Feature packages with router, schemas, service, repository
Routers handle HTTP only; services hold rules and know no HTTP
Dependencies wire layers; tests swap fakes
Commit at the service boundary
Do not over-layer trivial CRUD
Common mistakes
Writing SQL and business rules inside route functions
Importing FastAPI types into the service layer, tying rules to HTTP
Building repository, service and interface layers for trivial CRUD
Sharing ORM models directly as API schemas
Circular imports between feature packages
Follow-ups
Where do transactions begin and end in this design?
How would you test the service without a database?
How do you share code between features without circular imports?
Tips
Draw the folder layout
State each layer's responsibility and what it must not know
Mention when not to layer
47.fastapi-0047Hardsenior
How do you make a POST endpoint such as a payment idempotent in FastAPI using an Idempotency-Key header?
Clients send a unique Idempotency-Key header with each logical operation. The server stores the key with a hash of the request and the resulting response; a repeat with the same key and same body returns the stored response without redoing the work, the same key with a different body is rejected (422 or 409), and concurrent duplicates are blocked with an atomic insert or lock. Keys expire after a retention window, and storage must be shared and durable (database unique constraint or Redis SET NX).
Full answer
Networks fail between "server did the work" and "client got the answer". Clients then retry. Without protection, a retry of POST /payments charges twice. Idempotency means repeating the same request has the same effect as sending it once.
Protocol (popularised by Stripe, drafted at the IETF):
Client generates a unique key (UUID) per logical operation and sends Idempotency-Key: <key>. Retries reuse the same key.
Server, before doing work, tries to record the key atomically: INSERT ... ON CONFLICT DO NOTHING on a table with a unique key, or Redis SET key value NX EX 86400.
If it created the record, it runs the operation, then stores status code and body under the key.
If the key exists and the stored request fingerprint matches: return the stored response (or 409 if the first attempt is still in progress).
If the key exists but the body differs: reject (the client reused a key by mistake).
Details that matter
Atomic claim. A check-then-insert race lets two simultaneous retries both pass. The unique constraint or NX is what makes it safe.
Fingerprint the request (hash of method, path, body) so key reuse with different data is detected.
Store failures too, or define which errors may be retried with the same key (e.g. 5xx before side effects may be safe to re-run).
Same transaction: record the result in the same database transaction as the business change when possible, so "paid but no record" cannot happen. External side effects (a call to a payment gateway) need the gateway's own idempotency key passed through.
Retention: keep keys long enough for retries (24 hours is common).
Scope keys per user or API client so keys from different tenants never collide.
GET, PUT and DELETE are idempotent by definition; the key is for POST and PATCH.
In FastAPI this fits a dependency that reads the header and returns a helper object, or a small decorator around the endpoint.
python
import hashlib
import threading
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
STORE: dict[str, dict] = {} # in production: a table with a UNIQUE key, or Redis SET NX
LOCK = threading.Lock()
charges: list[int] = []
class PaymentIn(BaseModel):
roll_no: str
amount: int = Field(gt=0)
def idempotency(body: PaymentIn, key: Annotated[str, Header(alias="Idempotency-Key", min_length=8)]):
fingerprint = hashlib.sha256(body.model_dump_json().encode()).hexdigest()
with LOCK: # atomic claim
record = STORE.get(key)
if record is None:
STORE[key] = {"fingerprint": fingerprint, "response": None}
return {"key": key, "replay": None}
if record["fingerprint"] != fingerprint:
raise HTTPException(status_code=422, detail="Idempotency-Key reused with a different request")
if record["response"] is None:
raise HTTPException(status_code=409, detail="A request with this key is still in progress")
return {"key": key, "replay": record["response"]}
@app.post("/payments", status_code=201)
def pay(body: PaymentIn, idem: Annotated[dict, Depends(idempotency)]):
if idem["replay"] is not None:
return idem["replay"]
charges.append(body.amount) # the side effect, done once
response = {"payment_id": len(charges), "amount": body.amount, "status": "paid"}
STORE[idem["key"]]["response"] = response
return response
c = TestClient(app)
h = {"Idempotency-Key": "9f1c2b7e-0001"}
data = {"roll_no": "BCA-17", "amount": 1500}
print(c.post("/payments", json=data, headers=h).json())
print(c.post("/payments", json=data, headers=h).json()) # retry after a lost response
print("charges made:", charges)
r = c.post("/payments", json={**data, "amount": 9999}, headers=h)
print(r.status_code, r.json())
print(c.post("/payments", json=data, headers={"Idempotency-Key": "9f1c2b7e-0002"}).json()["payment_id"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. A dict and a lock stand in for the database unique constraint; with several workers the claim must be an atomic insert or Redis SET NX.
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):
{'payment_id': 1, 'amount': 1500, 'status': 'paid'}
{'payment_id': 1, 'amount': 1500, 'status': 'paid'}
charges made: [1500]
422 {'detail': 'Idempotency-Key reused with a different request'}
2
Key points
Same key + same request returns the stored response
Claim the key atomically (unique constraint or Redis NX)
Fingerprint the body; reject key reuse with different data
Commit result and business change together; pass keys to gateways
Scope per client and expire after a retention window
Common mistakes
Checking for the key and inserting it in two separate steps, leaving a race
Not comparing the request body, so a reused key silently returns the wrong result
Keeping keys in process memory with several workers
Treating the key as an authentication token
Forgetting to pass an idempotency key on to the payment gateway
Follow-ups
What should happen if the first attempt crashed halfway?
How long should you keep idempotency records?
How is this different from deduplicating in a message queue consumer?
Tips
Explain the lost-response scenario first
Highlight the atomic claim
Cover fingerprinting, scope and retention
48.fastapi-0048Hardsenior
How do you call other services reliably from FastAPI with httpx: shared clients, timeouts, retries and concurrency limits?
Create one httpx.AsyncClient per process in lifespan so connections are pooled, set explicit timeouts (connect, read, write, pool), retry only safe or idempotent calls with exponential backoff and jitter on network errors and 502/503/504, bound concurrency with a semaphore or client limits, and turn upstream failures into clear 502/503/504 responses. Consider circuit breakers and caching when a dependency is unstable. Test with httpx.MockTransport.
Full answer
Calling another service is where most latency and outages come from. A good client has these parts.
One shared client. httpx.AsyncClient() keeps a connection pool with keep-alive. Creating a client per request skips pooling and costs a TLS handshake each time. Create it in lifespan, store it on app.state, close it on shutdown.
Timeouts. httpx defaults to 5 seconds per phase, but set them explicitly: httpx.Timeout(connect=1, read=3, write=3, pool=1). pool is how long to wait for a free connection. A missing timeout turns one slow upstream into a pile of stuck requests.
Retries. Retry only when it is safe:
idempotent methods (GET, PUT, DELETE), or POSTs that carry an idempotency key,
errors that are probably temporary: connect errors, read timeouts, 502, 503, 504, 429 (honouring Retry-After).
Use exponential backoff with jitter (0.1s, 0.2s, 0.4s plus random) and a small maximum (2 to 3 retries), and keep the total under the caller's own deadline. Retrying at every layer multiplies traffic (a retry storm).
httpx.AsyncHTTPTransport(retries=n) only retries connection failures. For status-based retries use a loop or a library such as tenacity or stamina.
Limits. httpx.Limits(max_connections=100, max_keepalive_connections=20) bound sockets. A semaphore bounds how many concurrent calls one request fan-out can make.
Failure mapping. Convert upstream problems to proper responses: timeout to 504, connection error or bad upstream status to 502 or 503, with a short message and a log line carrying the request ID. Never leak upstream bodies blindly.
Circuit breaker. After many failures, stop calling for a cool-down period and fail fast, protecting both services. Add fallbacks (cached data) where acceptable.
Testing. httpx.MockTransport(handler) simulates timeouts and 503s with no network.
python
import asyncio
import random
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI, HTTPException, Request
from fastapi.testclient import TestClient
calls = {"n": 0}
def fake_upstream(request: httpx.Request) -> httpx.Response:
calls["n"] += 1
if request.url.path == "/flaky":
if calls["n"] < 3:
return httpx.Response(503, text="busy")
return httpx.Response(200, json={"fee_due": 4500})
if request.url.path == "/slow":
raise httpx.ReadTimeout("upstream too slow", request=request)
return httpx.Response(200, json={"ok": True})
TIMEOUT = httpx.Timeout(connect=1.0, read=3.0, write=3.0, pool=1.0)
RETRY_STATUS = {502, 503, 504}
async def get_with_retry(client: httpx.AsyncClient, url: str, attempts: int = 3) -> httpx.Response:
rng = random.Random(7) # fixed seed so the demo is repeatable
for attempt in range(1, attempts + 1):
try:
r = await client.get(url)
if r.status_code not in RETRY_STATUS:
return r
except (httpx.ConnectError, httpx.ReadTimeout):
if attempt == attempts:
raise
if attempt == attempts:
return r
await asyncio.sleep(0.01 * 2 ** attempt + rng.random() * 0.005) # backoff with jitter
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = httpx.AsyncClient(base_url="http://fees.internal", timeout=TIMEOUT,
limits=httpx.Limits(max_connections=50, max_keepalive_connections=10),
transport=httpx.MockTransport(fake_upstream))
yield
await app.state.http.aclose()
app = FastAPI(lifespan=lifespan)
@app.get("/fees/{path}")
async def fees(path: str, request: Request):
try:
r = await get_with_retry(request.app.state.http, f"/{path}")
except httpx.TimeoutException:
raise HTTPException(status_code=504, detail="Fee service timed out")
if r.status_code >= 500:
raise HTTPException(status_code=502, detail="Fee service unavailable")
return r.json()
with TestClient(app) as c:
print(c.get("/fees/flaky").json(), "after", calls["n"], "upstream calls")
print(c.get("/fees/slow").status_code, c.get("/fees/slow").json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. httpx.MockTransport plays the upstream service, so no network is used.
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):
{'fee_due': 4500} after 3 upstream calls
504 {'detail': 'Fee service timed out'}
Key points
One shared AsyncClient created in lifespan
Explicit connect/read/write/pool timeouts
Retry only safe calls, with backoff, jitter and a cap
Limits and semaphores bound concurrency
Map upstream failures to 502/503/504; test with MockTransport
Common mistakes
Creating a new AsyncClient for every request
Leaving out timeouts so one slow upstream exhausts the service
Retrying non-idempotent POSTs, causing duplicates
Retrying at every layer and creating a retry storm
Passing upstream error bodies straight to clients
Follow-ups
How does a circuit breaker work and where would you place it?
How would you propagate a deadline across several service calls?
What does httpx's pool timeout protect against?
Tips
Name the four timeout kinds
State which calls are safe to retry
Describe failure mapping and testing with MockTransport
49.fastapi-0049Hardsenior
How do you add observability to a FastAPI service: structured logs with a request ID, metrics and tracing?
Use a middleware that creates or accepts a request ID, stores it in a contextvar so every log line includes it, and logs one structured JSON line per request with method, path template, status and duration. Expose metrics (request count and latency histogram labelled by route template, not raw URL) for Prometheus, and use OpenTelemetry for distributed traces that propagate trace context to downstream calls. Keep log volume, label cardinality and personal data under control.
Full answer
Three signals, used together:
Logs: what happened. Make them structured (JSON) so tools can filter by fields, and correlate them with a request ID.
Middleware reads X-Request-ID (or generates a UUID), puts it in a contextvars.ContextVar, returns it in the response header, and a logging filter adds it to every record, including logs from libraries and services deep in the call stack. Contextvars flow correctly across await.
Log once per request at the end: method, route template (/students/{roll_no}), status, duration, user ID (not names or tokens). Do not log request bodies with passwords, tokens or personal data.
Log unexpected exceptions with stack traces and the request ID; keep expected 4xx at info or warning.
Write to stdout; let the platform ship it.
Metrics: how the system behaves over time. Prometheus style:
Counter http_requests_total{method, route, status} and histogram http_request_duration_seconds{route}.
Label with the route template from request.scope["route"].path, never the raw path; /students/1, /students/2... would create unbounded label values and overload the metrics store (high cardinality).
Add business and dependency metrics: database pool usage, queue depth, outbound call latency.
Watch the "golden signals": latency (p95, p99), traffic, errors, saturation.
Traces: where time went across services. OpenTelemetry instrumentation (opentelemetry-instrumentation-fastapi, -httpx, -sqlalchemy) creates spans and propagates the traceparent header. Put the trace ID in logs to jump from a log line to the trace.
Health: separate liveness and readiness endpoints; exclude them from noisy logs and latency alerts.
Alerts should be on symptoms users feel (error rate, p95 latency), with dashboards for diagnosis.
python
import contextvars
import io
import json
import logging
import time
import uuid
from collections import Counter
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
request_id_var = contextvars.ContextVar("request_id", default="-")
stream = io.StringIO()
class JsonFormatter(logging.Formatter):
def format(self, record):
payload = {"level": record.levelname, "msg": record.getMessage(), "request_id": request_id_var.get()}
payload.update(getattr(record, "extra_fields", {}))
return json.dumps(payload, sort_keys=True)
handler = logging.StreamHandler(stream)
handler.setFormatter(JsonFormatter())
log = logging.getLogger("campus")
log.addHandler(handler)
log.setLevel(logging.INFO)
log.propagate = False
REQUESTS = Counter() # a prometheus_client Counter/Histogram in a real service
app = FastAPI()
@app.middleware("http")
async def observe(request: Request, call_next):
rid = request.headers.get("X-Request-ID") or str(uuid.uuid4())
token = request_id_var.set(rid)
start = time.perf_counter()
try:
response = await call_next(request)
return_value = finish(request, response, rid, start)
finally:
request_id_var.reset(token)
return return_value
def finish(request: Request, response, rid: str, start: float):
route = request.scope.get("route")
template = route.path if route else "unmatched"
REQUESTS[(request.method, template, response.status_code)] += 1
response.headers["X-Request-ID"] = rid
log.info("request", extra={"extra_fields": {"method": request.method, "route": template,
"status": response.status_code,
"duration_s": int(time.perf_counter() - start)}})
return response
def check_fees(roll_no: str):
log.info("fee lookup") # deep in service code: still carries the request ID
@app.get("/students/{roll_no}")
def student(roll_no: str):
check_fees(roll_no)
return {"roll_no": roll_no}
c = TestClient(app)
c.get("/students/BCA-17", headers={"X-Request-ID": "req-abc"})
c.get("/students/BCA-18", headers={"X-Request-ID": "req-def"})
c.get("/nowhere")
for line in stream.getvalue().splitlines()[:2]:
print(line)
print(dict(REQUESTS))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Duration is logged in whole seconds in the log line so the output is identical on every run.
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):
{"level": "INFO", "msg": "fee lookup", "request_id": "req-abc"}
{"duration_s": 0, "level": "INFO", "method": "GET", "msg": "request", "request_id": "req-abc", "route": "/students/{roll_no}", "status": 200}
{('GET', '/students/{roll_no}', 200): 2, ('GET', 'unmatched', 404): 1}
Key points
Request ID in a contextvar, added to every log record
One structured log line per request with route template and duration
Metrics labelled by route template, not raw URL
OpenTelemetry for traces and context propagation
Never log secrets or personal data
Common mistakes
Using raw URL paths as metric labels and exploding cardinality
Logging request bodies with passwords or personal data
Passing the request ID through every function argument instead of a contextvar
Printing unstructured text that cannot be filtered
Alerting on every 4xx instead of user-visible error rates
Follow-ups
How do you propagate a trace across an HTTP call to another service?
What is metric cardinality and why does it matter?
How would you sample traces on a high-traffic service?
Tips
Explain the contextvar approach and why it survives await
Say route template, not raw path, for metrics
Link logs, metrics and traces by IDs
50.fastapi-0050Hardsenior
How would you add caching to a FastAPI API: HTTP caching headers with ETag, and server-side caching with Redis?
Use HTTP caching so clients, browsers and CDNs skip work: Cache-Control with max-age for public data, ETag and If-None-Match so clients revalidate cheaply with a 304 and no body, and Vary for headers that change the response. Use server-side caching (Redis or in-process TTL cache) for expensive computed results with explicit keys, TTLs and invalidation on writes, and protect against stampedes. Never cache per-user data in shared caches without private or Vary.
Full answer
Two layers solve different problems.
HTTP caching (client and CDN side)
Cache-Control: public, max-age=300 lets browsers and CDNs reuse a response for 5 minutes without asking. Suitable for public, slowly changing data such as a timetable. Use private for user-specific responses, no-store for sensitive data.
Validation with ETag: the server sends a fingerprint (for example a hash of the body or a version number). The client later sends If-None-Match: "<etag>". If unchanged, the server answers 304 Not Modified with no body: the client saves bandwidth, and the server can skip serialising if it can compute the ETag cheaply (from updated_at or a version column).
Vary: Accept-Encoding, Authorization tells caches which request headers change the response. A missing Vary can serve one user's data to another.
FastAPI does not add any of this automatically; set headers on the Response, or in a middleware.
Server-side caching
Cache expensive results (aggregations, calls to slow partners) in Redis with a key that includes every input: report:{class_id}:{term}.
TTL gives eventual freshness; invalidation on write (delete or update the key when marks change) gives immediate correctness. Do both.
Cache stampede: when a hot key expires, many requests recompute it at once. Use a lock around recomputation, early refresh with jittered TTLs, or serve slightly stale data while one request refreshes.
Cache negative results briefly (for not-found lookups) to protect the database.
Serialise with JSON or msgpack, not pickle, for data from shared stores.
Measure hit rate; a cache with a 10% hit rate is only added complexity.
In-process caches (functools.lru_cache, cachetools.TTLCache) are per worker, so each worker has its own copy; fine for small reference data, wrong when consistency across workers matters.
Rule: cache after the correctness story is clear: who may see this data, how stale may it be, and what event invalidates it.
python
import hashlib
import json
import time
from typing import Annotated
from fastapi import FastAPI, Header, Request, Response
from fastapi.testclient import TestClient
app = FastAPI()
TIMETABLE = {"version": 3, "monday": ["Maths", "DBMS", "Networks"]}
cache: dict[str, tuple[float, dict]] = {} # a Redis stand-in: key -> (expires_at, value)
computed = {"n": 0}
@app.get("/timetable")
def timetable(response: Response, if_none_match: Annotated[str | None, Header()] = None):
etag = '"v%d"' % TIMETABLE["version"] # cheap to compute: from a version column
response.headers["ETag"] = etag
response.headers["Cache-Control"] = "public, max-age=300"
response.headers["Vary"] = "Accept-Encoding"
if if_none_match == etag:
return Response(status_code=304, headers=dict(response.headers))
return TIMETABLE
def cached(key: str, ttl: float, compute):
hit = cache.get(key)
if hit and hit[0] > time.time():
return hit[1], "hit"
value = compute()
cache[key] = (time.time() + ttl, value)
return value, "miss"
def expensive_report(class_id: str) -> dict:
computed["n"] += 1
return {"class": class_id, "average": 74.5}
@app.get("/reports/{class_id}")
def report(class_id: str, response: Response):
value, status = cached(f"report:{class_id}", 60, lambda: expensive_report(class_id))
response.headers["X-Cache"] = status
response.headers["Cache-Control"] = "private, max-age=60"
return value
@app.post("/marks/{class_id}")
def update_marks(class_id: str):
cache.pop(f"report:{class_id}", None) # invalidate on write
return {"ok": True}
c = TestClient(app)
r = c.get("/timetable")
print(r.status_code, r.headers["etag"], r.headers["cache-control"])
r2 = c.get("/timetable", headers={"If-None-Match": r.headers["etag"]})
print(r2.status_code, repr(r2.content))
TIMETABLE["version"] = 4
print(c.get("/timetable", headers={"If-None-Match": '"v3"'}).status_code)
print([c.get("/reports/10A").headers["x-cache"] for _ in range(2)], "computations:", computed["n"])
c.post("/marks/10A")
print(c.get("/reports/10A").headers["x-cache"], "computations:", computed["n"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. A dict with expiry times stands in for Redis.
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 "v3" public, max-age=300
304 b''
200
['miss', 'hit'] computations: 1
miss computations: 2
Key points
Cache-Control for reuse; private vs public vs no-store
ETag + If-None-Match give cheap 304 revalidation
Vary prevents serving one user's data to another
Redis keys include all inputs; TTL plus invalidation on write
Guard against stampedes; in-process caches are per worker
Common mistakes
Caching per-user responses with public Cache-Control or without Vary
Caching in Redis without an invalidation plan
Using in-process caches and expecting consistency across workers
Building cache keys that leave out an input and return wrong data
Using pickle for data in a shared cache
Follow-ups
How would you stop a cache stampede on a popular report?
What is the difference between max-age and no-cache?
How would you derive ETags for list responses cheaply?
Tips
Separate HTTP caching from server-side caching
Explain ETag revalidation and the 304 flow
Talk about invalidation, staleness and who may see the data
51.fastapi-0051Easyfresher
How do you convert Pydantic v2 models to and from dicts, JSON and ORM objects with model_dump(), model_validate(), model_validate_json() and from_attributes?
In Pydantic v2, model_dump() turns a model into a dict, model_dump_json() into a JSON string, model_validate() builds a validated model from a dict or object, and model_validate_json() validates a JSON string directly. Setting from_attributes=True lets model_validate() read attributes from arbitrary objects such as ORM rows. These replace the v1 methods dict(), json(), parse_obj() and from_orm().
Full answer
Pydantic models validate on creation. Common conversions:
m.model_dump(): dict of Python values. Options: exclude_unset=True (only fields that were provided), exclude_none=True, include={...}, exclude={...}, by_alias=True, and mode="json" (turn dates, UUIDs and Decimals into JSON-compatible values).
m.model_dump_json(): a JSON string, produced by the fast Rust serializer.
Student.model_validate({"name": "Asha", "age": "17"}): validates a dict and coerces "17" to 17 (lax mode). Raises ValidationError with a list of errors.
Student.model_validate_json('{"name": "Asha"}'): parses and validates in one step; faster than json.loads followed by model_validate.
Student.model_validate(orm_obj) needs model_config = ConfigDict(from_attributes=True) (v1 called this orm_mode). FastAPI's response_model uses it to turn ORM objects into responses.
m.model_copy(update={"age": 18}) makes a copy (it does not re-validate the updated values).
v1 names still work in v2 but emit deprecation warnings: dict(), json(), parse_obj(), parse_raw(), from_orm(), copy().
Notes:
Validation errors are structured: exc.errors() gives loc, msg, type and input, and exc.json() serialises them.
model_dump() keeps nested models as dicts; use mode="json" before json.dumps.
Model fields keep Python types (datetime), so model_dump() returns a datetime but mode="json" returns an ISO string.
In FastAPI you rarely call these yourself: request bodies are validated automatically and return values are serialised, but they are essential in services, tests and background jobs.
python
from datetime import date
from pydantic import BaseModel, ConfigDict, ValidationError
class Student(BaseModel):
model_config = ConfigDict(from_attributes=True)
name: str
age: int
born: date | None = None
s = Student.model_validate({"name": "Asha", "age": "17", "born": "2009-03-04"}) # "17" is coerced to 17
print(s)
print(s.model_dump())
print(s.model_dump(mode="json"), s.model_dump(exclude={"born"}))
print(s.model_dump_json())
print(Student.model_validate_json('{"name": "Ravi", "age": 18}'))
part = Student(name="Kiran", age=16)
print(part.model_dump(exclude_unset=True), part.model_dump(exclude_none=True))
class OrmRow: # stands in for a SQLAlchemy object
def __init__(self):
self.name, self.age, self.born = "Meera", 19, None
print(Student.model_validate(OrmRow()))
print(s.model_copy(update={"age": 18}).age)
try:
Student.model_validate({"name": "X", "age": "abc"})
except ValidationError as exc:
print([(e["loc"], e["type"]) for e in exc.errors()])
model_dump and model_dump_json serialise; model_validate and model_validate_json parse
from_attributes=True reads ORM objects
exclude_unset is useful for PATCH-style updates
mode='json' makes output JSON-safe
v1 method names are deprecated
Common mistakes
Using v1 method names such as dict() and parse_obj() in new code
Forgetting from_attributes=True when validating ORM objects
Passing model_dump() output with datetimes straight to json.dumps
Expecting model_copy(update=...) to validate the new values
Follow-ups
How does model_dump(exclude_unset=True) help PATCH endpoints?
What does strict mode change?
How do you rename fields with aliases?
Tips
Name 4 conversion methods
Mention from_attributes
Mention deprecated v1 names
52.fastapi-0052Easyfresher
What is the difference between required, optional and nullable fields in Pydantic v2 and FastAPI, and how did Optional change from v1?
In Pydantic v2 a field with no default is required, even if its type allows None. str | None means None is accepted but the key must still be supplied; str | None = None makes it both nullable and optional. In v1, Optional[str] implicitly gave a default of None, which no longer happens. FastAPI follows these rules for body fields and uses defaults to decide whether query parameters are required.
Full answer
Three independent ideas:
Required or not: does a default exist?
Nullable or not: may the value be None?
Present or not: did the client send the key?
Declaration
Required?
Accepts null?
x: str
yes
no
x: str | None
yes (v2)
yes
x: str = "a"
no
no
x: str | None = None
no
yes
Migration trap: in Pydantic v1, x: Optional[str] silently meant = None. In v2, it is required, so old models that relied on this start rejecting payloads that omit the key. Write the default explicitly.
FastAPI effects:
Query and header parameters: a default makes them optional; no default makes them required (422 if missing).
Request bodies: missing required keys give 422 with type: "missing".
Response models: response_model_exclude_unset=True drops fields that were never set, which lets you distinguish "not provided" from "null".
PATCH updates: use model_dump(exclude_unset=True) so omitted fields are not overwritten with None; send explicit null to clear a nullable field.
OpenAPI marks fields in required only if they have no default; nullable types appear as anyOf with null (or nullable in older OpenAPI 3.0 output).
For mutable defaults, use Field(default_factory=list). Pydantic copies simple mutable defaults per instance, but the factory form is clearer.
python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class Student(BaseModel):
name: str
nickname: str | None # required, but None is allowed
email: str | None = None # optional and nullable
tags: list[str] = Field(default_factory=list)
@app.post("/students")
def create(s: Student):
return {"received": s.model_dump(), "set_by_client": sorted(s.model_fields_set)}
c = TestClient(app)
r = c.post("/students", json={"name": "Asha"})
print(r.status_code, [(e["loc"], e["type"]) for e in r.json()["detail"]])
print(c.post("/students", json={"name": "Asha", "nickname": None}).json())
print(c.post("/students", json={"name": "Asha", "nickname": "Ash", "email": None}).json())
props = c.get("/openapi.json").json()["components"]["schemas"]["Student"]
print("required in schema:", props["required"])
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 [(['body', 'nickname'], 'missing')]
{'received': {'name': 'Asha', 'nickname': None, 'email': None, 'tags': []}, 'set_by_client': ['name', 'nickname']}
{'received': {'name': 'Asha', 'nickname': 'Ash', 'email': None, 'tags': []}, 'set_by_client': ['email', 'name', 'nickname']}
required in schema: ['name', 'nickname']
Key points
No default means required, even if the type includes None
str | None = None is optional and nullable
v1 Optional implied a None default; v2 does not
exclude_unset distinguishes omitted from null
Use default_factory for mutable defaults
Common mistakes
Assuming Optional[str] gives a default of None in v2
Overwriting fields with None in PATCH because unset fields were dumped
Using a mutable default such as [] outside Field(default_factory=...)
Confusing missing keys with explicit null values
Follow-ups
How do you distinguish a missing field from an explicit null?
How does FastAPI decide if a query parameter is required?
What does model_fields_set contain?
Tips
Show the 2x2 of required and nullable
Call out the v1 behaviour change
Mention exclude_unset for PATCH
53.fastapi-0053Easyfresher
How do response_model_exclude_unset, response_model_exclude_none, response_model_include and response_model_by_alias shape a FastAPI response?
FastAPI validates and filters the returned value through response_model. Path operation parameters adjust the output: response_model_exclude_unset drops fields never set, response_model_exclude_none drops None values, response_model_include and response_model_exclude choose fields by name, and response_model_by_alias controls whether aliases are used. Prefer separate response models over include and exclude lists for anything public.
Full answer
After your function returns, FastAPI converts the value to the response_model type, filters fields that are not in the model (so a password_hash on the returned object never leaks if the model omits it), and serialises it.
Options on the decorator:
response_model_exclude_unset=True: omit fields that were not explicitly set when the returned object was created, so defaults do not appear. Useful for sparse PATCH-style responses.
response_model_exclude_defaults=True: omit fields whose value equals the default.
response_model_exclude_none=True: drop keys whose value is None.
response_model_include={"name"} and response_model_exclude={"email"}: a quick way to trim, but it hides the real contract, and the OpenAPI schema still shows the full model.
response_model_by_alias=True (the default): fields appear under their alias (Field(alias="rollNo")). Set it to False to use Python names.
Guidance:
For a public API, define explicit models (StudentPublic, StudentAdmin) and use them as response_model, because the docs, client generators and tests then match the real output.
exclude_unset works only when the returned object carries the "set" information, for example a Pydantic model instance or dict converted to a model. For ORM objects every attribute counts as set.
The return type annotation (-> StudentPublic) now also serves as the response model when response_model is omitted.
Filtering costs a validation pass; for very hot endpoints, return the right shape directly and set response_model=None.
python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class StudentPublic(BaseModel):
name: str
roll_no: str = Field(alias="rollNo")
nickname: str | None = None
grade: str = "C"
DB = {"name": "Asha", "rollNo": "BCA-1", "password_hash": "secret"} # a row with an extra private column
@app.get("/full", response_model=StudentPublic)
def full():
return DB # password_hash is filtered out
@app.get("/unset", response_model=StudentPublic, response_model_exclude_unset=True)
def unset():
return {"name": "Asha", "rollNo": "BCA-1"} # only these keys were set
@app.get("/none", response_model=StudentPublic, response_model_exclude_none=True)
def none():
return DB
@app.get("/names", response_model=StudentPublic, response_model_by_alias=False)
def names():
return DB
@app.get("/include", response_model=StudentPublic, response_model_include={"name", "grade"})
def include():
return DB
c = TestClient(app)
for path in ("full", "unset", "none", "names", "include"):
print(path, c.get(f"/{path}").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):
full {'name': 'Asha', 'rollNo': 'BCA-1', 'nickname': None, 'grade': 'C'}
unset {'name': 'Asha', 'rollNo': 'BCA-1'}
none {'name': 'Asha', 'rollNo': 'BCA-1', 'grade': 'C'}
names {'name': 'Asha', 'roll_no': 'BCA-1', 'nickname': None, 'grade': 'C'}
include {'name': 'Asha', 'grade': 'C'}
Key points
response_model filters and serialises the return value
exclude_unset and exclude_none shrink output
include and exclude lists hide the real contract in docs
by_alias controls alias use in output
Prefer separate public and admin models
Common mistakes
Returning ORM or dict objects with sensitive fields and no response model
Returning a model instance whose attributes use Python names when the response model validates by alias
Relying on include or exclude lists as the long-term contract
Expecting exclude_unset to work with ORM objects
Forgetting that aliases appear in output by default
Follow-ups
How does the return type annotation interact with response_model?
When would you set response_model=None?
How do you return different shapes for admins and users?
Tips
Explain the filtering effect
List the options
Prefer explicit models
54.fastapi-0054Easyfresher
How do GET, POST, PUT, PATCH and DELETE map to CRUD operations in FastAPI, and what status codes should each return?
GET reads (200, or 404 when missing), POST creates (201 with the new resource, ideally with a Location header), PUT replaces a resource completely (200 or 204), PATCH updates part of it (200), and DELETE removes it (204 No Content). GET is safe; GET, PUT and DELETE are idempotent; POST is neither. In FastAPI each is a decorator on a function, with status_code set where the default 200 is not right.
Full answer
Method
Purpose
Typical success
Safe
Idempotent
GET
read
200
yes
yes
POST
create (or run an action)
201
no
no
PUT
replace the whole resource
200 or 204
no
yes
PATCH
partial update
200
no
usually not guaranteed
DELETE
remove
204
no
yes
Design habits:
Use plural nouns for collections: /students and /students/{student_id}.
POST returns 201 Created with the created object and a Location header for the new URL. Validation errors are 422 (FastAPI) and conflicts such as duplicates are 409.
PUT needs the full representation, so missing fields are errors; PATCH accepts any subset: use a model whose fields are all optional and model_dump(exclude_unset=True).
DELETE returns 204 with an empty body (declare status_code=204, and return None). Deleting something already gone can return 204 or 404; choose one and document it.
Missing resources raise HTTPException(404).
Safe methods must not change state, because browsers, crawlers and caches may repeat GET requests.
FastAPI specifics: @app.post("/students", status_code=201, response_model=Student), and path parameters in the decorator path are passed to the function by name. Use separate schemas for input and output (create, update and read models) so clients cannot set ids or read internal fields.
An in-memory dict is fine for demos; production code uses a database with the same endpoint shapes.
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):
201 /students/1 {'name': 'Asha', 'grade': 'B', 'id': 1}
{'name': 'Asha', 'grade': 'A', 'id': 1}
{'name': 'Asha Rao', 'grade': 'A', 'id': 1}
422
204 b'' 404
Key points
Map verbs to CRUD with correct status codes
POST returns 201 and a Location header
PUT replaces; PATCH updates a subset
DELETE returns 204 with no body
GET must be safe; GET, PUT and DELETE are idempotent
Common mistakes
Returning 200 for creation instead of 201
Using GET for operations that change data
Treating PUT as a partial update
Returning a body with 204
Using verbs in URLs such as /createStudent
Follow-ups
Why is PUT idempotent and POST not?
How do you make POST safe to retry?
When is PATCH not idempotent?
Tips
Fill the table from memory
State status codes
Explain safe vs idempotent
55.fastapi-0055Easyfresher
When do you use the Request object in FastAPI, and what can you read from it (client address, URL, headers, raw body, app state)?
Declare a parameter typed as starlette Request to get the raw request: URL parts, client (host and port), headers, cookies, query parameters, path params, the raw body via await request.body() or JSON via await request.json(), plus request.app, request.state and request.scope. Use it for things the typed parameters cannot express; otherwise prefer typed Query, Header and body models, which validate input and appear in the OpenAPI docs.
Full answer
FastAPI passes a Request when a parameter is annotated with it. It is the Starlette object, so everything in the ASGI request is available:
request.client.host and .port (the TCP peer; behind a reverse proxy this is the proxy unless you run Uvicorn with --proxy-headers and trusted forwarded IPs).
request.app (the FastAPI instance, often with app.state holding shared clients) and request.state (a per-request namespace that middleware and dependencies can fill).
request.scope: the raw ASGI dictionary (route, root_path, server).
When to prefer typed parameters: they validate and document themselves. Parameters like x_token: Annotated[str, Header()] show up in /docs, while headers read from Request do not, and they are not validated.
Good uses of Request: raw body for webhook signature checks (the signature covers exact bytes), custom content types, client IP for logging, url_for to build links, and reading request.state set by middleware.
Cautions: the body can be read only once unless cached (await request.body() caches it in Starlette, but a dependency consuming request.stream() will exhaust it), and reading the whole body of a large upload into memory is risky; stream it instead.
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):
{'method': 'POST', 'path': '/inspect/3', 'query': {'verbose': '1'}, 'path_params': {'item_id': '3'}, 'agent': 'demo', 'client_is_set': True, 'raw_bytes': 7, 'json': {'a': 1}, 'service': 'campus-api', 'source': 'mobile', 'url_for': '/inspect/7'}
Key points
A parameter typed as Request gives the raw Starlette request
client.host is the TCP peer; proxies need forwarded headers configured
request.state and app.state share per-request and per-app data
Raw body is needed for signature verification
Typed parameters validate and appear in docs; Request does not
Common mistakes
Reading headers through Request and losing validation and docs
Trusting client.host behind a proxy without configuring forwarded headers
Loading a huge body with request.body() instead of streaming
Assuming the raw body is available after a dependency already consumed the stream
Follow-ups
How do you get the real client IP behind a load balancer?
What is the difference between app.state and request.state?
Why does webhook verification need the raw body?
Tips
List what Request exposes
Contrast with typed parameters
Mention proxies
56.fastapi-0056Easyfresher
How do you accept a list of values in a query parameter in FastAPI, and how do Query() alias, deprecated and validation arguments work?
Declare the type as list[str] and wrap it with Query() so repeated keys (?tag=a&tag=b) are collected, because a bare list would be read as a request body. Query() also takes alias (a name that is not a valid Python identifier), min_length, max_length, pattern, ge and le for numbers, description, deprecated=True to flag a parameter in the docs, and include_in_schema=False to hide one.
Full answer
Scalar types (int, str, bool) in the signature become query parameters if they are not part of the path. A list[int] needs Query explicitly:
The URL repeats the key; FastAPI collects the values into a list and converts each to the item type (list[int] rejects ?id=x with 422). Comma-separated values (?tags=a,b) arrive as one string unless you split them yourself.
Common Query() arguments:
alias="item-query": the external name, needed for hyphenated names such as x-page-size.
min_length, max_length, pattern: for strings. For lists, min_length and max_length limit the number of items.
ge, gt, le, lt: numeric bounds, applied to each item for lists of numbers.
description, title, examples: docs.
deprecated=True: shown as deprecated in /docs, while still working.
validation_alias and serialization_alias give finer control on models.
Required or optional is decided by the default: no default (or ...) is required; a default value or None makes it optional.
Booleans accept true, false, 1, 0, yes, no, on, off. For many related query parameters, group them in a Pydantic model with Annotated[FilterParams, Query()] (FastAPI 0.115+), which keeps signatures short.
Beware that query strings end up in logs and browser history, so never put secrets in them.
python
from typing import Annotated
from fastapi import FastAPI, Query
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/students")
def search(
tags: Annotated[list[str] | None, Query(max_length=3, description="Repeat the key for several tags")] = None,
ids: Annotated[list[int], Query()] = [],
page_size: Annotated[int, Query(alias="page-size", ge=1, le=50)] = 10,
q: Annotated[str | None, Query(min_length=2, pattern="^[a-z ]+$")] = None,
legacy: Annotated[str | None, Query(deprecated=True)] = None,
):
return {"tags": tags, "ids": ids, "page_size": page_size, "q": q}
c = TestClient(app)
print(c.get("/students?tags=a&tags=b&ids=1&ids=2&page-size=20&q=ravi").json())
print(c.get("/students?tags=a,b").json())
for url in ("/students?ids=x", "/students?page-size=500", "/students?q=A1", "/students?tags=1&tags=2&tags=3&tags=4"):
err = c.get(url).json()["detail"][0]
print(url, "->", err["loc"], err["type"])
params = {p["name"]: p for p in c.get("/openapi.json").json()["paths"]["/students"]["get"]["parameters"]}
print(params["legacy"].get("deprecated"), sorted(params))
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):
{'tags': ['a', 'b'], 'ids': [1, 2], 'page_size': 20, 'q': 'ravi'}
{'tags': ['a,b'], 'ids': [], 'page_size': 10, 'q': None}
/students?ids=x -> ['query', 'ids', 0] int_parsing
/students?page-size=500 -> ['query', 'page-size'] less_than_equal
/students?q=A1 -> ['query', 'q'] string_pattern_mismatch
/students?tags=1&tags=2&tags=3&tags=4 -> ['query', 'tags'] too_long
True ['ids', 'legacy', 'page-size', 'q', 'tags']
Key points
list[T] needs Query() so it is not read as a body
Repeat the key for lists: ?tag=a&tag=b
alias supports external names that are not valid identifiers
deprecated=True marks parameters in the docs
A default value makes a parameter optional
Common mistakes
Declaring list[str] without Query() so it is treated as a body
Sending comma-separated values and expecting a list
Forgetting the alias for hyphenated parameter names
Putting secrets in query strings
Using a mutable default carelessly (use None or a factory)
Follow-ups
How do you group many query parameters into a model?
How do you make a repeated key required to have at least one value?
What does include_in_schema=False do?
Tips
Show repeated-key lists
List 4 Query arguments
Explain required vs default
57.fastapi-0057Easyfresher
How do you accept a path containing slashes in FastAPI with {file_path:path}, and what security risk comes with it?
A plain path parameter stops at the next slash. Declaring {file_path:path} makes the parameter match the rest of the URL including slashes. When that value is used to open files, it must never be joined to a directory without checking: a client can send ../ segments (path traversal) to reach other files. Resolve the final path and verify it stays inside the allowed base directory, or use StaticFiles which does this for you.
Full answer
@app.get("/files/{file_path:path}") uses Starlette's path convertor, so /files/reports/2026/term1.pdf gives file_path = "reports/2026/term1.pdf". Without :path, the request would not match because the parameter stops at /.
The risk: code such as open(BASE / file_path) is dangerous. A request for /files/../../etc/passwd points outside BASE. Browsers and HTTP clients usually normalise literal .. segments before sending, but attackers use raw sockets or percent-encoded dots (%2e%2e/), which are decoded before they reach your function. Absolute paths are worse: Path("/srv/files") / "/etc/passwd" becomes /etc/passwd, because joining with an absolute path replaces the base.
Safe pattern:
python
BASE = Path("/srv/files").resolve()
target = (BASE / file_path).resolve()
if not target.is_relative_to(BASE) or not target.is_file():
raise HTTPException(404)
return FileResponse(target)
resolve() collapses .. and follows symlinks, so the containment check sees the real location. Return 404 rather than 403 so attackers learn nothing about which files exist.
Other defences: serve user content from object storage with signed URLs; use StaticFiles for static directories (it normalises and rejects traversal); keep uploads outside the code tree with generated names, never user-supplied filenames; run the process with minimal filesystem permissions; and set an allow-list of extensions.
Also note that FastAPI route order matters: a catch-all /{file_path:path} declared early will swallow other routes, so declare specific routes first.
python
import tempfile
from pathlib import Path
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse
from fastapi.testclient import TestClient
BASE = Path(tempfile.mkdtemp()).resolve()
(BASE / "reports").mkdir()
(BASE / "reports" / "term1.txt").write_text("term 1 report")
SECRET = BASE.parent / "outside-secret.txt"
SECRET.write_text("not for clients")
app = FastAPI()
@app.get("/unsafe/{file_path:path}")
def unsafe(file_path: str):
return FileResponse(BASE / file_path)
@app.get("/files/{file_path:path}")
def safe(file_path: str):
target = (BASE / file_path).resolve()
if not target.is_relative_to(BASE) or not target.is_file():
raise HTTPException(status_code=404, detail="Not found")
return FileResponse(target)
c = TestClient(app)
print(c.get("/files/reports/term1.txt").text)
print(c.get(f"/unsafe/%2e%2e/{SECRET.name}").text) # encoded dots: the traversal succeeds, this is the bug
print(c.get(f"/files/%2e%2e/{SECRET.name}").status_code)
print(c.get("/files//etc/passwd").status_code, c.get("/files/missing.txt").status_code)
print(Path("/srv/files") / "/etc/passwd")
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. The snippet creates a temporary directory and a file outside it to demonstrate traversal.
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):
term 1 report
not for clients
404
404 404
/etc/passwd
Key points
{name:path} matches slashes
Never join user input to a base directory without checking
resolve() then is_relative_to(BASE) blocks traversal
Absolute paths replace the base when joined
Declare catch-all routes last
Common mistakes
Joining user input to a directory and opening the result
Checking for '..' with string tests instead of resolving the path
Trusting user-supplied filenames for uploads
Returning 403 and revealing which paths exist
Declaring a catch-all path route before specific routes
Follow-ups
How does StaticFiles protect against traversal?
How would you serve private files with expiring links?
Why do symlinks matter in the check?
Tips
Show the :path convertor
Explain traversal with an example
Show resolve plus is_relative_to
58.fastapi-0058Easyfresher
How do you serve HTML pages with Jinja2Templates and static files with StaticFiles in FastAPI?
FastAPI can serve server-rendered pages through Starlette's Jinja2Templates: create it with a directory, return templates.TemplateResponse(request, "page.html", context) from a route declared with response_class=HTMLResponse, and mount StaticFiles at /static for CSS and images. Jinja2 autoescapes HTML by default for .html files, which protects against XSS, and url_for builds links to routes and static files.
Full answer
FastAPI is API-first, but it can also render HTML for small sites, admin tools or dashboards.
(Install jinja2.) In recent Starlette versions the request is the first argument to TemplateResponse; the older TemplateResponse(name, {"request": request, ...}) form is deprecated.
In templates: {{ roll_no }}, loops and conditions with {% for %} and {% if %}, inheritance with {% extends "base.html" %} and blocks, and {{ url_for('static', path='/app.css') }} for assets.
Security and behaviour:
Autoescaping is on for .html, so <script> in a student's name renders as text. Mark content safe (|safe) only for HTML you generated yourself.
response_class=HTMLResponse sets the content type and makes the OpenAPI docs show HTML.
Templates are cached; in development use --reload and auto_reload.
The dependency injection system works the same way: a dependency can supply the current user, and the template receives it in context.
StaticFiles handles ETag and Last-Modified headers and rejects path traversal; in production a CDN or reverse proxy normally serves static files.
For rich interactivity, FastAPI is more often paired with a separate frontend, with Jinja2 kept for emails, reports and admin pages.
python
import tempfile
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.testclient import TestClient
root = Path(tempfile.mkdtemp())
(root / "static").mkdir()
(root / "templates").mkdir()
(root / "static" / "app.css").write_text("body { color: navy; }")
(root / "templates" / "student.html").write_text(
'<link rel="stylesheet" href="{{ url_for(\'static\', path=\'/app.css\') }}">\n'
"<h1>{{ name }}</h1>\n"
"<ul>{% for s in subjects %}<li>{{ s }}</li>{% endfor %}</ul>"
)
app = FastAPI()
app.mount("/static", StaticFiles(directory=root / "static"), name="static")
templates = Jinja2Templates(directory=root / "templates")
@app.get("/students/{roll_no}", response_class=HTMLResponse)
def page(request: Request, roll_no: str):
return templates.TemplateResponse(request, "student.html",
{"name": "<script>alert(1)</script> Asha", "subjects": ["Maths", "DBMS"]})
c = TestClient(app)
r = c.get("/students/BCA-1")
print(r.status_code, r.headers["content-type"])
print(r.text)
print(c.get("/static/app.css").text, c.get("/static/missing.css").status_code)
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install jinja2`; the snippet writes its templates to a temporary folder.
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 text/html; charset=utf-8
<link rel="stylesheet" href="http://testserver/static/app.css">
<h1><script>alert(1)</script> Asha</h1>
<ul><li>Maths</li><li>DBMS</li></ul>
body { color: navy; } 404
Key points
Jinja2Templates plus TemplateResponse render HTML
Mount StaticFiles for assets
Autoescaping protects from XSS; avoid |safe on user input
Pass request first in recent Starlette versions
Serve static files from a CDN or proxy in production
Common mistakes
Using |safe on user-supplied text
Using the deprecated TemplateResponse(name, {'request': request}) call style
Serving static files through Python in production at scale
Forgetting to install jinja2
Trying to build a heavy interactive UI only with Jinja2
Follow-ups
How would you pass the current user to every template?
How does FastAPI serve HTML differently from JSON in OpenAPI?
How do you cache templates in production?
Tips
Show setup in three lines
Mention autoescape
Say CDN in production
59.fastapi-0059Easyfresher
How do you read FastAPI's 422 validation error response, and what do loc, msg, type and input mean?
When request data fails validation, FastAPI returns 422 Unprocessable Entity with a JSON body {"detail": [ ... ]}. Each item has loc (where the problem is: body, query, path, header, cookie, followed by the field path), msg (human text), type (a stable machine code such as missing or int_parsing), and often input (the offending value) and ctx (constraint details). Clients should use loc and type, not parse msg.
Full answer
Example response for a bad body:
json
{"detail": [
{"type": "missing", "loc": ["body", "name"], "msg": "Field required", "input": {...}},
{"type": "int_parsing", "loc": ["body", "age"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "abc"}
]}
Reading each part:
loc: a path from the request source down to the field. The first element is the source: "body", "query", "path", "header" or "cookie". Nested models and lists extend it: ["body", "marks", 2, "score"] means the third item of marks. With a single non-embedded body model the model name is not part of loc.
type: stable codes from Pydantic v2 such as missing, string_too_short, greater_than_equal, int_parsing, literal_error, value_error, json_invalid. Use these in client logic and tests.
msg: English text; may change between versions.
input: the value received, helpful in development. Consider hiding it in production if it can include sensitive data (override the handler).
ctx: constraint values, e.g. {"min_length": 3}.
Notes:
Several errors are reported together, so a client can fix all fields in one round trip.
Malformed JSON gives json_invalid with a position in ctx.
Wrong types for path parameters are also 422, not 404.
Errors raised in your own code with HTTPException use {"detail": "text"} instead, so clients see two shapes unless you standardise (see custom exception handlers).
Response validation errors (your function returned bad data) are a server bug and result in a 500, not a 422.
Frontend tip: map loc[-1] to the form field name to show messages beside inputs.
python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class Mark(BaseModel):
subject: str
score: int = Field(ge=0, le=100)
class Student(BaseModel):
name: str = Field(min_length=3)
marks: list[Mark]
@app.post("/students/{roll_no}")
def create(roll_no: int, student: Student, page: int = 1):
return {"ok": True}
c = TestClient(app)
body = {"name": "Al", "marks": [{"subject": "Maths", "score": 90}, {"subject": "DBMS", "score": 120}]}
r = c.post("/students/abc?page=x", json=body)
print(r.status_code)
for e in r.json()["detail"]:
print(e["loc"], e["type"], "|", e["msg"], "|", e.get("ctx"))
r = c.post("/students/1", content="{bad json", headers={"content-type": "application/json"})
print(r.json()["detail"][0]["type"], r.json()["detail"][0]["loc"])
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
['path', 'roll_no'] int_parsing | Input should be a valid integer, unable to parse string as an integer | None
['query', 'page'] int_parsing | Input should be a valid integer, unable to parse string as an integer | None
['body', 'name'] string_too_short | String should have at least 3 characters | {'min_length': 3}
['body', 'marks', 1, 'score'] less_than_equal | Input should be less than or equal to 100 | {'le': 100}
json_invalid ['body', 1]
Key points
422 means the request failed validation; body is {'detail': [...]}
loc starts with the source: body, query, path, header or cookie
type is a stable machine code; msg is for people
All errors are reported together
HTTPException errors use a different shape unless standardised
Common mistakes
Parsing the msg text in client code
Assuming one error per response
Exposing input values that may contain sensitive data
Mixing the 422 list shape and HTTPException string shape without a standard
Follow-ups
How would you convert 422 errors into one error format?
How do you hide input in production?
Why is a bad path parameter a 422 rather than a 404?
Tips
Explain loc with a nested example
Say use type not msg
Mention both error shapes
60.fastapi-0060Easyfresher
How do you model nested objects and lists in a FastAPI request body, and how are they validated?
Use Pydantic models as field types inside other models: a Student with address: Address and marks: list[Mark]. FastAPI validates every level, reports errors with a full loc path, documents the nested structure in OpenAPI, and converts the data into model instances. Constraints on collections use Field (min_length, max_length) and unique items can be checked with a set type or a validator.
Full answer
Models compose naturally:
python
class Address(BaseModel):
city: str
pin: str = Field(pattern=r"^\d{6}$")
class Mark(BaseModel):
subject: str
score: int = Field(ge=0, le=100)
class Student(BaseModel):
name: str
address: Address
marks: list[Mark] = Field(min_length=1, max_length=10)
tags: set[str] = set()
Behaviour:
The incoming JSON object nests the same way: {"name": "Asha", "address": {...}, "marks": [{...}]}.
Validation is recursive. Errors include the position: ["body", "marks", 1, "score"].
list[Mark] validates each item. set[str] removes duplicates and, in JSON output, becomes a list. dict[str, int] accepts arbitrary string keys with integer values (useful for maps like subject to score).
The nested models appear in /docs under components.schemas, so clients can generate types from them.
A body that is only a list (list[Mark]) is allowed: declare marks: list[Mark] as the parameter and send a JSON array.
Within the function you get typed objects: student.address.city, and for m in student.marks. Convert with model_dump() when you need dicts.
Design tips: keep payloads shallow where possible; deeply nested bodies are hard to validate, patch and document. For read-heavy responses use separate response models. Limit collection size to avoid denial of service from huge arrays, and set a maximum request body size at the proxy or ASGI layer. Recursive structures (a tree of comments) need forward references: children: list["Comment"] = [], followed by model_rebuild() if required.
python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class Address(BaseModel):
city: str
pin: str = Field(pattern=r"^\d{6}$")
class Mark(BaseModel):
subject: str
score: int = Field(ge=0, le=100)
class Student(BaseModel):
name: str
address: Address
marks: list[Mark] = Field(min_length=1, max_length=3)
tags: set[str] = set()
@app.post("/students")
def create(student: Student):
best = max(student.marks, key=lambda m: m.score)
return {"city": student.address.city, "best": best.subject, "tags": sorted(student.tags)}
c = TestClient(app)
good = {"name": "Asha", "address": {"city": "Pune", "pin": "411001"},
"marks": [{"subject": "Maths", "score": 91}, {"subject": "DBMS", "score": 84}], "tags": ["a", "a", "b"]}
print(c.post("/students", json=good).json())
bad = {**good, "address": {"city": "Pune", "pin": "41"}, "marks": [{"subject": "Maths", "score": 101}]}
print([(e["loc"], e["type"]) for e in c.post("/students", json=bad).json()["detail"]])
print([(e["loc"], e["type"]) for e in c.post("/students", json={**good, "marks": []}).json()["detail"]])
print(sorted(c.get("/openapi.json").json()["components"]["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):
{'city': 'Pune', 'best': 'Maths', 'tags': ['a', 'b']}
[(['body', 'address', 'pin'], 'string_pattern_mismatch'), (['body', 'marks', 0, 'score'], 'less_than_equal')]
[(['body', 'marks'], 'too_short')]
['Address', 'HTTPValidationError', 'Mark', 'Student', 'ValidationError']
Key points
Models nest as field types; validation is recursive
Errors carry a full loc path including list indexes
Constrain collection sizes with Field
Nested models appear in OpenAPI components
Keep bodies shallow and limit sizes
Common mistakes
Creating very deep or unbounded nested payloads
Not limiting list sizes
Forgetting forward references for recursive models
Mutating nested objects from shared defaults
Follow-ups
How do you validate that list items are unique?
How would you accept a bare JSON array as the body?