The idea
Every request from outside is untrusted. Pydantic models declare the expected shape: field types, required and optional fields, string lengths, number ranges, allowed values and custom checks. FastAPI validates every request body, query and path parameter against them and returns a clear 422 error when input is wrong.
Response models do the same on the way out: they guarantee your API returns the documented shape and never leaks extra fields like password hashes or internal IDs.
The same Pydantic models validate LLM structured outputs, so one library guards both your API boundary and your model boundary.
Validation at the edge prevents a whole class of bugs and security issues, and documents your API for free.
Words to know
- Model (Pydantic)A class describing and validating data.
- 422FastAPI’s status code for validation errors.
Try it without code
Send bad input
- Run the example and open /docs.
- Send a message longer than allowed and a temperature of 5.
- Read the 422 error.
Use it in code
Request and response models for a chat endpoint.
from typing import Literal
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class ChatIn(BaseModel):
message: str = Field(min_length=1, max_length=4000)
mode: Literal["chat", "json"] = "chat"
temperature: float = Field(0.3, ge=0, le=1)
document_ids: list[str] = Field(default_factory=list, max_length=20)
class Citation(BaseModel):
document_id: str
page: int
class ChatOut(BaseModel):
answer: str
citations: list[Citation]
@app.post("/v1/chat", response_model=ChatOut)
def chat(body: ChatIn) -> ChatOut:
return ChatOut(answer=f"echo: {body.message}", citations=[])Add request and response models to every endpoint in your API and check /docs shows them.
Common mistakes
- Accepting dict and validating by hand.
- Returning ORM objects without a response model.