Full answer
Where time goes: building a validator (schema compilation) is expensive; running it is cheap. Per-request building is the most common mistake.
Practical rules:
- Create
TypeAdapter(list[Student])at module level. CallingTypeAdapter(...)inside a request handler rebuilds the core schema every time. The same applies to defining models inside functions. - Parse bytes directly:
Model.model_validate_json(raw)avoids creating an intermediate Python dict fromjson.loads. In FastAPI the framework already parses the body for you, but for custom reads (webhooks, queue messages, files) this saves memory and time. - Strict mode:
ConfigDict(strict=True)orField(strict=True)skips coercion paths (and rejects"5"for anint), which is faster and safer for internal service-to-service payloads. For public JSON APIs lax mode is usually what clients expect. - Avoid double validation: with
response_modelor a return annotation FastAPI validates and serialises your return value, so returning an already-validated model means the work happens twice. For hot endpoints, return plain dicts that match the schema, or return aResponseobject yourself withresponse_model=Nonewhen bytes are prebuilt (cached JSON). model_construct()skips validation: use it only for data you trust (rows from your own database, already validated), never for client input.- Choose cheaper types: concrete
list[int]beatsSequence[int],Literalbeats custom validators, built-in constraints beat Python validators. Pythonfield_validatorfunctions run per item and cost the most.mode="before"validators run extra code on every call. from_attributes=Truefor ORM objects reads attributes; load only the columns you need (select(Student.id, Student.name)) and return rows mapped to a lean model.- Serialisation:
model_dump_json()writes JSON bytes in Rust and is faster thanjson.dumps(model.model_dump()). FastAPI uses this path when a return type or response model exists, so deprecated custom response classes such asORJSONResponseare no longer needed. - Large payloads: stream NDJSON, paginate, and limit list sizes to protect memory.
Measure: use timeit/pyperf on production-shaped payloads and profile endpoints under load (py-spy). The database and network usually dominate, so do not trade readability for micro-gains without evidence.
import json
from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError, validate_call
class Student(BaseModel):
roll_no: str
marks: int
class StrictStudent(BaseModel):
model_config = ConfigDict(strict=True)
roll_no: str
marks: int
STUDENTS = TypeAdapter(list[Student]) # built once, reused for every call
raw = b'[{"roll_no": "BCA-1", "marks": "81"}, {"roll_no": "BCA-2", "marks": 64}]'
parsed = STUDENTS.validate_json(raw) # bytes in, validated models out
print(parsed)
print("same result via json.loads:", parsed == STUDENTS.validate_python(json.loads(raw)))
try:
StrictStudent.model_validate({"roll_no": "BCA-1", "marks": "81"})
except ValidationError as exc:
print("strict mode:", exc.errors()[0]["type"])
trusted = Student.model_construct(roll_no="BCA-3", marks="not-an-int") # no validation at all
print("model_construct keeps bad data:", repr(trusted.marks))
print("serialised:", STUDENTS.dump_json(parsed).decode())
@validate_call
def percent(marks: int, total: int = 100) -> float:
return round(marks * 100 / total, 1)
print(percent("45", total=50))
Standalone script. Run it with `python file.py`; no server is needed. Timing is deliberately not printed because it varies by machine. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): [Student(roll_no='BCA-1', marks=81), Student(roll_no='BCA-2', marks=64)] same result via json.loads: True strict mode: int_type model_construct keeps bad data: 'not-an-int' serialised: [{"roll_no":"BCA-1","marks":81},{"roll_no":"BCA-2","marks":64}] 90.0
Key points
- Build TypeAdapters and models once at import time
- model_validate_json parses and validates bytes in one pass
- Strict mode avoids coercion work when clients are trusted
- Avoid validating the same data twice; model_construct only for trusted data
- Python validators are the slowest part; measure before tuning
Common mistakes
- Creating TypeAdapter or models inside request handlers
- Calling json.loads then model_validate when model_validate_json works
- Returning validated models and also paying for response_model validation on hot paths
- Using model_construct on client input
- Optimising before measuring with real payloads
Follow-ups
- How do you profile a FastAPI endpoint under load?
- What does defer_build do?
- When would you use RootModel?
Tips
- List 3 concrete optimisations
- Say measure first
- Mention Rust core