Performance: Field validation rules
Field validation rules affect server response time and user experience by validating input before processing.
from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() class Item(BaseModel): name: str = Field(..., min_length=3) price: float = Field(..., gt=0) @app.post('/items/') async def create_item(item: Item): return item
from fastapi import FastAPI app = FastAPI() @app.post('/items/') async def create_item(name: str, price: float): if not name or len(name) < 3: return {'error': 'Name too short'} if price <= 0: return {'error': 'Price must be positive'} return {'name': name, 'price': price}
| Pattern | CPU Usage | Response Latency | Code Complexity | Verdict |
|---|---|---|---|---|
| Manual validation in endpoint | High CPU per request | Higher latency | More complex and repetitive | [X] Bad |
| Pydantic model validation | Lower CPU per request | Lower latency | Simpler and reusable | [OK] Good |
Field with parameters like min_length or ge in FastAPI models?Field?min_length to set minimum string length.min_length=3, which is correct syntax.from pydantic import BaseModel, Field
class User(BaseModel):
age: int = Field(ge=18, le=65)
user = User(age=70)user?from pydantic import BaseModel, Field
class Product(BaseModel):
code: str = Field(regex="[A-Z]{3}[0-9]{4}")
product = Product(code="abC1234")Field validation is correct?Pass the test and this pattern moves unknown