Performance: Pydantic model basics
This affects server response time and memory usage by validating and parsing data efficiently before processing.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str @app.post("/items") async def create_item(item: Item): return {"item": item}
from fastapi import FastAPI, Request app = FastAPI() @app.post("/items") async def create_item(request: Request): data = await request.json() # manual validation if "name" not in data or not isinstance(data["name"], str): return {"error": "Invalid name"} return {"item": data}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual JSON validation in endpoint | N/A (server-side) | N/A | N/A | [X] Bad |
| Using Pydantic BaseModel for validation | N/A (server-side) | N/A | N/A | [OK] Good |
Pydantic model in FastAPI?name?from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
item = Item(id='10', name='Book')
print(item.id, type(item.id))from pydantic import BaseModel
class Product(BaseModel):
price: float = 'free'User with an optional age field that defaults to 18 if not provided. Which is the correct way?Pass the test and this pattern moves unknown