Script Valley
FastAPI: Build Production Python APIs
FastAPI FoundationsLesson 1.3

How to validate request bodies with Pydantic models in FastAPI

Pydantic BaseModel, request body declaration, field types, Field constraints, nested models, JSON schema generation, automatic validation

Request Body Validation with Pydantic

FastAPI uses Pydantic models to describe, validate, and parse JSON request bodies. Declare a class that inherits from BaseModel, add typed fields, and use it as a parameter type in your route function.

Basic model and route

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    in_stock: bool = True

@app.post("/items/")
def create_item(item: Item):
    return item

FastAPI reads the JSON body, validates every field against the types declared, and injects a fully typed Item object into the function. If price is missing or is a string that cannot be coerced, the caller gets a 422 with details about which field failed.

Adding constraints with Field

from pydantic import BaseModel, Field

class Product(BaseModel):
    name: str = Field(..., min_length=2, max_length=100)
    price: float = Field(..., gt=0)
    quantity: int = Field(default=0, ge=0)

Field(...) marks a field as required. Use gt, ge, lt, le, min_length, max_length to constrain values. These constraints appear in the generated OpenAPI schema so frontend teams see them too.

Nested models

class Address(BaseModel):
    city: str
    country: str

class User(BaseModel):
    name: str
    address: Address

Nest models directly. Pydantic validates the full tree and FastAPI serializes it back to nested JSON automatically.

Up next

How FastAPI response models and status codes work

Sign in to track progress