Pydantic models and request body

Difficulty: Beginner

Question

What is Pydantic and how does FastAPI use it for request body validation?

Answer

Pydantic is a data validation library that uses Python type hints. FastAPI uses Pydantic models to define the shape of request bodies, validate incoming data, and serialize responses.

When a Pydantic model is declared as a function parameter (not a path/query param), FastAPI: 1. Reads the request body as JSON 2. Converts types as needed 3. Validates the data against the model 4. Returns a 422 Unprocessable Entity error if validation fails 5. Provides the validated data as a Pydantic model instance

Pydantic v2 (used by default with FastAPI 0.100+) is significantly faster than v1 due to its Rust core.

Code examples

Pydantic model for request body

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr, field_validator
from typing import Optional

app = FastAPI()

class UserCreate(BaseModel):
    name: str
    email: EmailStr
    age: int
    bio: Optional[str] = None

    @field_validator('age')
    @classmethod
    def age_must_be_positive(cls, v):
        if v < 0:
            raise ValueError('age must be positive')
        return v

@app.post("/users")
def create_user(user: UserCreate):
    # user is already validated
    return {"created": user.model_dump()}

Key points

Concepts covered

Pydantic, BaseModel, request body, validation, serialization