Performance: Example data in schema
This affects the speed of API response serialization and validation during request handling.
from pydantic import BaseModel class User(BaseModel): id: int name: str bio: str = "Short bio" class Config: schema_extra = { "example": { "id": 1, "name": "Alice", "bio": "Short bio" } }
from pydantic import BaseModel class User(BaseModel): id: int name: str bio: str = """A very long biography text repeated many times to simulate large example data...""" class Config: schema_extra = { "example": { "id": 1, "name": "Alice", "bio": "A very long biography text repeated many times to simulate large example data..." } }
| Pattern | Schema Size | Validation Time | Serialization Time | Verdict |
|---|---|---|---|---|
| Large example data | Large (10+ KB) | High (blocks startup) | High (adds 20ms) | [X] Bad |
| Minimal example data | Small (<1 KB) | Low (fast startup) | Low (adds <5ms) | [OK] Good |
example data in a FastAPI schema field?Field(..., example=...) to add example data to schema fields.Field(example="John Doe"), which is the correct syntax for example data.from pydantic import BaseModel, Field
class User(BaseModel):
username: str = Field(..., example="alice123")
age: int = Field(..., example=30)age field?example=30, which is an integer value 30.from pydantic import BaseModel, Field
class Item(BaseModel):
name: str = Field(example=123)
price: float = Field(..., example="9.99")Field(example=...) to show correct samples in docs.Pass the test and this pattern moves unknown