Careeroza
Field Validation
Field()
Example
Field adds rules and documentation to model attributes:
from fastapi import FastAPI
from pydantic import BaseModel, Field
class Signup(BaseModel):
username: str = Field(min_length=3, max_length=20, pattern=r"^[a-z0-9_]+$")
age: int = Field(ge=13, le=120)
bio: str = Field(default="", max_length=160)
app = FastAPI()
@app.post("/signup")
def signup(data: Signup):
return {"welcome": data.username}Requests and responses
POST /signup {"username": "asha_21", "age": 21}
→ 200 {"welcome": "asha_21"}
POST /signup {"username": "A!", "age": 9}
→ 422 {"detail": [{"type": "string_too_short", "loc": ["body", "username"], "msg": "String should have at least 3 characters", "input": "A!", "ctx": {"min_length": 3}}, {"type": "greater_than_equal", "loc": ["body", "age"], "msg": "Input should be greater than or equal to 13", "input": 9, "ctx": {"ge": 13}}]}Custom Validators and Nested Models
Example
from fastapi import FastAPI
from pydantic import BaseModel, field_validator
class Item(BaseModel):
name: str
qty: int
class Order(BaseModel):
customer: str
items: list[Item]
@field_validator("items")
@classmethod
def not_empty(cls, items):
if not items:
raise ValueError("an order needs at least one item")
return items
app = FastAPI()
@app.post("/orders")
def place_order(order: Order):
return {"customer": order.customer, "units": sum(i.qty for i in order.items)}Requests and responses
POST /orders {"customer": "Asha", "items": [{"name": "pen", "qty": 3}, {"name": "book", "qty": 1}]}
→ 200 {"customer": "Asha", "units": 4}
POST /orders {"customer": "Asha", "items": []}
→ 422 {"detail": [{"type": "value_error", "loc": ["body", "items"], "msg": "Value error, an order needs at least one item", "input": [], "ctx": {"error": {}}}]}