Performance: Pydantic model definition
Defines data validation and serialization which impacts API response time and server CPU usage.
from pydantic import BaseModel from typing import List, Dict class Address(BaseModel): street: str city: str class User(BaseModel): id: int name: str email: str address: Address preferences: Dict[str, str] history: List[int]
from pydantic import BaseModel class User(BaseModel): id: int name: str email: str address: dict preferences: dict history: list # Using generic dict and list without strict typing
| Pattern | CPU Usage | Validation Time | Serialization Speed | Verdict |
|---|---|---|---|---|
| Generic dict/list fields | High | Slow | Slower | [X] Bad |
| Typed nested models | Low | Fast | Faster | [OK] Good |
Pydantic model in FastAPI?name and an optional integer field age?name: str (required) and age: Optional[int] = None (optional), which is correct.from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
price: float
item = Item(id='5', name='Book', price=12.99)item.id after creation?item.id becomes int 5.from pydantic import BaseModel
class Product(BaseModel):
name: str
price: float = 'free'price expects a float but is given a string default 'free'.User with a required username (string), an optional email (string), and a roles list of strings that defaults to an empty list. Which is the correct way to define it?Optional[str] = None to allow missing value.roles: list[str] = [] is unsafe because lists are mutable defaults shared across instances. Use Field(default_factory=list) to create a new list each time.Pass the test and this pattern moves unknown