Performance: Custom request validation
This affects the server response time and user experience by adding processing before sending responses.
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): return {"message": "Item created"}
from fastapi import FastAPI, Request app = FastAPI() @app.post("/items") async def create_item(request: Request): data = await request.json() if 'name' not in data or not isinstance(data['name'], str): return {"error": "Invalid name"} # manual validation for each field if 'price' not in data or not isinstance(data['price'], (float, int)): return {"error": "Invalid price"} return {"message": "Item created"}
| Pattern | CPU Usage | Response Delay | Code Complexity | Verdict |
|---|---|---|---|---|
| Manual field checks in endpoint | High CPU per request | Delays response by ms to 10s | High, repetitive code | [X] Bad |
| Pydantic model validation | Low CPU, optimized C code | Minimal delay, async friendly | Low, declarative code | [OK] Good |
from pydantic import BaseModel, validator
class User(BaseModel):
age: int
@validator('age')
def age_must_be_positive(cls, v):
if v <= 0:
raise ValueError('Age must be positive')
return v
{"age": -5} to a FastAPI endpoint using this model?from pydantic import BaseModel, validator
class Item(BaseModel):
price: float
@validator('price')
def check_price(cls, value):
if value < 0:
return ValueError('Price must be non-negative')
return value
Pass the test and this pattern moves unknown