Performance: Numeric validation (gt, lt, ge, le)
This affects server-side request validation speed and response time by how quickly numeric constraints are checked before processing.
from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() class Item(BaseModel): price: float = Field(..., gt=0) @app.post('/items/') async def create_item(item: Item): return item
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): price: float @app.post('/items/') async def create_item(item: Item): if item.price <= 0: return {'error': 'Price must be greater than 0'} return item
| Pattern | Server CPU Cost | Validation Speed | Frontend Impact | Verdict |
|---|---|---|---|---|
| Manual numeric validation in endpoint | Higher due to extra code | Slower, runs after parsing | None | [!] OK |
| Pydantic gt/lt/ge/le validation | Minimal CPU overhead | Fast, during parsing | None | [OK] Good |
Field to ensure a number is strictly greater than 10?gtgt parameter means "greater than" and excludes the value itself.gt=10 is the correct choice.gt=10 -> Option Ale stands for "less than or equal to".Field(le=100) to enforce the value to be at most 100.from pydantic import BaseModel, Field
class Item(BaseModel):
price: float = Field(gt=0, le=100)price=0?gt=0 (greater than 0) and le=100 (less or equal to 100).gt=0 rule.from pydantic import BaseModel, Field
class User(BaseModel):
age: int = Field(ge=18, lt=65)age=65, it passes validation. Why?lt and lelt=65 means strictly less than 65, so 65 should fail validation.le=65 (less or equal) instead of lt=65, allowing 65.lt=65 means less than 65, so 65 should fail but it passes because you used le=65 instead of lt=65 -> Option Age (greater or equal) and le (less or equal).ge=1 and le=5 to allow 1 and 5 as valid values.Pass the test and this pattern moves unknown