Questions 21–40 of 100 · 0 of 20 on this page marked learned
21.fastapi-0021Mediummid
How do field_validator and model_validator work in Pydantic v2, and when do you use each?
@field_validator("field") runs custom logic for one field; mode="after" (the default) receives the already-parsed value and mode="before" receives raw input. @model_validator(mode="after") sees the whole validated model and suits cross-field rules such as end_date after start_date; mode="before" can reshape raw input. Raise ValueError with a clear message; FastAPI turns it into a 422 with the field location.
Full answer
Pydantic v2 replaced v1's @validator and @root_validator with @field_validator and @model_validator.
Must be a classmethod. Return the (possibly changed) value.
mode="after" (default): runs after type parsing, so v already has the declared type.
mode="before": runs on raw input, useful to accept "88%" and turn it into 88 before int parsing.
mode="wrap" and mode="plain" exist for full control.
One validator can cover several fields: @field_validator("first_name", "last_name").
info: ValidationInfo gives access to already-validated fields (info.data), but field order then matters. Prefer a model validator for cross-field logic.
@model_validator
python
@model_validator(mode="after")
def check_dates(self) -> Self:
if self.end < self.start:
raise ValueError("end must be after start")
return self
mode="after": an instance method that receives the validated model. Return self.
mode="before": a classmethod that receives raw data (often a dict) and returns data. Use it to accept legacy input shapes.
Errors: raise ValueError (or PydanticCustomError for a custom type code). FastAPI returns 422; field validators report the field's location, model validators report the body.
Alternatives: reusable validators via Annotated[str, AfterValidator(func)] or BeforeValidator, which attach logic to a type instead of a model. Good when the same rule (like normalising phone numbers) applies in many models.
Keep validators pure and fast. Do not query databases in validators; check things like "email already registered" in the service layer, where you can return a proper 409.
python
from datetime import date
from typing import Annotated, Self
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import AfterValidator, BaseModel, field_validator, model_validator
def indian_mobile(v: str) -> str:
digits = "".join(ch for ch in v if ch.isdigit())[-10:]
if len(digits) != 10 or digits[0] not in "6789":
raise ValueError("must be a 10-digit mobile number")
return digits
Mobile = Annotated[str, AfterValidator(indian_mobile)]
class LeaveRequest(BaseModel):
roll_no: str
attendance: int
start: date
end: date
parent_mobile: Mobile
@field_validator("roll_no")
@classmethod
def normalise_roll(cls, v: str) -> str:
return v.strip().upper()
@field_validator("attendance", mode="before")
@classmethod
def strip_percent(cls, v):
return v.rstrip("%") if isinstance(v, str) else v
@model_validator(mode="after")
def check_dates(self) -> Self:
if self.end < self.start:
raise ValueError("end date must be on or after start date")
return self
app = FastAPI()
@app.post("/leave")
def apply(req: LeaveRequest):
return req
c = TestClient(app)
ok = {"roll_no": " bca-17 ", "attendance": "82%", "start": "2026-12-10", "end": "2026-12-12",
"parent_mobile": "+91 98765 43210"}
print(c.post("/leave", json=ok).json())
for bad in ({**ok, "parent_mobile": "12345"}, {**ok, "end": "2026-12-01"}):
for e in c.post("/leave", json=bad).json()["detail"]:
print(e["loc"], "->", e["msg"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. An after-model validator runs only when every field is valid, so the date error is shown with a separate request.
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', 'attendance': 82, 'start': '2026-12-10', 'end': '2026-12-12', 'parent_mobile': '9876543210'}
['body', 'parent_mobile'] -> Value error, must be a 10-digit mobile number
['body'] -> Value error, end date must be on or after start date
Key points
field_validator for one field; model_validator for cross-field rules
mode='before' sees raw input; mode='after' sees parsed values
Field validators are classmethods returning the value
After model validators return self
AfterValidator/BeforeValidator attach logic to reusable types
Common mistakes
Using v1's @validator and @root_validator in new v2 code
Forgetting @classmethod on field validators or forgetting to return the value
Doing cross-field checks in a field validator that depends on field order
Querying the database inside validators
Follow-ups
When would you use mode='before' rather than mode='after'?
How do you reuse one validation rule across many models?
Where should 'email already registered' be checked, and why not in a validator?
Tips
Show both decorators with the right signatures
Explain before and after modes with a concrete example
Mention AfterValidator for reusable rules
22.fastapi-0022Mediummid
What changed between Pydantic v1 and v2 that matters for FastAPI code?
Pydantic v2 has a Rust core that makes validation much faster, and renamed many APIs: .dict() and .json() became model_dump() and model_dump_json(), parse_obj became model_validate, orm_mode became from_attributes, class Config became model_config = ConfigDict(...), @validator and @root_validator became @field_validator and @model_validator, and Field(regex=) became pattern=. Optional fields without defaults are now required, and type coercion is stricter in places.
Full answer
FastAPI supports Pydantic v2 since 0.100 and current releases require it. Interviewers ask about v2 because many codebases are still mid-migration.
Renames you will meet daily:
v1
v2
obj.dict()
obj.model_dump()
obj.json()
obj.model_dump_json()
Model.parse_obj(d)
Model.model_validate(d)
Model.parse_raw(s)
Model.model_validate_json(s)
Model.schema()
Model.model_json_schema()
obj.copy(update=...)
obj.model_copy(update=...)
class Config: orm_mode = True
model_config = ConfigDict(from_attributes=True)
@validator, @root_validator
@field_validator, @model_validator
Field(regex=...), min_items
Field(pattern=...), min_length
__fields__
model_fields
BaseSettings in pydantic
separate pydantic-settings package
Behaviour changes that cause bugs:
Optional[int] without a default is now required (it may be None, but must be sent). Write int | None = None for truly optional fields.
Lax conversion is narrower: v2 no longer turns 1.5 into 1 for an int field, and numbers are not converted to strings by default (str field with 123 fails). ConfigDict(coerce_numbers_to_str=True) restores that if needed.
Error format changed: each error has type, loc, msg, input, and url. Tests that assert on old error messages break.
model_dump(mode="json") gives JSON-safe types (dates as strings) in a dict.
Validators: @field_validator must be a classmethod; values became info.data.
Migration approach:
Run bump-pydantic, the official codemod, for mechanical renames.
Fix deprecation warnings (v1 names still work in v2 with warnings, until removed).
Re-run tests, especially ones that check error messages or edge-case coercion.
Measure: serialisation-heavy endpoints often get noticeably faster.
python
import warnings
from typing import Optional
from pydantic import BaseModel, ConfigDict, ValidationError, field_validator
class StudentRow: # stands in for an ORM object
id, name, marks = 1, "Tanvi", 91
class Student(BaseModel):
model_config = ConfigDict(from_attributes=True) # v1: class Config: orm_mode = True
id: int
name: str
marks: int
nickname: Optional[str] # v2: required, but may be None
@field_validator("name")
@classmethod
def title_case(cls, v: str) -> str:
return v.title()
try:
Student.model_validate(StudentRow())
except ValidationError as e:
print("missing:", e.errors()[0]["loc"], e.errors()[0]["type"])
s = Student.model_validate({"id": 1, "name": "tanvi", "marks": 91, "nickname": None})
print(s.model_dump(), s.model_dump_json())
try:
Student(id=1, name="x", marks=91.5, nickname=None)
except ValidationError as e:
print("float to int:", e.errors()[0]["type"])
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
s.dict() # v1 name still works, with a warning
print("v1 .dict() warning:", caught[0].category.__name__)
Leaving v1 method names and ignoring deprecation warnings until they are removed
Asserting on exact v1 error messages in tests
Importing BaseSettings from pydantic instead of pydantic-settings
Follow-ups
What does bump-pydantic do and what does it not handle?
How did lax conversion change between v1 and v2?
How would you migrate a 200-model codebase safely?
Tips
Know at least five renames without looking
Call out the Optional behaviour change, it causes real bugs
Describe a migration plan, not just the differences
23.fastapi-0023Mediummid
How do you write middleware in FastAPI, and what are the trade-offs between @app.middleware('http') and pure ASGI middleware?
@app.middleware("http") (Starlette's BaseHTTPMiddleware) receives the request and a call_next function, runs code before and after the endpoint, and can modify the response; it is simple and fine for headers and timing. Pure ASGI middleware is a class that wraps the app's (scope, receive, send) interface; it is more work but avoids BaseHTTPMiddleware's overhead and limitations with streaming responses and context variables. Middleware runs for every request, including 404s, in the reverse order of being added.
Full answer
Middleware wraps the whole application. Each request passes through it before reaching routing and the endpoint, and each response passes back through it.
Less overhead per request (BaseHTTPMiddleware wraps streams and tasks).
Works naturally with streaming responses and WebSockets (BaseHTTPMiddleware only handles HTTP).
Context variables set inside it are visible to the endpoint.
Uses for middleware: request IDs, timing and logging, security headers, CORS, GZip, trusted host checks, HTTPS redirect.
When not to use middleware: logic that needs route information or applies to some routes only fits better in dependencies. Authentication is usually a dependency so it appears in OpenAPI and can vary per route.
Exceptions: unhandled exceptions from the endpoint propagate through call_next. Starlette's ServerErrorMiddleware is always outermost, so a 500 response is still produced.
python
import itertools
import time
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
app = FastAPI()
counter = itertools.count(1)
@app.middleware("http")
async def timing(request: Request, call_next):
start = time.perf_counter()
response = await call_next(request)
response.headers["X-Process-Time"] = f"{time.perf_counter() - start:.4f}"
return response
class RequestIDMiddleware:
"""Pure ASGI middleware: adds X-Request-ID without wrapping the response body."""
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
request_id = f"req-{next(counter)}".encode()
scope.setdefault("state", {})["request_id"] = request_id.decode()
async def send_with_id(message):
if message["type"] == "http.response.start":
message.setdefault("headers", []).append((b"x-request-id", request_id))
await send(message)
await self.app(scope, receive, send_with_id)
app.add_middleware(RequestIDMiddleware)
@app.get("/marks")
def marks(request: Request):
return {"request_id": request.state.request_id}
c = TestClient(app)
r = c.get("/marks")
print(r.json(), r.headers["x-request-id"], "x-process-time" in r.headers)
r = c.get("/missing")
print(r.status_code, r.headers["x-request-id"], "x-process-time" in r.headers)
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. X-Process-Time varies per run, so the script only checks that the header exists.
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):
{'request_id': 'req-1'} req-1 True
404 req-2 True
Key points
@app.middleware('http') is simple: request, call_next, response
Last added middleware runs first
Pure ASGI middleware has less overhead and handles streaming
Middleware runs on every request, even 404s
Per-route logic like auth fits better in dependencies
Common mistakes
Doing authentication in middleware so it is invisible in OpenAPI and hard to vary per route
Reading the request body in BaseHTTPMiddleware and breaking the endpoint's access to it
Adding middleware in the wrong order, for example CORS inside another middleware that returns early
Doing slow work in middleware that runs on every request
Follow-ups
Why might BaseHTTPMiddleware cause problems with StreamingResponse?
How would you propagate a request ID into log records?
In which order do three added middlewares run?
Tips
Show both styles and say when to pick each
Explain the ordering rule
Say what should be a dependency instead
24.fastapi-0024Mediummid
What is CORS, and how do you configure it correctly in FastAPI?
CORS (Cross-Origin Resource Sharing) is how a server tells browsers that JavaScript from another origin may read its responses. Without it, the browser's same-origin policy blocks those reads. In FastAPI, add CORSMiddleware with an explicit allow_origins list, the methods and headers you need, and allow_credentials=True only when cookies or auth headers must be sent; wildcard origins cannot be combined with credentials.
Full answer
An origin is scheme + host + port: https://app.college.edu and https://api.college.edu are different origins. Browsers apply the same-origin policy: a page's JavaScript can send requests to another origin, but cannot read the response unless that server allows it through CORS headers.
CORS does not protect your API from other servers, scripts or curl. It only controls what browsers let web pages read. Authentication still has to protect data.
How it works:
Simple requests (GET or POST with simple headers) are sent directly; the browser checks Access-Control-Allow-Origin on the response.
Other requests (PUT, DELETE, JSON Content-Type, Authorization header) trigger a preflight OPTIONS request first. The server answers with allowed methods and headers, and the browser then sends the real request.
allow_origins: exact origins. allow_origin_regex for patterns like preview deployments.
allow_credentials=True: lets the browser send cookies or HTTP auth. The spec forbids Access-Control-Allow-Origin: * with credentials, so use explicit origins.
expose_headers: response headers JavaScript may read beyond the basic set.
max_age: how long browsers cache preflight results, reducing OPTIONS traffic.
Add CORSMiddleware so it wraps everything (adding it last makes it outermost); otherwise error responses produced by inner layers may lack CORS headers, and the browser reports a CORS error that hides the real error.
python
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.testclient import TestClient
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.college.edu", "http://localhost:5173"],
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
allow_credentials=True,
expose_headers=["X-Total-Count"],
max_age=600,
)
@app.get("/notices")
def notices(response: Response):
response.headers["X-Total-Count"] = "2"
return ["Exam on Monday", "Library closed Sunday"]
c = TestClient(app)
pre = c.options("/notices", headers={"Origin": "https://app.college.edu",
"Access-Control-Request-Method": "PUT",
"Access-Control-Request-Headers": "authorization"})
print("preflight:", pre.status_code, pre.headers["access-control-allow-origin"],
pre.headers["access-control-allow-methods"], pre.headers["access-control-max-age"])
r = c.get("/notices", headers={"Origin": "https://app.college.edu"})
print("allowed origin:", r.headers.get("access-control-allow-origin"),
r.headers.get("access-control-allow-credentials"), r.headers.get("access-control-expose-headers"))
r = c.get("/notices", headers={"Origin": "https://evil.example"})
print("other origin header present:", "access-control-allow-origin" in r.headers, "| status:", r.status_code)
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. The request from the unknown origin still returns 200; the browser, not the server, blocks the page from reading it.
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):
preflight: 200 https://app.college.edu GET, POST, PUT, DELETE 600
allowed origin: https://app.college.edu true X-Total-Count
other origin header present: False | status: 200
Key points
CORS lets browsers read cross-origin responses
It is not an access control for non-browser clients
Preflight OPTIONS for non-simple requests
No wildcard origin with credentials
expose_headers and max_age are often forgotten
Common mistakes
Thinking CORS protects the API from non-browser clients
Using allow_origins=['*'] together with allow_credentials=True
Forgetting expose_headers, so the front end cannot read custom headers
Misdiagnosing a server error as a CORS error because the error response lacks CORS headers
Follow-ups
Why does a JSON POST trigger a preflight request?
How would you allow all preview deployments like pr-123.app.college.edu?
Why is CORS not a security boundary for your API?
Tips
Define origin precisely
Explain preflight and the credentials rule
Say clearly what CORS does not protect
25.fastapi-0025Mediummid
How do you implement OAuth2 password flow with JWT access tokens in FastAPI?
Use OAuth2PasswordBearer(tokenUrl="token") to read the Bearer token, a /token endpoint that accepts OAuth2PasswordRequestForm, verifies the password hash (for example Argon2 via pwdlib) and returns a signed JWT with sub and exp claims, and a get_current_user dependency that decodes and verifies the token with PyJWT and loads the user. Keep access tokens short-lived, store the signing key in configuration, and return 401 with WWW-Authenticate: Bearer on failure.
Full answer
The pieces:
Password storage: never store plain passwords. Hash with Argon2 or bcrypt. The current FastAPI docs use pwdlib with Argon2 (PasswordHash.recommended()); passlib is unmaintained.
Token endpoint: POST /token with form fields username and password (the OAuth2 spec requires form data, which is why OAuth2PasswordRequestForm is used). On success, return {"access_token": ..., "token_type": "bearer"}.
JWT creation: a JSON Web Token is a signed, base64-encoded JSON payload. Include sub (the user ID or username), exp (expiry), and optionally scopes or roles. Sign with HS256 and a secret from settings, or RS256/ES256 with a private key when other services must verify tokens with a public key.
Protected routes: oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") reads Authorization: Bearer <token> and returns 401 if missing. get_current_user decodes with jwt.decode(token, key, algorithms=["HS256"]), which verifies the signature and exp, then loads the user and checks it is active.
Security details interviewers look for:
Always pass algorithms=[...] to decode; never accept the algorithm from the token header blindly.
JWTs are signed, not encrypted. Anyone can read the payload, so do not put secrets in it.
Short access token lifetime (5 to 30 minutes) plus refresh tokens stored securely (httpOnly cookie or server-side), rotated on use.
Revocation is hard with stateless tokens: keep lifetimes short, or keep a deny-list of token IDs (jti) in Redis for logout and password change.
Same error message for "no such user" and "wrong password", and run the hasher for unknown users too, to avoid user enumeration.
Rate limit /token.
OAuth2PasswordBearer adds an Authorize button in /docs.
For production, many teams use an identity provider (Keycloak, Auth0, Cognito, Entra ID) and only verify its tokens in FastAPI.
python
from datetime import datetime, timedelta, timezone
from typing import Annotated
import jwt
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.testclient import TestClient
from pwdlib import PasswordHash
SECRET_KEY = "demo-only-change-me-load-from-env-0123456789abcdef" # from settings in real code
ALGORITHM = "HS256"
password_hash = PasswordHash.recommended() # Argon2
DUMMY_HASH = password_hash.hash("dummy")
USERS = {"meena": {"username": "meena", "hash": password_hash.hash("Canteen@12"), "active": True}}
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
CREDENTIALS_ERROR = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"})
def create_access_token(sub: str, minutes: int = 15) -> str:
expire = datetime.now(timezone.utc) + timedelta(minutes=minutes)
return jwt.encode({"sub": sub, "exp": expire}, SECRET_KEY, algorithm=ALGORITHM)
@app.post("/token")
def login(form: Annotated[OAuth2PasswordRequestForm, Depends()]):
user = USERS.get(form.username)
if not user:
password_hash.verify(form.password, DUMMY_HASH) # similar timing for unknown users
raise HTTPException(status_code=401, detail="Incorrect username or password")
if not password_hash.verify(form.password, user["hash"]):
raise HTTPException(status_code=401, detail="Incorrect username or password")
return {"access_token": create_access_token(user["username"]), "token_type": "bearer"}
def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
except jwt.InvalidTokenError:
raise CREDENTIALS_ERROR
user = USERS.get(payload.get("sub"))
if user is None or not user["active"]:
raise CREDENTIALS_ERROR
return user
@app.get("/me")
def me(user: Annotated[dict, Depends(get_current_user)]):
return {"username": user["username"]}
c = TestClient(app)
print(c.post("/token", data={"username": "meena", "password": "wrong"}).json())
token = c.post("/token", data={"username": "meena", "password": "Canteen@12"}).json()["access_token"]
print(c.get("/me", headers={"Authorization": f"Bearer {token}"}).json())
print(c.get("/me").status_code)
expired = create_access_token("meena", minutes=-1)
r = c.get("/me", headers={"Authorization": f"Bearer {expired}"})
print(r.status_code, r.headers["www-authenticate"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install pyjwt "pwdlib[argon2]" python-multipart`. The secret key is a demo value.
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, PyJWT 2.15.1, pwdlib 0.4.2):
{'detail': 'Incorrect username or password'}
{'username': 'meena'}
401
401 Bearer
Key points
Hash passwords with Argon2 or bcrypt (pwdlib)
/token accepts form data and returns a bearer JWT
JWT has sub and exp; decode with explicit algorithms
get_current_user dependency verifies and loads the user
Storing plain or fast-hashed (MD5, SHA-256) passwords
Calling jwt.decode without the algorithms argument
Putting sensitive data in the JWT payload, which is only encoded
Issuing long-lived access tokens with no revocation plan
Different error messages for unknown user and wrong password
Follow-ups
How would you implement refresh tokens and rotation?
How do you log a user out when JWTs are stateless?
When would you use RS256 instead of HS256?
Tips
Name every piece: hashing, token endpoint, JWT claims, dependency
Mention explicit algorithms and short expiry
Discuss revocation, it separates mid from senior answers
26.fastapi-0026Mediummid
How do BackgroundTasks work in FastAPI, and when should you use a real task queue instead?
Add a BackgroundTasks parameter and call background_tasks.add_task(func, *args); FastAPI runs the function after the response has been sent, in the same process. It suits small, quick follow-up work like sending one email or writing an audit log. For heavy, slow or must-not-be-lost work, use a task queue (Celery, ARQ, Dramatiq, RQ) with a broker, because in-process tasks are lost if the server restarts and they compete with requests for resources.
Full answer
BackgroundTasks (from Starlette) lets an endpoint return quickly and finish small jobs afterwards:
Tasks are collected during the request and run after the response is sent, in order.
def tasks run in the thread pool; async def tasks run on the event loop (so they must not block).
Dependencies can also accept BackgroundTasks; FastAPI merges all tasks for the request.
The client does not wait, but the worker process does: the connection slot and memory stay in use until tasks finish.
Limits:
No persistence. If the process restarts or crashes, pending tasks are lost.
No retries, scheduling, or visibility (no dashboard, no status).
Runs in the web process, so heavy work slows down request handling. CPU-heavy work in an async def task blocks the event loop.
Resources from yield dependencies follow their scope. With the default scope="request", current FastAPI closes them after background tasks finish; with scope="function" they are already closed. Opening a fresh session inside the task is the safe habit either way, and it keeps a slow task from holding the request's connection.
Choose a task queue when:
The work takes more than a few seconds (reports, video processing, bulk emails).
It must not be lost (payments follow-up, notifications with legal weight).
You need retries with backoff, rate limits, scheduling or monitoring.
You want to scale workers separately from the web servers.
Options: Celery (mature, many features), ARQ or SAQ (asyncio, Redis), Dramatiq, RQ, Taskiq; or a managed queue (SQS, Cloud Tasks, Pub/Sub). Pass IDs, not large objects, and make tasks idempotent because queues deliver at least once.
python
import time
from fastapi import BackgroundTasks, Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
outbox = []
class Payment(BaseModel):
roll_no: str
email: str
amount: int
def send_receipt(email: str, amount: int):
time.sleep(0.2) # slow email provider
outbox.append(f"receipt for {amount} sent to {email}")
def audit(background_tasks: BackgroundTasks):
background_tasks.add_task(outbox.append, "audit log written")
@app.post("/fees/pay", dependencies=[Depends(audit)])
def pay(payment: Payment, background_tasks: BackgroundTasks):
background_tasks.add_task(send_receipt, payment.email, payment.amount)
return {"status": "paid", "outbox_when_returning": list(outbox)}
c = TestClient(app)
r = c.post("/fees/pay", json={"roll_no": "BCA-17", "email": "parent@example.com", "amount": 1500})
print(r.json())
print(outbox) # TestClient waits for background tasks before returning
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. The response is built before the tasks run, so outbox_when_returning is empty; TestClient waits for the tasks, so the final print shows both.
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):
{'status': 'paid', 'outbox_when_returning': []}
['audit log written', 'receipt for 1500 sent to parent@example.com']
Key points
add_task runs work after the response is sent, in the same process
Good for small, quick, losable work
No persistence, retries or monitoring
Open fresh resources inside the task instead of borrowing the request's
Use a task queue for heavy or critical work
Common mistakes
Using BackgroundTasks for long or critical jobs that must survive restarts
Relying on the request's database session inside a long background task
Running CPU-heavy work in an async def background task
Expecting retries or a status endpoint from BackgroundTasks
Follow-ups
How would you report progress of a long report generation to the client?
What happens to pending background tasks during a deploy?
Why should queued tasks receive IDs instead of full objects?
Tips
Explain exactly when tasks run
Name the limitations honestly
Give a clear rule for switching to a queue
27.fastapi-0027Mediummid
How do you use SQLAlchemy 2.0 with FastAPI? Show models, a session dependency and CRUD endpoints.
Create one Engine per process and a sessionmaker, define models with DeclarativeBase, Mapped and mapped_column, and provide a get_db dependency that yields a Session per request and closes it. Endpoints use the 2.0 query style (select(), session.scalars(), session.get()) and return Pydantic models with from_attributes=True. Use Alembic for migrations instead of create_all in production.
Full answer
SQLAlchemy 2.0 (and the current 2.1 line) uses a typed, explicit style.
Avoid the legacy session.query(...) API in new code.
Pydantic integration: response models with model_config = ConfigDict(from_attributes=True) can read ORM objects. expire_on_commit=False keeps attributes loaded after commit so serialisation does not trigger new queries on a closed session.
Production notes:
Schema changes through Alembic migrations (alembic revision --autogenerate, review, alembic upgrade head). Base.metadata.create_all() is only for demos and tests.
Tune the pool: pool_size, max_overflow, pool_pre_ping=True (detects dropped connections), pool_recycle.
Relationship loading: use selectinload() / joinedload() to avoid N+1 queries when responses include related objects.
Sync SQLAlchemy in def endpoints runs in the thread pool, which is fine. For async def endpoints use the async engine and AsyncSession instead.
SQLModel (by FastAPI's author) combines SQLAlchemy models and Pydantic models in one class; useful for simple apps.
python
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import String, create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, sessionmaker
from sqlalchemy.pool import StaticPool
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
SessionLocal = sessionmaker(engine, expire_on_commit=False)
class Base(DeclarativeBase):
pass
class Book(Base):
__tablename__ = "books"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(100), index=True)
copies: Mapped[int] = mapped_column(default=1)
Base.metadata.create_all(engine) # use Alembic migrations in real projects
class BookIn(BaseModel):
title: str = Field(min_length=1, max_length=100)
copies: int = Field(default=1, ge=0)
class BookOut(BookIn):
model_config = ConfigDict(from_attributes=True)
id: int
def get_db():
with SessionLocal() as session:
yield session
DB = Annotated[Session, Depends(get_db)]
app = FastAPI()
@app.post("/books", status_code=201, response_model=BookOut)
def create_book(data: BookIn, db: DB):
book = Book(**data.model_dump())
db.add(book)
db.commit()
return book
@app.get("/books", response_model=list[BookOut])
def list_books(db: DB, available: bool = False):
stmt = select(Book).order_by(Book.title)
if available:
stmt = stmt.where(Book.copies > 0)
return db.scalars(stmt).all()
@app.patch("/books/{book_id}/issue", response_model=BookOut)
def issue(book_id: int, db: DB):
book = db.get(Book, book_id)
if book is None:
raise HTTPException(status_code=404, detail="Book not found")
if book.copies == 0:
raise HTTPException(status_code=409, detail="No copies left")
book.copies -= 1
db.commit()
return book
c = TestClient(app)
print(c.post("/books", json={"title": "Train to Pakistan", "copies": 1}).json())
print(c.post("/books", json={"title": "Godan", "copies": 0}).json())
print(c.patch("/books/1/issue").json())
print(c.patch("/books/1/issue").json(), c.patch("/books/9/issue").status_code)
print([b["title"] for b in c.get("/books").json()], c.get("/books?available=true").json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. An in-memory SQLite database with StaticPool keeps the example self-contained; production uses PostgreSQL or MySQL URLs.
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):
{'title': 'Train to Pakistan', 'copies': 1, 'id': 1}
{'title': 'Godan', 'copies': 0, 'id': 2}
{'title': 'Train to Pakistan', 'copies': 0, 'id': 1}
{'detail': 'No copies left'} 404
['Godan', 'Train to Pakistan'] []
Key points
One engine per process; sessionmaker; session per request
DeclarativeBase, Mapped, mapped_column for typed models
2.0 queries: select(), scalars(), get()
from_attributes=True and expire_on_commit=False for responses
Alembic for migrations; eager loading against N+1
Common mistakes
Creating a new engine per request instead of once per process
Using the legacy session.query() API in new code
Forgetting to close sessions, leaking pool connections
Using sync SQLAlchemy inside async def endpoints and blocking the event loop
Relying on create_all() instead of Alembic in production
Follow-ups
How would you avoid N+1 queries when returning books with their authors?
Why set expire_on_commit=False?
How do you run Alembic migrations safely during deployment?
Tips
Show the 2.0 style APIs by name
Explain session-per-request and why
Mention Alembic and pool settings for production
28.fastapi-0028Mediummid
How do you customise error handling in FastAPI, including validation errors and your own exception types?
Register handlers with @app.exception_handler(ExceptionType). A handler receives the request and the exception and returns a response. Override RequestValidationError to change the 422 format, StarletteHTTPException to reshape HTTP errors, and define domain exceptions (such as NoCopiesLeft) that services raise and one handler maps to a status code. Add a catch-all Exception handler for logging, without leaking internal details.
Full answer
FastAPI already turns HTTPException into {"detail": ...} and validation failures into a 422 list. Larger APIs often want one consistent error shape and cleaner service code.
Domain exceptions: services raise meaningful exceptions (StudentNotFound, FeeAlreadyPaid) without importing FastAPI. Handlers translate them into HTTP responses in one place. This keeps business logic reusable from CLI scripts or workers.
Validation errors: override RequestValidationError to reshape the default 422 body, for example into {"error": {"code": "VALIDATION_ERROR", "fields": {...}}}. exc.errors() gives the list of Pydantic errors with loc, msg, type. Keep the details; clients need to know which field failed. fastapi.exception_handlers.request_validation_exception_handler lets you log and then call the default.
HTTP errors: register a handler for starlette.exceptions.HTTPException (the parent of FastAPI's) to cover 404s for unknown routes and 405s too, not only the ones you raise.
Unexpected errors: an Exception handler can log with a request ID and return a generic 500 body. Never return stack traces or SQL errors to clients. Note that Starlette's ServerErrorMiddleware handles Exception handlers outside other middleware, and the exception still re-raises for the server log.
Standard formats: RFC 9457 "Problem Details for HTTP APIs" (application/problem+json with type, title, status, detail) is a widely understood shape if your organisation has no standard.
Document error responses in route responses= so the OpenAPI schema matches reality.
python
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
from starlette.exceptions import HTTPException as StarletteHTTPException
app = FastAPI()
class NoCopiesLeft(Exception):
def __init__(self, title: str):
super().__init__(f"No copies of '{title}' are available")
def error(status: int, code: str, message: str, **extra):
return JSONResponse(status_code=status, content={"error": {"code": code, "message": message, **extra}})
@app.exception_handler(NoCopiesLeft)
async def handle_no_copies(request: Request, exc: NoCopiesLeft):
return error(409, "NO_COPIES", str(exc))
@app.exception_handler(RequestValidationError)
async def handle_validation(request: Request, exc: RequestValidationError):
fields = {".".join(str(p) for p in e["loc"][1:]): e["msg"] for e in exc.errors()}
return error(422, "VALIDATION_ERROR", "Some fields are invalid", fields=fields)
@app.exception_handler(StarletteHTTPException)
async def handle_http(request: Request, exc: StarletteHTTPException):
return error(exc.status_code, f"HTTP_{exc.status_code}", str(exc.detail))
@app.exception_handler(Exception)
async def handle_unexpected(request: Request, exc: Exception):
return error(500, "INTERNAL_ERROR", "Something went wrong. Please try again.")
class IssueIn(BaseModel):
roll_no: str = Field(min_length=3)
days: int = Field(ge=1, le=30)
def issue_book(title: str): # service layer: no FastAPI imports needed
raise NoCopiesLeft(title)
@app.post("/books/{title}/issue")
def issue(title: str, data: IssueIn):
issue_book(title)
@app.get("/crash")
def crash():
raise ZeroDivisionError("secret internal detail")
c = TestClient(app, raise_server_exceptions=False)
print(c.post("/books/Godan/issue", json={"roll_no": "BCA-17", "days": 7}).json())
print(c.post("/books/Godan/issue", json={"roll_no": "B", "days": 90}).json())
print(c.get("/no-such-page").json())
print(c.get("/crash").status_code, c.get("/crash").json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. raise_server_exceptions=False makes TestClient return the 500 response instead of re-raising the error in the test.
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):
{'error': {'code': 'NO_COPIES', 'message': "No copies of 'Godan' are available"}}
{'error': {'code': 'VALIDATION_ERROR', 'message': 'Some fields are invalid', 'fields': {'roll_no': 'String should have at least 3 characters', 'days': 'Input should be less than or equal to 30'}}}
{'error': {'code': 'HTTP_404', 'message': 'Not Found'}}
500 {'error': {'code': 'INTERNAL_ERROR', 'message': 'Something went wrong. Please try again.'}}
Key points
@app.exception_handler maps exception types to responses
Domain exceptions keep services free of HTTP code
Override RequestValidationError to reshape 422 bodies
Handle Starlette's HTTPException to cover framework 404/405
Catch-all handler logs and hides internals
Common mistakes
Returning stack traces or database error text to clients
Throwing away field details when reshaping validation errors
Raising HTTPException deep inside service code that should not know about HTTP
Handling only FastAPI's HTTPException and missing framework-level 404 and 405 errors
Follow-ups
How would you add a request ID to every error response?
What is RFC 9457 Problem Details?
Where would you log unexpected errors, and with what context?
Tips
Show domain exceptions plus a handler, the cleanest architecture point
Mention RequestValidationError by name
Stress not leaking internals
29.fastapi-0029Mediummid
How would you implement pagination in a FastAPI API, and when should you use offset versus cursor pagination?
Offset pagination (limit and offset or page and size) is simple and allows jumping to any page, but gets slower deep into large tables and can skip or repeat rows when data changes. Cursor (keyset) pagination returns an opaque cursor based on the last row's sort key and queries WHERE key > cursor, which stays fast and stable on big or changing data. Implement either as a reusable dependency and return items with pagination metadata.
Full answer
Every list endpoint needs a limit; returning 200,000 attendance rows in one response hurts the database, the network and the client.
Offset pagination
Parameters: limit and offset, or page and size.
SQL: ORDER BY id LIMIT 20 OFFSET 400.
Pros: simple, supports "go to page 37", easy totals for page numbers.
Cons: the database still reads and discards the first 400 rows, so deep pages get slow on large tables. If rows are inserted or deleted between requests, items shift: users can see duplicates or miss rows. COUNT(*) for totals is also expensive on big tables.
Cursor (keyset) pagination
The response includes next_cursor, usually the last item's sort key encoded as an opaque string (base64 of {"id": 420}).
Next query: WHERE id > 420 ORDER BY id LIMIT 20, which uses the index directly.
Pros: consistent speed at any depth, stable under inserts.
Cons: no jumping to arbitrary pages; ordering must be on a unique, indexed key (use a tie-breaker like (created_at, id) for non-unique sort columns).
Good for feeds, logs, infinite scroll and public APIs with large data.
Implementation tips:
Put parameters in a dependency (or a Pydantic model with Query()), with a default and a hard maximum (le=100).
Return an envelope: {"items": [...], "next_cursor": "...", "has_more": true}. Fetch limit + 1 rows to know if more exist without counting.
Keep cursors opaque so you can change their format later. Sign them if clients must not tamper with them.
Libraries such as fastapi-pagination implement both styles if you prefer not to build your own.
python
import base64
import json
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Query
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
ROWS = [{"id": i, "roll_no": f"R{i:03d}"} for i in range(1, 8)] # stands in for a table ordered by id
class Page(BaseModel):
items: list[dict]
next_cursor: str | None
has_more: bool
def encode(last_id: int) -> str:
return base64.urlsafe_b64encode(json.dumps({"id": last_id}).encode()).decode()
def decode(cursor: str) -> int:
try:
return json.loads(base64.urlsafe_b64decode(cursor.encode()))["id"]
except Exception:
raise HTTPException(status_code=400, detail="Invalid cursor")
def cursor_params(limit: Annotated[int, Query(ge=1, le=100)] = 3, cursor: str | None = None):
return {"limit": limit, "after_id": decode(cursor) if cursor else 0}
@app.get("/attendance", response_model=Page)
def list_attendance(p: Annotated[dict, Depends(cursor_params)]):
# SQL: SELECT ... WHERE id > :after_id ORDER BY id LIMIT :limit + 1
rows = [r for r in ROWS if r["id"] > p["after_id"]][: p["limit"] + 1]
has_more = len(rows) > p["limit"]
items = rows[: p["limit"]]
return Page(items=items, next_cursor=encode(items[-1]["id"]) if has_more else None, has_more=has_more)
@app.get("/attendance-offset")
def list_offset(limit: Annotated[int, Query(ge=1, le=100)] = 3, offset: Annotated[int, Query(ge=0)] = 0):
return ROWS[offset: offset + limit]
c = TestClient(app)
page = c.get("/attendance").json()
seen = [r["roll_no"] for r in page["items"]]
while page["has_more"]:
page = c.get("/attendance", params={"cursor": page["next_cursor"]}).json()
seen += [r["roll_no"] for r in page["items"]]
print("cursor pages:", seen)
first = [r["roll_no"] for r in c.get("/attendance-offset").json()]
ROWS.insert(0, {"id": 0, "roll_no": "R000"}) # a new row arrives at the top
second = [r["roll_no"] for r in c.get("/attendance-offset?offset=3").json()]
print("offset pages after an insert:", first, second, "<- R003 repeated")
print(c.get("/attendance?limit=500").status_code, c.get("/attendance?cursor=bad!").status_code)
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. A Python list stands in for the table; comments show the equivalent SQL.
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):
cursor pages: ['R001', 'R002', 'R003', 'R004', 'R005', 'R006', 'R007']
offset pages after an insert: ['R001', 'R002', 'R003'] ['R003', 'R004', 'R005'] <- R003 repeated
422 400
Key points
Every list endpoint needs a limit with a maximum
Offset is simple but slow deep and unstable under changes
Cursor uses WHERE key > last and stays fast and stable
Fetch limit + 1 to compute has_more without COUNT
Make cursors opaque; use unique, indexed sort keys
Common mistakes
Shipping list endpoints with no limit or no maximum
Using OFFSET deep into tables with millions of rows
Cursor pagination on a non-unique sort key without a tie-breaker
Running COUNT(*) on every request just to show a total
Follow-ups
How would you paginate by created_at when timestamps can repeat?
How do you show 'page 3 of 40' with cursor pagination, or should you?
How would you sign cursors so clients cannot tamper with them?
Tips
Compare the two styles on speed and consistency
Explain the limit + 1 trick
Make the parameters a reusable dependency
30.fastapi-0030Mediummid
What is the lifespan function in FastAPI, and how do you use it for startup and shutdown work?
lifespan is an async context manager passed to FastAPI(lifespan=...). Code before its yield runs once at startup, before the app accepts requests, and code after yield runs at shutdown. Use it to create and close shared resources such as database engines, HTTP clients, caches or ML models, and store them on app.state or yield a state dict. It replaces the deprecated @app.on_event("startup") and ("shutdown") handlers.
Full answer
Some resources should be created once per process, not per request: a database engine with its connection pool, an httpx.AsyncClient, a Redis client, a loaded ML model. They also need clean shutdown.
python
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = httpx.AsyncClient(timeout=5)
model = load_model()
yield {"model": model} # app runs while suspended here
await app.state.http.aclose()
app = FastAPI(lifespan=lifespan)
How it runs:
The ASGI server sends a lifespan "startup" event when a worker starts. FastAPI runs the code up to yield. If it raises, startup fails and the worker does not serve traffic, which is good: better to fail loudly than to serve errors.
During yield, the app serves requests.
On shutdown (SIGTERM during a deploy, Ctrl+C), the code after yield runs. Wrap in try/finally if cleanup must run even when something fails.
Sharing resources with endpoints:
app.state.x (read through request.app.state.x).
Yield a dict: its keys become available as request.state.x in each request (Starlette copies the lifespan state into each request's state).
Wrap access in a dependency (def get_http(request: Request)) so tests can override it.
Notes:
@app.on_event("startup") is deprecated in FastAPI. Starlette 1.0 removed its own on_startup/on_shutdown arguments, so use lifespan in new code.
Each worker process runs its own lifespan. Four workers load the model four times and open four pools.
Mounted sub-applications do not get their own lifespan events, only the main app does.
In tests, with TestClient(app) as client: triggers lifespan; a client without with does not.
Keep startup fast; orchestrators kill slow-starting containers. Use readiness probes that check the resources are ready.
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):
{'result': 'on track'}
{'result': 'needs support'}
['pool opened', 'model loaded', 'serving', 'pool closed']
Key points
Async context manager: before yield = startup, after = shutdown
Use for engines, HTTP clients, models: once per process
Share via app.state or a yielded state dict
Replaces deprecated on_event handlers
Runs per worker; TestClient needs 'with' to trigger it
Common mistakes
Using the deprecated @app.on_event decorators in new code
Creating an HTTP client or engine inside each request
Forgetting that every worker runs lifespan separately
Testing without 'with TestClient(app)' so startup never runs
Doing slow work at startup without readiness checks
Follow-ups
How would you load a 2 GB ML model without slowing every deploy?
How do you share a resource from lifespan with endpoints in a testable way?
What happens to in-flight requests during shutdown?
Tips
Describe exactly when each half runs
Show how endpoints get the resource
Mention the per-worker point and the TestClient detail
31.fastapi-0031Mediummid
How do you manage configuration and secrets in a FastAPI app with pydantic-settings?
Define a class that inherits from pydantic_settings.BaseSettings with typed fields; values are read from environment variables (and optionally a .env file), validated and converted at startup. Expose it through a cached dependency (@lru_cache def get_settings()) so it is created once and can be overridden in tests. Use SecretStr for secrets, an env_prefix to avoid name clashes, and keep real secrets out of the repository.
Full answer
Configuration differs per environment (local, staging, production): database URLs, API keys, feature flags, CORS origins. The twelve-factor approach stores it in environment variables.
pydantic-settings (a separate package since Pydantic v2) turns those variables into a validated object:
Type conversion: CAMPUS_DEBUG=true becomes True; CAMPUS_ALLOWED_ORIGINS='["https://a.edu"]' becomes a list (complex types are parsed as JSON).
Validation at startup: a missing required variable stops the app immediately with a clear error, instead of failing at 2 a.m. on the first request that needs it.
lru_cache means the environment is read once. In tests, app.dependency_overrides[get_settings] = lambda: Settings(database_url="sqlite://", ...).
Rules: commit a .env.example with placeholder values, never the real .env; load secrets from a secret manager in production; do not log the settings object without SecretStr protection; keep one settings class (or a few nested ones), not scattered os.getenv calls.
python
import os
from functools import lru_cache
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic import SecretStr, ValidationError
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="CAMPUS_")
database_url: str
debug: bool = False
allowed_origins: list[str] = []
max_upload_mb: int = 5
sms_api_key: SecretStr
try:
Settings()
except ValidationError as e:
print("missing at startup:", sorted(err["loc"][0] for err in e.errors()))
os.environ.update({
"CAMPUS_DATABASE_URL": "postgresql+psycopg://app@db/campus",
"CAMPUS_DEBUG": "true",
"CAMPUS_ALLOWED_ORIGINS": '["https://app.college.edu"]',
"CAMPUS_SMS_API_KEY": "sk-demo-123",
})
@lru_cache
def get_settings() -> Settings:
return Settings()
app = FastAPI()
@app.get("/config")
def config(settings: Annotated[Settings, Depends(get_settings)]):
return {"debug": settings.debug, "origins": settings.allowed_origins,
"max_upload_mb": settings.max_upload_mb, "key_repr": repr(settings.sms_api_key)}
c = TestClient(app)
print(c.get("/config").json())
app.dependency_overrides[get_settings] = lambda: Settings(database_url="sqlite://", sms_api_key="test",
max_upload_mb=1)
print(c.get("/config").json()["max_upload_mb"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install pydantic-settings`.
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):
missing at startup: ['database_url', 'sms_api_key']
{'debug': True, 'origins': ['https://app.college.edu'], 'max_upload_mb': 5, 'key_repr': "SecretStr('**********')"}
1
Key points
BaseSettings reads and validates environment variables
Missing required settings fail at startup
Priority: init args > env vars > .env > defaults
SecretStr hides secret values
Cached get_settings dependency, overridable in tests
Common mistakes
Scattering os.getenv calls with no validation across the code
Importing BaseSettings from pydantic (v1 location) instead of pydantic-settings
Committing the real .env file
Logging settings objects that contain plain-string secrets
Creating Settings() on every request instead of caching
Follow-ups
How would you load secrets from a cloud secret manager into settings?
How do you override settings in tests?
Why fail at startup instead of at first use?
Tips
Show the cached dependency pattern
Mention SecretStr and the priority order
Talk about .env.example and secret managers
32.fastapi-0032Mediummid
How do WebSockets work in FastAPI, and how do you handle connect, messages and disconnects?
Declare an endpoint with @app.websocket("/path") that takes a WebSocket parameter, call await websocket.accept(), then loop with receive_text() or receive_json() and send responses with send_text() or send_json(). A client disconnect raises WebSocketDisconnect, which you catch to clean up. WebSocket endpoints support path, query and dependency parameters, but authentication must be checked before accept or by closing with a policy-violation code.
Full answer
HTTP is request then response. A WebSocket upgrades one HTTP connection into a long-lived, two-way channel, so the server can push messages (live quiz scores, chat, attendance updates) without the client polling.
When the client leaves, receive_*() raises WebSocketDisconnect with a code (1000 normal, 1001 going away). The iter_text() / iter_json() async iterators instead end the loop quietly, so put cleanup in finally to cover both styles.
Path and query parameters, Header, Cookie and Depends work as in HTTP endpoints. HTTPException does not apply; use WebSocketException.
Authentication: browsers cannot set custom headers on WebSocket connections, so tokens usually come through a cookie, a query parameter (beware of logs), or a first "auth" message. Validate before doing anything else.
Endpoints should be async def; the connection lives on the event loop. Blocking code there stalls every socket on that worker.
Testing: TestClient(app).websocket_connect("/ws/...") returns a session with send_json / receive_json.
Operations: WebSockets are long-lived, so plan for proxies (enable upgrade headers, raise idle timeouts), heartbeats (ping/pong) to detect dead connections, reconnect logic on the client, and connection limits per worker. Broadcasting across several workers needs a shared channel such as Redis pub/sub.
python
from typing import Annotated
from fastapi import FastAPI, Query, WebSocket, WebSocketDisconnect, status
from fastapi.testclient import TestClient
app = FastAPI()
ANSWERS = {"q1": "B", "q2": "D"}
events = []
@app.websocket("/ws/quiz/{room}")
async def quiz(websocket: WebSocket, room: str, token: Annotated[str | None, Query()] = None):
if token != "student-token":
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
return
await websocket.accept()
score = 0
try:
while True:
msg = await websocket.receive_json()
correct = ANSWERS.get(msg["question"]) == msg["answer"]
score += correct
await websocket.send_json({"room": room, "question": msg["question"],
"correct": correct, "score": score})
except WebSocketDisconnect as exc:
events.append(f"left room {room} with code {exc.code}")
finally:
events.append(f"final score {score}")
c = TestClient(app)
with c.websocket_connect("/ws/quiz/10A?token=student-token") as ws:
ws.send_json({"question": "q1", "answer": "B"})
print(ws.receive_json())
ws.send_json({"question": "q2", "answer": "A"})
print(ws.receive_json())
try:
with c.websocket_connect("/ws/quiz/10A") as ws:
ws.receive_json()
except WebSocketDisconnect as exc:
print("rejected with code", exc.code)
print(events)
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):
{'room': '10A', 'question': 'q1', 'correct': True, 'score': 1}
{'room': '10A', 'question': 'q2', 'correct': False, 'score': 1}
rejected with code 1008
['left room 10A with code 1000', 'final score 1']
Key points
@app.websocket endpoint with accept, receive, send loop
WebSocketDisconnect signals the client left
Reject before accept with close code 1008 or WebSocketException
Browsers cannot set headers; plan token delivery
Use async def; test with websocket_connect
Common mistakes
Not catching WebSocketDisconnect, so cleanup never runs
Doing work before checking authentication
Calling blocking code inside the WebSocket loop
Keeping connection lists in process memory and expecting broadcasts to reach clients on other workers
Forgetting proxy upgrade headers and idle timeouts
Follow-ups
How would you broadcast a message to everyone in a room across four workers?
How do you authenticate a browser WebSocket connection?
When would Server-Sent Events be a better choice?
Tips
Show the accept, loop, disconnect structure
Address authentication explicitly
Mention scaling with Redis pub/sub and proxy settings
33.fastapi-0033Mediummid
Why do FastAPI projects use separate schemas for create, update and read, and how do you implement PATCH partial updates?
Create, update and read have different rules: create needs required fields, update usually allows any subset, and read adds server fields like id while hiding secrets. Separate models (StudentCreate, StudentUpdate, StudentRead), often sharing a base class, keep these rules explicit. For PATCH, make every field optional in the update model and apply only fields the client actually sent with model_dump(exclude_unset=True).
Full answer
One model for everything creates bugs: clients can set id or is_admin, responses leak password_hash, and PATCH cannot tell "not sent" from "set to null".
A common layout:
python
class StudentBase(BaseModel):
name: str = Field(min_length=2)
email: EmailStr
class StudentCreate(StudentBase):
password: str = Field(min_length=8)
class StudentUpdate(BaseModel):
name: str | None = Field(default=None, min_length=2)
email: EmailStr | None = None
phone: str | None = None
class StudentRead(StudentBase):
model_config = ConfigDict(from_attributes=True)
id: int
phone: str | None
PATCH semantics: the client sends only the fields to change.
python
changes = data.model_dump(exclude_unset=True)
for field, value in changes.items():
setattr(student, field, value)
exclude_unset=True includes only fields present in the request body. So {"phone": null} clears the phone, while omitting phone leaves it unchanged. That difference is the whole point; exclude_none=True would wrongly ignore an intentional null.
Pydantic also offers model.model_copy(update=changes) to build an updated copy of a Pydantic object.
PUT vs PATCH: PUT replaces the whole resource, so it should use a model with required fields (often the create model without the password). PATCH changes part of it.
Guard fields that may be updated: the update model simply does not contain id, role or created_at, so clients cannot change them. If some fields need validation rules on update but can be null (clearing), express that explicitly. Optional fields with constraints still validate when present.
Naming conventions vary (StudentIn/StudentOut, StudentCreate/StudentPublic); consistency inside a project matters more than the exact names.
python
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict, Field
class StudentBase(BaseModel):
name: str = Field(min_length=2)
email: str
class StudentCreate(StudentBase):
password: str = Field(min_length=8)
class StudentUpdate(BaseModel):
name: str | None = Field(default=None, min_length=2)
email: str | None = None
phone: str | None = None
class StudentRead(StudentBase):
model_config = ConfigDict(from_attributes=True)
id: int
phone: str | None = None
DB: dict[int, dict] = {}
app = FastAPI()
@app.post("/students", response_model=StudentRead, status_code=201)
def create(data: StudentCreate):
sid = len(DB) + 1
DB[sid] = {"id": sid, **data.model_dump(exclude={"password"}), "phone": None,
"password_hash": "hashed:" + data.password[::-1]}
return DB[sid]
@app.patch("/students/{sid}", response_model=StudentRead)
def update(sid: int, data: StudentUpdate):
if sid not in DB:
raise HTTPException(status_code=404, detail="Student not found")
changes = data.model_dump(exclude_unset=True)
DB[sid].update(changes)
return DB[sid]
c = TestClient(app)
print(c.post("/students", json={"name": "Yash", "email": "yash@example.edu", "password": "Banyan-tree-7"}).json())
print(c.patch("/students/1", json={"phone": "98xxxxxx11"}).json())
print(c.patch("/students/1", json={"name": "Yash Jain"}).json()) # phone untouched
print(c.patch("/students/1", json={"phone": None}).json()) # phone cleared on purpose
print(c.patch("/students/1", json={"name": "Y"}).status_code)
print("password_hash" in c.get("/openapi.json").text)
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):
{'name': 'Yash', 'email': 'yash@example.edu', 'id': 1, 'phone': None}
{'name': 'Yash', 'email': 'yash@example.edu', 'id': 1, 'phone': '98xxxxxx11'}
{'name': 'Yash Jain', 'email': 'yash@example.edu', 'id': 1, 'phone': '98xxxxxx11'}
{'name': 'Yash Jain', 'email': 'yash@example.edu', 'id': 1, 'phone': None}
422
False
Key points
Separate create, update and read models
Read model hides secrets and adds server fields
Update model has all fields optional
PATCH applies model_dump(exclude_unset=True)
exclude_unset distinguishes 'not sent' from 'set to null'
Common mistakes
Using one model for input and output and leaking password hashes
Using exclude_none for PATCH and ignoring intentional nulls
Letting the update model include id or role fields
Implementing PATCH with a model whose fields are required
Follow-ups
What is the difference between PUT and PATCH in practice?
How would you prevent a student from changing their own role?
How would you implement JSON Merge Patch or JSON Patch?
Tips
Explain why each model exists
Show exclude_unset and explain its difference from exclude_none
Mention PUT versus PATCH
34.fastapi-0034Mediummid
How do you handle many filter parameters and nested or list request bodies in FastAPI?
Group related query parameters into a Pydantic model and declare it as Annotated[Filters, Query()] (FastAPI 0.115+), which validates them together and documents each one; model_config = {"extra": "forbid"} rejects unknown filters. For bodies, Pydantic models can nest other models and lists, such as an exam with a list of question objects, and an endpoint can accept a list of models directly. Limit list sizes to protect the server.
Full answer
Grouped query parameters
An endpoint with eight filters becomes hard to read and repeat. Since FastAPI 0.115:
Each field is still a separate query parameter (?subject=Maths&min_score=40), validated and documented.
extra="forbid" returns 422 for unknown parameters, which catches typos like min_scroe.
The same pattern works for headers (Header()), cookies (Cookie()) and forms (Form()).
Before 0.115, the usual approach was a dependency class or function.
Nested bodies
Pydantic models can contain other models, lists and dicts:
python
class Question(BaseModel):
text: str
options: list[str] = Field(min_length=2, max_length=6)
answer_index: int
class Exam(BaseModel):
title: str
questions: list[Question] = Field(min_length=1, max_length=100)
Validation errors point to the exact location, such as ["body", "questions", 2, "options"].
List bodies: def bulk(students: list[StudentIn]) accepts a JSON array at the top level. Add a length limit (with Annotated[list[StudentIn], Field(max_length=500)] or by checking) so one request cannot submit a million items.
Other body shapes: dict[str, int] for maps (keys arrive as strings and are converted), and discriminated unions for "one of several shapes".
Keep request payloads bounded: limit list lengths and string sizes, and set a request size limit at the proxy.
python
from typing import Annotated, Literal
from fastapi import FastAPI, Query
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class MarkFilters(BaseModel):
model_config = {"extra": "forbid"}
subject: str | None = None
min_score: int = Field(0, ge=0, le=100)
term: Literal["mid", "final"] = "final"
tags: list[str] = []
class Question(BaseModel):
text: str
options: list[str] = Field(min_length=2, max_length=6)
answer_index: int = Field(ge=0)
class Exam(BaseModel):
title: str
questions: list[Question] = Field(min_length=1, max_length=100)
class StudentIn(BaseModel):
roll_no: str
name: str
@app.get("/marks")
def list_marks(filters: Annotated[MarkFilters, Query()]):
return filters
@app.post("/exams")
def create_exam(exam: Exam):
return {"title": exam.title, "questions": len(exam.questions)}
@app.post("/students/bulk")
def bulk(students: Annotated[list[StudentIn], Field(max_length=3)]):
return {"created": [s.roll_no for s in students]}
c = TestClient(app)
print(c.get("/marks?subject=Maths&min_score=40&tags=unit1&tags=unit2").json())
print(c.get("/marks?min_scroe=40").json()["detail"][0]["type"])
exam = {"title": "Unit test 1", "questions": [
{"text": "2 + 2 = ?", "options": ["3", "4"], "answer_index": 1},
{"text": "Capital of India?", "options": ["Delhi"], "answer_index": 0}]}
print(c.post("/exams", json=exam).json()["detail"][0]["loc"])
exam["questions"][1]["options"].append("Mumbai")
print(c.post("/exams", json=exam).json())
students = [{"roll_no": f"R{i}", "name": "x"} for i in range(4)]
print(c.post("/students/bulk", json=students[:2]).json(), c.post("/students/bulk", json=students).status_code)
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
{'subject': 'Maths', 'min_score': 40, 'term': 'final', 'tags': ['unit1', 'unit2']}
extra_forbidden
['body', 'questions', 1, 'options']
{'title': 'Unit test 1', 'questions': 2}
{'created': ['R0', 'R1']} 422
Key points
Annotated[Model, Query()] groups query parameters (0.115+)
extra='forbid' rejects unknown filters
Models nest other models and lists
Errors include precise locations like questions.2.options
Bound list lengths in bodies
Common mistakes
Repeating the same eight query parameters across endpoints
Accepting unbounded lists in request bodies
Silently ignoring misspelled filter names
Flattening naturally nested data into awkward field names
Follow-ups
How did people group query parameters before FastAPI 0.115?
How would you validate that answer_index is within the options list?
How would you accept a body that can be one of three shapes?
Tips
Mention the 0.115 Query model feature by version
Show the precise error locations for nested data
Always bound list sizes
35.fastapi-0035Hardsenior
What are the common async pitfalls in FastAPI, and how do you handle blocking or CPU-heavy code safely?
The main pitfall is blocking the event loop: calling synchronous I/O (requests, sync database drivers, time.sleep, large file reads) or CPU-heavy code inside async def, which stalls every request on that worker. Offload blocking I/O with run_in_threadpool or asyncio.to_thread, remember the default thread pool has about 40 slots shared by all def endpoints and dependencies, and send CPU-heavy work to a process pool or task queue. Also bound concurrency for outbound calls and never create unbounded background tasks.
Full answer
An async worker has one event loop thread. Anything that runs without awaiting holds that thread.
Pitfalls and fixes:
Blocking I/O in async def. requests.get(), psycopg2, sync SQLAlchemy, boto3, open().read() on big files. Fix: use async libraries (httpx.AsyncClient, asyncpg, async SQLAlchemy, aiofiles), or make the endpoint def, or wrap calls with await run_in_threadpool(fn, *args) / await asyncio.to_thread(fn, *args).
CPU-heavy work. JSON parsing of huge payloads, image resizing, PDF generation, ML inference in pure Python. Threads do not help much because of the GIL. Fix: loop.run_in_executor(ProcessPoolExecutor(), fn, ...), a task queue, or a separate service. (Free-threaded CPython builds from 3.13/3.14 change this picture, but most deployments still run with the GIL.)
Thread pool exhaustion. def endpoints, def dependencies and run_in_threadpool share AnyIO's default limiter of 40 threads per process. If 40 requests block on a slow sync call, the 41st waits even for a trivial def endpoint. Fix: avoid long blocking calls, use async drivers, or raise the limit at startup (anyio.to_thread.current_default_thread_limiter().total_tokens = 100) after measuring.
Unbounded concurrency. asyncio.gather(*[call(x) for x in 10_000 items]) opens 10,000 connections. Fix: asyncio.Semaphore(20) or anyio task groups with limits.
Fire-and-forget tasks. asyncio.create_task() without keeping a reference can be garbage collected, and exceptions vanish. Fix: keep references, use task groups, or use BackgroundTasks / a queue.
Async libraries used without timeouts. One stuck upstream can hold coroutines forever. Fix: always set timeouts.
How to detect blocking: run with PYTHONASYNCIODEBUG=1 (asyncio logs callbacks slower than 100 ms), watch event loop lag metrics, or profile with py-spy dump to see what the loop thread is doing.
python
import asyncio
import threading
import time
import anyio
from fastapi import FastAPI
from fastapi.concurrency import run_in_threadpool
from fastapi.testclient import TestClient
app = FastAPI()
def legacy_sms_sdk(number: str) -> str: # a sync SDK we cannot change
time.sleep(0.3)
return f"sent to {number}"
@app.post("/notify-blocking")
async def notify_blocking():
return {"result": legacy_sms_sdk("98xxxxxx01")} # blocks the event loop
@app.post("/notify-threadpool")
async def notify_threadpool():
return {"result": await run_in_threadpool(legacy_sms_sdk, "98xxxxxx01")}
limit = asyncio.Semaphore(3)
active = {"now": 0, "peak": 0}
async def call_upstream(i: int) -> int:
async with limit:
active["now"] += 1
active["peak"] = max(active["peak"], active["now"])
await asyncio.sleep(0.01)
active["now"] -= 1
return i
@app.post("/fan-out")
async def fan_out():
results = await asyncio.gather(*(call_upstream(i) for i in range(20)))
return {"count": len(results), "peak_concurrency": active["peak"]}
@app.get("/thread-limit")
async def thread_limit():
return {"default_thread_limit": anyio.to_thread.current_default_thread_limiter().total_tokens}
def run_parallel(client, path, n=3):
start = time.perf_counter()
threads = [threading.Thread(target=client.post, args=(path,)) for _ in range(n)]
[t.start() for t in threads]
[t.join() for t in threads]
return "concurrent" if time.perf_counter() - start < 0.6 else "serialised"
with TestClient(app) as c:
print("blocking in async def:", run_parallel(c, "/notify-blocking"))
print("run_in_threadpool:", run_parallel(c, "/notify-threadpool"))
print(c.post("/fan-out").json())
print(c.get("/thread-limit").json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. The 40-slot limit printed at the end is AnyIO's default thread limiter, which FastAPI uses for sync code.
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):
blocking in async def: serialised
run_in_threadpool: concurrent
{'count': 20, 'peak_concurrency': 3}
{'default_thread_limit': 40}
Key points
Never block the event loop in async def
run_in_threadpool or asyncio.to_thread for blocking I/O
Process pools or queues for CPU-heavy work
Default thread pool is about 40 slots shared by all sync code
Bound concurrency with semaphores; set timeouts
Common mistakes
Calling sync SDKs or requests inside async def
Using threads for CPU-heavy Python code and expecting a speedup
Ignoring the shared 40-thread limit when many def endpoints block
Launching thousands of concurrent outbound calls without a semaphore
Creating tasks with asyncio.create_task and dropping the reference
Follow-ups
How would you find out which code is blocking the event loop in production?
When would you raise the thread pool limit, and what are the risks?
How would you run a CPU-heavy model inside a FastAPI service?
Tips
Name several pitfalls, not only blocking I/O
Mention the shared thread pool and its default size
Give detection techniques, not only fixes
36.fastapi-0036Hardsenior
How do you use SQLAlchemy's async engine and AsyncSession with FastAPI, and what problems are specific to async ORM usage?
Create an engine with create_async_engine and an async driver (asyncpg, psycopg async, aiosqlite), an async_sessionmaker with expire_on_commit=False, and an async generator dependency that yields an AsyncSession. Use await session.execute/scalars/get and await session.commit. The async-specific trap is implicit lazy loading: touching an unloaded relationship raises MissingGreenlet, so load relationships eagerly with selectinload or use AsyncAttrs.awaitable_attrs, and never share one AsyncSession across concurrent tasks.
Full answer
Setup:
python
engine = create_async_engine("postgresql+asyncpg://...", pool_size=10, pool_pre_ping=True)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_db():
async with SessionLocal() as session:
yield session
async with session.begin(): for a transaction block
Create tables in lifespan with async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) (demos only; use Alembic for real schemas, it supports async engines via run_sync).
Async-specific problems:
Lazy loading. In sync code, book.author silently runs a query. In async code, SQLAlchemy cannot run I/O implicitly and the attempt fails with MissingGreenlet. When it happens while a statement is executing, SQLAlchemy wraps it, so you catch StatementError and find the original under exc.orig (the snippet shows this). Fixes: select(Book).options(selectinload(Book.author)), lazy="selectin" on the relationship, or lazy="raise" (fail fast: any lazy access raises InvalidRequestError before I/O, a clearer error than the wrapped one), or await book.awaitable_attrs.author with the AsyncAttrs mixin.
Expired attributes after commit. With the default expire_on_commit=True, reading book.title after commit triggers a refresh, which fails the same way. Set expire_on_commit=False.
Sharing a session. An AsyncSession is not safe for concurrent use. asyncio.gather(query1(session), query2(session)) on one session raises errors. Use one session per task, or run queries sequentially.
Pool sizing. Async code can start many more concurrent queries than sync code. Keep pool_size + max_overflow under the database's connection budget across all workers, and use a semaphore for big fan-outs.
Engine disposal. await engine.dispose() in lifespan shutdown.
Async is worth it when the service does lots of concurrent I/O (database plus outbound HTTP) per request. For simple CRUD, sync SQLAlchemy in def endpoints is often just as fast and simpler.
python
import asyncio
from contextlib import asynccontextmanager
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict
from sqlalchemy import ForeignKey, select
from sqlalchemy.exc import InvalidRequestError, MissingGreenlet, StatementError
from sqlalchemy.ext.asyncio import AsyncAttrs, AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, selectinload
engine = create_async_engine("sqlite+aiosqlite:///:memory:")
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
class Base(AsyncAttrs, DeclarativeBase):
pass
class Author(Base):
__tablename__ = "authors"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
books: Mapped[list["Book"]] = relationship(back_populates="author")
class Book(Base):
__tablename__ = "books"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str]
author_id: Mapped[int] = mapped_column(ForeignKey("authors.id"))
author: Mapped[Author] = relationship(back_populates="books")
editor: Mapped[Author] = relationship(foreign_keys=[author_id], viewonly=True, lazy="raise")
class BookOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
title: str
author_name: str
@asynccontextmanager
async def lifespan(app: FastAPI):
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async with SessionLocal() as s:
rk = Author(name="R. K. Narayan")
s.add_all([Book(title="Swami and Friends", author=rk), Book(title="The Guide", author=rk)])
await s.commit()
yield
await engine.dispose()
async def get_db():
async with SessionLocal() as session:
yield session
DB = Annotated[AsyncSession, Depends(get_db)]
app = FastAPI(lifespan=lifespan)
@app.get("/books-lazy")
async def books_lazy(db: DB):
books = (await db.scalars(select(Book).order_by(Book.id))).all()
try:
return [b.author.name for b in books] # implicit lazy load
except StatementError as exc: # SQLAlchemy wraps MissingGreenlet here
return {"error": "lazy load attempted inside async code",
"cause": type(exc.orig).__name__, "is_missing_greenlet": isinstance(exc.orig, MissingGreenlet)}
@app.get("/books-raise")
async def books_raise(db: DB):
books = (await db.scalars(select(Book).order_by(Book.id))).all()
try:
return [b.editor.name for b in books] # relationship declared with lazy="raise"
except InvalidRequestError as exc:
return {"error": "blocked before any I/O", "cause": type(exc).__name__}
@app.get("/books", response_model=list[BookOut])
async def books(db: DB):
stmt = select(Book).options(selectinload(Book.author)).order_by(Book.id)
rows = (await db.scalars(stmt)).all()
return [BookOut(title=b.title, author_name=b.author.name) for b in rows]
@app.get("/authors/{author_id}/count")
async def count_books(author_id: int, db: DB):
author = await db.get(Author, author_id)
return {"author": author.name, "books": len(await author.awaitable_attrs.books)}
with TestClient(app) as c:
print(c.get("/books-lazy").json())
print(c.get("/books-raise").json())
print(c.get("/books").json())
print(c.get("/authors/1/count").json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install "sqlalchemy[asyncio]" aiosqlite`; production uses asyncpg or psycopg with PostgreSQL.
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):
{'error': 'lazy load attempted inside async code', 'cause': 'MissingGreenlet', 'is_missing_greenlet': True}
{'error': 'blocked before any I/O', 'cause': 'InvalidRequestError'}
[{'title': 'Swami and Friends', 'author_name': 'R. K. Narayan'}, {'title': 'The Guide', 'author_name': 'R. K. Narayan'}]
{'author': 'R. K. Narayan', 'books': 2}
Lazy loading raises MissingGreenlet; eager load with selectinload
One AsyncSession per task; size pools carefully
Common mistakes
Relying on lazy loading and getting MissingGreenlet errors
Keeping expire_on_commit=True and reading attributes after commit
Sharing one AsyncSession across asyncio.gather tasks
Using async SQLAlchemy with a sync driver like psycopg2
Choosing async for plain CRUD where sync would be simpler
Follow-ups
What does lazy='raise' on a relationship do, and why use it?
How do you run Alembic migrations with an async engine?
How would you run two independent queries concurrently?
Tips
Show the setup and the await points
Explain MissingGreenlet and two fixes
Say when async SQLAlchemy is not worth it
37.fastapi-0037Hardsenior
How do you write async tests for a FastAPI app, and when do you need them instead of TestClient?
Use httpx.AsyncClient with ASGITransport(app=app) inside async test functions run by the AnyIO pytest plugin (@pytest.mark.anyio) or pytest-asyncio. You need async tests when the test itself must await things: async database fixtures, async service calls, or checking state with async clients on the same event loop. ASGITransport does not run lifespan events, so wrap the app with asgi-lifespan's LifespanManager or set up resources in fixtures.
Full answer
TestClient is synchronous: it runs the app in a separate thread with its own event loop. That is simple and covers most endpoint tests. It becomes awkward when:
fixtures are async (creating rows with an AsyncSession, seeding Redis with an async client),
the test needs to call async functions directly alongside HTTP calls,
async resources are bound to one event loop (asyncpg connections, async engines) and the test and app must share it.
An async test:
python
@pytest.mark.anyio
async def test_create_book():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
r = await client.post("/books", json={...})
assert r.status_code == 201
Setup choices:
AnyIO's pytest plugin ships with AnyIO (a Starlette dependency). Mark tests with @pytest.mark.anyio and define an anyio_backend fixture returning "asyncio" to avoid also running on trio.
pytest-asyncio works too (@pytest.mark.asyncio or asyncio_mode = "auto").
ASGITransport calls the app in-process; no network. It does not send lifespan events. Use asgi_lifespan.LifespanManager(app) or create resources in fixtures and inject them with dependency_overrides.
Use base_url="http://test"; the host is required but not contacted.
Starlette 1.x's TestClient builds on the httpx2 package; httpx2 keeps the same AsyncClient and ASGITransport API, so either package works for these tests.
Patterns for reliable async tests:
Database per test: open a connection, begin a transaction, bind the session to it, override get_db, and roll back at teardown. Fast and isolated.
Override outbound HTTP clients with fakes, or use respx to mock httpx calls.
Keep event-loop scope consistent: session-scoped async fixtures need the matching loop scope in pytest-asyncio.
Test concurrency bugs explicitly with asyncio.gather on several requests when behaviour under parallel calls matters (idempotency, locking).
python
import asyncio
import httpx
import pytest
from fastapi import Depends, FastAPI
app = FastAPI()
class AsyncStore: # stands in for an async repository
def __init__(self):
self.rows = {}
async def add(self, roll_no, name):
await asyncio.sleep(0)
self.rows[roll_no] = name
async def get(self, roll_no):
await asyncio.sleep(0)
return self.rows.get(roll_no)
async def get_store():
raise RuntimeError("real store not used in tests")
@app.post("/students/{roll_no}", status_code=201)
async def add_student(roll_no: str, name: str, store: AsyncStore = Depends(get_store)):
if await store.get(roll_no):
return {"created": False}
await store.add(roll_no, name)
return {"created": True}
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.fixture
async def store():
s = AsyncStore()
await s.add("BCA-01", "Existing Student") # async fixture setup
app.dependency_overrides[get_store] = lambda: s
yield s
app.dependency_overrides.clear()
@pytest.fixture
async def client():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as c:
yield c
@pytest.mark.anyio
async def test_add_and_read_back(client, store):
r = await client.post("/students/BCA-02", params={"name": "Neel"})
assert r.status_code == 201 and r.json() == {"created": True}
assert await store.get("BCA-02") == "Neel" # check state with an async call
@pytest.mark.anyio
async def test_duplicate(client, store):
r = await client.post("/students/BCA-01", params={"name": "Someone"})
assert r.json() == {"created": False}
@pytest.mark.anyio
async def test_parallel_requests(client, store):
results = await asyncio.gather(*(client.post(f"/students/R{i}", params={"name": "x"}) for i in range(5)))
assert all(r.status_code == 201 for r in results)
assert len(store.rows) == 6
if __name__ == "__main__":
code = pytest.main([__file__, "-qq", "-p", "no:cacheprovider", "-p", "no:warnings"])
print("pytest exit code:", int(code))
Standalone pytest file using AnyIO's pytest plugin (bundled with AnyIO). Run with `python file.py` or `pytest file.py`; needs `pip install pytest httpx`.
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0, pytest 9.2.0):
... [100%]
pytest exit code: 0
Key points
httpx.AsyncClient + ASGITransport for in-process async calls
Run with @pytest.mark.anyio or pytest-asyncio
Needed when fixtures or checks are async or loop-bound
ASGITransport skips lifespan; use LifespanManager or fixtures
Roll back a transaction per test for isolation
Common mistakes
Mixing TestClient with async fixtures bound to another event loop
Expecting ASGITransport to run lifespan startup code
Forgetting the anyio_backend fixture and running tests twice on trio
Sharing state between tests without resetting dependency overrides
Follow-ups
How would you give each async test its own database transaction?
How do you mock outbound httpx calls in async tests?
What is the difference between pytest-anyio and pytest-asyncio?
Tips
Explain why TestClient is not enough in some cases
Mention ASGITransport and the lifespan gap
Describe a database isolation strategy
38.fastapi-0038Hardsenior
How would you deploy a FastAPI service to production? Cover processes, containers, proxies, health checks and graceful shutdown.
Package the app in a small container that runs Uvicorn (or fastapi run) as a non-root user, one or a few worker processes per container, scaled horizontally behind a load balancer that terminates TLS. Trust forwarded headers only from the proxy, restrict hosts, set body size limits, expose liveness and readiness endpoints, load configuration from the environment, log to stdout, run migrations as a separate job, and let SIGTERM drain in-flight requests before the process exits.
Full answer
A production setup has several layers. A typical one:
Load balancer or ingress
Terminates TLS, routes to healthy instances, enforces request size and timeouts, may add a WAF and rate limits.
Forwards X-Forwarded-For and X-Forwarded-Proto. Run Uvicorn with --proxy-headers --forwarded-allow-ips=<proxy IPs> so request.client.host and request.url.scheme are correct, and only trust these headers from the proxy.
Application processes
Kubernetes or another orchestrator: often one Uvicorn process per container and many replicas, so the orchestrator handles restarts and scaling. On a VM: uvicorn --workers N or Gunicorn with Uvicorn workers.
Async apps doing I/O can handle many concurrent requests per process; CPU-bound work needs more processes or offloading.
Container image
Slim Python base image, dependencies installed in a separate layer (or with uv for speed), app code copied last.
Non-root user, no secrets baked in, exec-form CMD ["fastapi", "run", "app/main.py", "--port", "8000", "--proxy-headers"] so SIGTERM reaches the server.
Configuration and secrets: environment variables via pydantic-settings, secrets from a secret manager or orchestrator secrets.
Health checks
Liveness: "is the process alive?" Cheap, no dependency checks, or a stuck database would restart every pod.
Readiness: "can it serve traffic?" Checks the database pool and required services; the load balancer stops sending traffic when it fails.
Graceful shutdown: on SIGTERM, Uvicorn stops accepting connections and waits for in-flight requests (bounded by --timeout-graceful-shutdown), then lifespan shutdown closes pools. Set the orchestrator's termination grace period longer than this. Kubernetes may send traffic for a short time after SIGTERM, so a small pre-stop delay helps.
Safety settings: TrustedHostMiddleware with allowed hosts, request body limits (recent FastAPI versions accept max_body_size on the app or a route; also limit at the proxy), disable or protect /docs if the API is not public.
Release process: run Alembic migrations as a separate job before rolling out, keep schema changes backward compatible, roll out gradually (rolling or canary), and watch error rate and latency dashboards.
Observability: structured JSON logs to stdout, metrics (Prometheus or OpenTelemetry), tracing, and alerts on p95 latency and 5xx rates.
python
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, Response
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.testclient import TestClient
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
state = {"db_ready": False}
@asynccontextmanager
async def lifespan(app: FastAPI):
state["db_ready"] = True # open the database pool here
yield
state["db_ready"] = False # close it here during graceful shutdown
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, max_body_size=1_000_000)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["api.college.edu", "testserver"])
@app.get("/livez")
def livez():
return {"status": "alive"}
@app.get("/readyz")
def readyz(response: Response):
if not state["db_ready"]:
response.status_code = 503
return {"status": "not ready"}
return {"status": "ready"}
@app.get("/whoami")
def whoami(request: Request):
return {"client": request.client.host, "scheme": request.url.scheme}
@app.post("/upload")
async def upload(request: Request):
return {"bytes": len(await request.body())}
asgi = ProxyHeadersMiddleware(app, trusted_hosts=["10.0.0.5"]) # what --proxy-headers enables
print("before startup:", TestClient(app).get("/readyz").status_code)
with TestClient(asgi, base_url="http://api.college.edu", client=("10.0.0.5", 5000)) as c:
print(c.get("/livez").json(), c.get("/readyz").json())
print(c.get("/whoami", headers={"X-Forwarded-For": "203.0.113.9", "X-Forwarded-Proto": "https"}).json())
print(c.get("/livez", headers={"Host": "evil.example"}).status_code)
print(c.post("/upload", content=b"x" * 2_000_000).status_code)
with TestClient(ProxyHeadersMiddleware(app, trusted_hosts=["10.0.0.5"]), client=("198.51.100.7", 5000)) as c:
print("untrusted proxy:", c.get("/whoami", headers={"X-Forwarded-For": "203.0.113.9"}).json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. ProxyHeadersMiddleware is the same middleware Uvicorn adds for --proxy-headers; client=(...) sets the TCP peer address TestClient reports. max_body_size needs a recent FastAPI release (verified on 0.165).
Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0):
before startup: 503
{'status': 'alive'} {'status': 'ready'}
{'client': '203.0.113.9', 'scheme': 'https'}
400
413
untrusted proxy: {'client': '198.51.100.7', 'scheme': 'http'}
Key points
Container: slim image, non-root, exec-form CMD
One process per container with replicas, or --workers on VMs
Trust proxy headers only from the proxy; TrustedHostMiddleware
Separate liveness and readiness checks
SIGTERM drains requests; migrations run as a separate job
Common mistakes
Trusting X-Forwarded-For from any client, which lets callers fake their IP
Making liveness checks depend on the database and restart-looping every pod during an outage
Using the shell form of CMD so SIGTERM never reaches Uvicorn
Running migrations at container startup from every replica
Baking secrets into the image
Follow-ups
How would you roll out a breaking database change with zero downtime?
How many Uvicorn workers per container would you run on Kubernetes, and why?
What should a readiness check verify?
Tips
Walk the request path from load balancer to process
Separate liveness from readiness
Mention graceful shutdown and proxy header trust explicitly
39.fastapi-0039Hardsenior
How do you make a FastAPI service faster under load? What would you measure and change first?
Measure first with load tests and tracing to see whether time goes to the database, outbound calls, serialisation or Python code. The biggest wins are usually in I/O: fewer and faster queries, connection pooling, caching, and concurrency for independent calls. On the FastAPI side, declare response models or return types so FastAPI serialises with Pydantic's Rust core directly to JSON bytes, keep responses small with pagination, avoid blocking the event loop, and tune worker counts from measurements.
Full answer
Start with numbers
Load test with realistic traffic (Locust, k6, wrk) and record p50, p95, p99 latency, throughput and error rate.
Trace requests (OpenTelemetry) to see time in the database, HTTP calls and application code.
Profile hot paths with py-spy or pyinstrument.
Typical bottlenecks and fixes, roughly in order of impact:
Database: N+1 queries (eager load), missing indexes (EXPLAIN ANALYZE), unbounded result sets (paginate), chatty transactions. Use a connection pool sized to the database's limits.
Outbound calls: reuse one httpx.AsyncClient per process (connection pooling, keep-alive), set timeouts, run independent calls concurrently with asyncio.gather and a semaphore, cache results.
Caching: Redis for computed results, HTTP caching headers (Cache-Control, ETag) so clients and CDNs skip requests.
Serialisation: when a return type or response_model is set, current FastAPI serialises through Pydantic directly to JSON bytes, which is fast; ORJSONResponse and UJSONResponse are now deprecated for that reason. Without a declared model, FastAPI falls back to jsonable_encoder plus json.dumps, which is slower. Avoid building big intermediate dicts; return only fields clients use.
Event loop health: no blocking calls in async def; offload CPU work.
Payload size: GZipMiddleware (with minimum_size) for large JSON; compress at the proxy if possible.
Process model: workers per CPU core, tuned by load test. Python 3.13+ and recent Pydantic releases also bring free speed-ups, so stay current.
Avoid premature micro-optimisation: replacing one JSON library rarely matters when a query takes 80 ms. Change one thing at a time and re-measure, and keep a performance test in CI for critical endpoints.
python
import asyncio
import time
from fastapi import FastAPI
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
app.add_middleware(GZipMiddleware, minimum_size=1000)
class Row(BaseModel):
roll_no: int
name: str
attendance: float
ROWS = [{"roll_no": i, "name": f"Student {i}", "attendance": 80 + i % 20} for i in range(2000)]
@app.get("/rows-typed", response_model=list[Row])
def rows_typed():
return ROWS
@app.get("/rows-untyped")
def rows_untyped():
return ROWS
async def fetch(service: str) -> str:
await asyncio.sleep(0.2) # an outbound call
return service
@app.get("/dashboard-sequential")
async def sequential():
return [await fetch(s) for s in ("fees", "library", "hostel")]
@app.get("/dashboard-concurrent")
async def concurrent():
return await asyncio.gather(*(fetch(s) for s in ("fees", "library", "hostel")))
def timed(client, path, **kw):
start = time.perf_counter()
r = client.get(path, **kw)
return r, time.perf_counter() - start
with TestClient(app) as c:
_, seq = timed(c, "/dashboard-sequential")
_, con = timed(c, "/dashboard-concurrent")
print("concurrent calls faster than sequential:", con < seq / 2)
r, _ = timed(c, "/rows-typed", headers={"Accept-Encoding": "gzip"})
print("gzip:", r.headers.get("content-encoding"), "| rows:", len(r.json()))
print("same data either way:", c.get("/rows-typed").json() == c.get("/rows-untyped").json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Timings are compared rather than printed, so the output is stable across machines.
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):
concurrent calls faster than sequential: True
gzip: gzip | rows: 2000
same data either way: True
Key points
Measure p95/p99 and trace before changing code
Database and outbound I/O are usually the biggest wins
Reuse HTTP clients; cache; run independent calls concurrently
Declare response models: FastAPI serialises via Pydantic to JSON bytes
ORJSONResponse is deprecated in current FastAPI; tune workers by load test
Common mistakes
Optimising JSON libraries before checking database time
Creating a new HTTP client per request
Returning thousands of rows with no pagination
Tuning worker counts by guesswork instead of load tests
Measuring averages only and missing tail latency
Follow-ups
How would you find which part of a slow endpoint takes the time?
Why did FastAPI deprecate ORJSONResponse?
How do you choose the number of workers for an async service?
Tips
Start with measurement and tools
Rank fixes by typical impact
Know the current serialisation behaviour with response models
40.fastapi-0040Hardsenior
How do you implement fine-grained authorisation in FastAPI with OAuth2 scopes and Security()?
Declare scopes on OAuth2PasswordBearer(scopes={...}), put granted scopes in the token, and declare required scopes per endpoint with Security(get_current_user, scopes=["marks:write"]). Inside the dependency, SecurityScopes.scopes lists every scope required by the dependency chain, so one function checks them all and returns 401 or 403 with a proper WWW-Authenticate header. Scopes also appear in OpenAPI so /docs can request them.
Full answer
Role checks ("is admin?") get coarse quickly. OAuth2 scopes express permissions as strings such as marks:read, marks:write, fees:refund. A token carries the scopes granted to that user or client, and each endpoint states what it needs.
Pieces:
python
oauth2 = OAuth2PasswordBearer(tokenUrl="token",
scopes={"marks:read": "Read marks", "marks:write": "Edit marks"})
def get_current_user(security_scopes: SecurityScopes, token: str = Depends(oauth2)):
payload = decode(token)
granted = set(payload.get("scopes", []))
missing = [s for s in security_scopes.scopes if s not in granted]
if missing:
raise HTTPException(403, "Not enough permissions",
headers={"WWW-Authenticate": f'Bearer scope="{security_scopes.scope_str}"'})
return user
@app.put("/marks/{id}")
def edit(user = Security(get_current_user, scopes=["marks:write"])): ...
How it works:
Security() is Depends() plus scopes.
SecurityScopes collects scopes from the whole dependency chain. If a router requires marks:read and an endpoint adds marks:write, the dependency sees both.
Dependency caching is per set of scopes, so the same user dependency with different scopes is resolved separately.
Keep scopes about actions on resources, and map roles to scopes in one place at token creation (teacher gets marks:read marks:write).
Scopes say what kinds of action are allowed; they do not cover ownership. "Can edit marks" still needs "only for my classes", which belongs in the service or query layer (filter by teacher ID).
401 for missing or invalid tokens, 403 for valid tokens without the scope.
If an identity provider issues tokens, read scopes from its claim (scope as a space-separated string in many providers, scp in some) and validate audience and issuer.
Libraries such as Casbin or Oso help when rules become complex (attribute-based access control).
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install pyjwt`. Tokens are created directly with demo roles to keep the example short.
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, PyJWT 2.15.1):
{'roll_no': 'BCA-17', 'maths': 81, 'viewer': 'aditi'}
403 {'detail': 'Missing scope: marks:write'} Bearer scope="marks:write"
{'roll_no': 'BCA-17', 'updated_by': 'mr_paul'}
401
[{'OAuth2PasswordBearer': ['marks:write']}]
Key points
Scopes are permission strings carried in the token
Security(dep, scopes=[...]) declares requirements per endpoint
SecurityScopes aggregates scopes across the chain
401 for bad token, 403 for missing scope
Ownership checks still belong in services or queries
Common mistakes
Checking scopes in each endpoint body instead of one Security dependency
Returning 401 when the token is valid but lacks a scope
Treating scopes as ownership checks
Trusting scopes from a token without verifying signature, audience and issuer
Follow-ups
How would you restrict a teacher to editing marks only for their own classes?
How do scopes from a router and an endpoint combine?
When would you move to a policy engine such as Casbin or Oso?