Area 08 · Backend · Concept 19 of 20

Input Validation with Pydantic

Define request and response shapes in Python. Bad data is rejected automatically.

11–20 · Production levelPhase 0 + 5 · Weeks 1–2, 18–20≈ 45 min

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.

Why it matters

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

  1. Run the example and open /docs.
  2. Send a message longer than allowed and a temperature of 5.
  3. Read the 422 error.

Use it in code

Request and response models for a chat endpoint.

python
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=[])
PRACTICE · TICK IT AFTER THIS

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.

Go deeper