Full answer
Models compose naturally:
class Address(BaseModel):
city: str
pin: str = Field(pattern=r"^\d{6}$")
class Mark(BaseModel):
subject: str
score: int = Field(ge=0, le=100)
class Student(BaseModel):
name: str
address: Address
marks: list[Mark] = Field(min_length=1, max_length=10)
tags: set[str] = set()Behaviour:
- The incoming JSON object nests the same way:
{"name": "Asha", "address": {...}, "marks": [{...}]}. - Validation is recursive. Errors include the position:
["body", "marks", 1, "score"]. list[Mark]validates each item.set[str]removes duplicates and, in JSON output, becomes a list.dict[str, int]accepts arbitrary string keys with integer values (useful for maps like subject to score).- The nested models appear in
/docsundercomponents.schemas, so clients can generate types from them. - A body that is only a list (
list[Mark]) is allowed: declaremarks: list[Mark]as the parameter and send a JSON array. - Within the function you get typed objects:
student.address.city, andfor m in student.marks. Convert withmodel_dump()when you need dicts.
Design tips: keep payloads shallow where possible; deeply nested bodies are hard to validate, patch and document. For read-heavy responses use separate response models. Limit collection size to avoid denial of service from huge arrays, and set a maximum request body size at the proxy or ASGI layer. Recursive structures (a tree of comments) need forward references: children: list["Comment"] = [], followed by model_rebuild() if required.
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class Address(BaseModel):
city: str
pin: str = Field(pattern=r"^\d{6}$")
class Mark(BaseModel):
subject: str
score: int = Field(ge=0, le=100)
class Student(BaseModel):
name: str
address: Address
marks: list[Mark] = Field(min_length=1, max_length=3)
tags: set[str] = set()
@app.post("/students")
def create(student: Student):
best = max(student.marks, key=lambda m: m.score)
return {"city": student.address.city, "best": best.subject, "tags": sorted(student.tags)}
c = TestClient(app)
good = {"name": "Asha", "address": {"city": "Pune", "pin": "411001"},
"marks": [{"subject": "Maths", "score": 91}, {"subject": "DBMS", "score": 84}], "tags": ["a", "a", "b"]}
print(c.post("/students", json=good).json())
bad = {**good, "address": {"city": "Pune", "pin": "41"}, "marks": [{"subject": "Maths", "score": 101}]}
print([(e["loc"], e["type"]) for e in c.post("/students", json=bad).json()["detail"]])
print([(e["loc"], e["type"]) for e in c.post("/students", json={**good, "marks": []}).json()["detail"]])
print(sorted(c.get("/openapi.json").json()["components"]["schemas"]))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'city': 'Pune', 'best': 'Maths', 'tags': ['a', 'b']} [(['body', 'address', 'pin'], 'string_pattern_mismatch'), (['body', 'marks', 0, 'score'], 'less_than_equal')] [(['body', 'marks'], 'too_short')] ['Address', 'HTTPValidationError', 'Mark', 'Student', 'ValidationError']
Key points
- Models nest as field types; validation is recursive
- Errors carry a full loc path including list indexes
- Constrain collection sizes with Field
- Nested models appear in OpenAPI components
- Keep bodies shallow and limit sizes
Common mistakes
- Creating very deep or unbounded nested payloads
- Not limiting list sizes
- Forgetting forward references for recursive models
- Mutating nested objects from shared defaults
Follow-ups
- How do you validate that list items are unique?
- How would you accept a bare JSON array as the body?
- How do recursive models work?
Tips
- Describe recursive validation
- Show error loc for nested fields
- Mention size limits