Skip to content
FastAPI

Pydantic Request Body

Validate JSON bodies with Pydantic models.

By EZ4Code Team
pydanticrequest-bodyvalidation

Code

from pydantic import BaseModel, Field, EmailStr
from fastapi import FastAPI

app = FastAPI()

class UserIn(BaseModel):
    name: str = Field(..., min_length=1, max_length=50)
    email: EmailStr
    age: int = Field(0, ge=0, le=150)
    tags: list[str] = []

@app.post("/users")
def create_user(user: UserIn):
    return {"created": user}

@app.put("/users/{user_id}")
def update_user(user_id: int, user: UserIn):
    return {"user_id": user_id, "user": user}

Explanation

A Pydantic BaseModel declares the shape of the JSON body and FastAPI validates it before the handler runs. Field() adds constraints such as length and numeric bounds, and EmailStr enforces email format. Validation errors automatically produce a 422 response with detailed messages.

More FastAPI Snippets