Performance: Optional and nullable fields
This affects the API response size and validation speed, impacting initial response time and user experience.
from typing import Optional from pydantic import BaseModel class User(BaseModel): name: str age: Optional[int] = None # only optional if truly needed email: str
from typing import Optional from pydantic import BaseModel class User(BaseModel): name: Optional[str] = None age: Optional[int] = None email: Optional[str] = None
| Pattern | Validation Cost | Payload Size | Response Time Impact | Verdict |
|---|---|---|---|---|
| Many optional/nullable fields | High (validates many fields) | Large (includes nulls) | Slower (blocks response) | [X] Bad |
| Minimal optional/nullable fields | Low (validates fewer fields) | Small (only needed data) | Faster (quicker response) | [OK] Good |
Optional[str] in a request model?from typing import Optional
from pydantic import BaseModel
class User(BaseModel):
name: str
nickname: Optional[str] = None
user = User(name='Alice')user.nickname?from typing import Optional
from pydantic import BaseModel
class Item(BaseModel):
description: Optional[str]
email can be omitted, but if present, it can be set to null explicitly. Which is the best way to declare this field?Pass the test and this pattern moves unknown