Difficulty: Beginner
What is Pydantic, and how does FastAPI use Pydantic models to validate the request body?
Pydantic is a Python library that validates and parses data using type hints: you declare a class that inherits from BaseModel, and Pydantic turns raw input such as JSON into a typed object or raises a detailed ValidationError. When a FastAPI handler parameter is typed as a Pydantic model, FastAPI reads the JSON request body, validates it against the model and passes you a ready-to-use instance, returning a 422 automatically if the data is invalid.
POST /users with Content-Type: application/json.UserCreate instance with attribute access and editor autocomplete.422 with a list of errors, each with a loc (like ["body", "email"]), msg and type.The same model also appears in the OpenAPI schema, so Swagger UI shows example payloads and the required fields.
FastAPI has used Pydantic v2 by default since FastAPI 0.100 (2023), and Pydantic v1 support is deprecated in current FastAPI releases. The v2 API differs from tutorials you may find online:
| v1 (old) | v2 (current) |
|---|---|
.dict() / .json() | .model_dump() / .model_dump_json() |
parse_obj() | model_validate() |
@validator | @field_validator (a classmethod) |
@root_validator | @model_validator(mode="after") |
class Config: | model_config = ConfigDict(...) |
orm_mode = True | from_attributes=True |
The validation core (pydantic-core) is written in Rust, which makes v2 much faster than v1.
By default Pydantic runs in lax mode: the string "25" is accepted for an int field and converted. That is convenient for query strings but sometimes surprising for JSON. Use Field(strict=True), StrictInt, or model_config = ConfigDict(strict=True) when you want exact types. Also note that unknown fields are ignored by default; set extra="forbid" to reject them, which helps catch client typos.
Field(): Field(min_length=1, max_length=100), Field(gt=0), Field(pattern=r"^[6-9]\d{9}quot;) for an Indian mobile number.@field_validator("name").@model_validator(mode="after").ValueError inside validators; Pydantic converts it into a 422 entry.float for money. Use integer paise or Decimal.password_hash. Use separate UserCreate, UserUpdate and UserOut models.tags: list[str] = [] are safe in Pydantic (it copies them), unlike plain Python functions, but Field(default_factory=list) is clearer.from datetime import date
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, EmailStr, Field, field_validator, model_validator
app = FastAPI()
class InternshipApplication(BaseModel):
model_config = ConfigDict(extra="forbid") # reject unknown fields
name: str = Field(min_length=2, max_length=80)
email: EmailStr # needs: pip install "pydantic[email]"
phone: str = Field(pattern=r"^[6-9]\d{9}quot;) # 10-digit Indian mobile
cgpa: float = Field(ge=0, le=10)
start_date: date
end_date: date
skills: list[str] = Field(default_factory=list, max_length=20)
@field_validator("skills")
@classmethod
def normalise_skills(cls, v: list[str]) -> list[str]:
return sorted({s.strip().lower() for s in v if s.strip()})
@model_validator(mode="after")
def check_dates(self):
if self.end_date <= self.start_date:
raise ValueError("end_date must be after start_date")
return self
@app.post("/applications", status_code=201)
def apply(app_in: InternshipApplication):
return {"received": app_in.model_dump()}
Field() covers simple constraints, field_validator cleans one field and model_validator checks rules that involve several fields. extra='forbid' turns unknown keys into errors.
POST /applications
{"name": "A", "email": "not-an-email", "phone": "12345", "cgpa": 8.4,
"start_date": "2026-06-01", "end_date": "2026-05-01"}
Every failing field is reported at once, each with its location in the body, so the frontend can highlight the right inputs.
Pydantic v2, BaseModel, request body, field_validator, Field, serialization