Performance: Why validation prevents bad data
Validation affects server response time and client experience by catching errors early and reducing unnecessary processing.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float @app.post('/items/') async def create_item(item: Item): process(item.dict()) return {'status': 'success'}
from fastapi import FastAPI app = FastAPI() @app.post('/items/') async def create_item(item: dict): # No validation, assume data is correct process(item) return {'status': 'success'}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No validation | N/A | N/A | N/A | [X] Bad |
| Automatic validation with Pydantic | N/A | N/A | N/A | [OK] Good |
name: str = Field(...).name: str = Field(min_length=3), which is correct.age: int = Field(gt=0), what happens if a client sends {"age": -5}?age must be greater than 0 (gt=0).-5 violates this rule, so validation fails.username: str field?
class User(BaseModel):
username: str
username: str accepts any string, including empty ones.min_length=1 in Field().Pass the test and this pattern moves unknown