Trung BìnhPython iconPython

Pydantic validation trong FastAPI hoạt động thế nào?

FastAPI dùng Pydantic model để tự động validate request body, query params, path params.

Trả về 422 Unprocessable Entity nếu invalid.

python
from pydantic import BaseModel, EmailStr, Field, field_validator

class UserCreate(BaseModel):
    name: str = Field(min_length=2, max_length=50)
    email: EmailStr
    age: int = Field(ge=0, le=150)

    @field_validator('name')
    @classmethod
    def name_alpha(cls, v: str) -> str:
        if not v.replace(' ', '').isalpha():
            raise ValueError('Only letters allowed')
        return v.strip().title()

    model_config = {"from_attributes": True}  # Pydantic v2

@app.post("/users", status_code=201)
async def create_user(user: UserCreate):  # Auto-validated!
    ...

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python