Skip to content

Lesson 9 of 59How backends work

Pydantic Models

Describe request and response shapes with Pydantic models so FastAPI validates input and controls output.

28 min read0/7 questions

A JSON body is a message from a stranger. It might be missing fields, have a number where you expected text, or contain "is_admin": true that you never asked for. Pydantic lets you describe the exact shape you accept and the exact shape you send back, and FastAPI enforces both on every request. It is the single biggest reason FastAPI code is short and safe.

A model is a typed shape

A Pydantic model is a class that inherits from BaseModel and lists fields with type hints. Creating one validates the data: it checks types, converts what it safely can, and raises a ValidationError listing every problem.

app/schemas.py
from pydantic import BaseModel
 
 
class TodoCreate(BaseModel):
    title: str
    done: bool = False
    priority: int = 1
TodoCreate(title="Buy milk")
# TodoCreate(title='Buy milk', done=False, priority=1)
 
TodoCreate(title="Buy milk", priority="3")
# priority is converted to 3: the string holds a valid integer
 
TodoCreate(priority="high")
# ValidationError: 2 validation errors for TodoCreate
#   title     Field required [type=missing]
#   priority  Input should be a valid integer [type=int_parsing]

By default Pydantic runs in lax mode: "3" becomes 3, and "true" becomes True. Values that cannot be converted without guessing, like "high" or 3.5 for an int, are errors. If you want no conversion at all, set model_config = ConfigDict(strict=True).

Request bodies

Declare a parameter whose type is a model, and FastAPI reads it from the JSON body.

app/main.py
from fastapi import FastAPI, status
 
from app.schemas import TodoCreate
 
app = FastAPI()
todos: list[dict] = []
 
 
@app.post("/todos", status_code=status.HTTP_201_CREATED)
def create_todo(todo: TodoCreate):
    record = {"id": len(todos) + 1, **todo.model_dump()}
    todos.append(record)
    return record

So FastAPI now has three places to look, decided by the type:

DeclarationRead from
Name appears in the path, like {todo_id}Path
Simple type: int, str, bool, enumQuery string
A Pydantic modelJSON body

Send {"title": 42} and the route never runs. The client gets a 422 whose detail has "loc": ["body", "title"] and "type": "string_type".

Quick check
In def update(todo_id: int, notify: bool, data: TodoCreate) on @app.put("/todos/{todo_id}"), where is notify read from?
Need a nudge? A hint rules out a wrong answer.

What happens to a body

A POST body on its way through FastAPI
  1. Raw bytes{"title": "Buy milk", "priority": "2", "is_admin": true}
  2. Parse JSONBytes to Python dict. Broken JSON is a 422 here.
  3. Validate with TodoCreateTypes, conversions, constraints. Unknown keys are ignored.
  4. Your functionReceives a TodoCreate instance, fully typed
  5. Filter with response_modelOnly declared output fields survive
  6. Serialize to JSONThe response body

The body arrives as bytes and is parsed into a dict. Nothing is trusted yet.

1/4

Constraints with Field

Types say "a string". Field says "a string of 1 to 200 characters". Like Query in the last lesson, it goes inside Annotated (or as the default).

app/schemas.py
from typing import Annotated
 
from pydantic import BaseModel, EmailStr, Field, field_validator
 
 
class UserCreate(BaseModel):
    username: Annotated[str, Field(min_length=3, max_length=20, pattern=r"^[a-z0-9_]+$")]
    email: EmailStr
    password: Annotated[str, Field(min_length=12)]
    age: Annotated[int | None, Field(ge=13)] = None
 
    @field_validator("username")
    @classmethod
    def not_reserved(cls, value: str) -> str:
        if value in {"admin", "root"}:
            raise ValueError("this username is reserved")
        return value

EmailStr checks the email format (it needs the email-validator package, which fastapi[standard] includes). @field_validator runs your own rule after the built-in checks; raising ValueError turns into a 422 with "type": "value_error".

Nested models and lists

Fields can be other models or lists of them. Validation goes all the way down, and error locations show the full path, like ["body", "items", 2, "quantity"].

app/schemas.py
class Tag(BaseModel):
    name: str
    color: str = "gray"
 
 
class TodoCreate(BaseModel):
    title: Annotated[str, Field(min_length=1, max_length=200)]
    tags: list[Tag] = []

Under the hood: a tiny validator

Pydantic's core is written in Rust and is very fast, but the idea is easy to copy. This version reads a class's type hints, converts lax values, and collects all the errors instead of stopping at the first.

Pythonmini_pydantic.py
MISSING = object() class Model: def __init__(self, **data): errors = [] for name, typ in type(self).__annotations__.items(): value = data.get(name, getattr(type(self), name, MISSING)) if value is MISSING: errors.append({"loc": name, "type": "missing"}) continue if typ is int and isinstance(value, str): try: value = int(value) # lax mode: "3" -> 3 except ValueError: errors.append({"loc": name, "type": "int_parsing"}) continue if not isinstance(value, typ): errors.append({"loc": name, "type": f"{typ.__name__}_type"}) continue setattr(self, name, value) if errors: raise ValueError(errors) def model_dump(self): return {name: getattr(self, name) for name in type(self).__annotations__} class TodoCreate(Model): title: str done: bool = False priority: int = 1 print(TodoCreate(title="Buy milk", priority="3", is_admin=True).model_dump())try: TodoCreate(priority="high", done="yes")except ValueError as err: print(err)
Output
Press Run (⌘ Enter) to see what happens.

Notice that is_admin silently disappeared: only declared fields are kept. That is the same default Pydantic uses (extra="ignore"), and it is why you can never be tricked into saving a field you did not declare. Set model_config = ConfigDict(extra="forbid") to reject unknown keys with a 422 instead.

Predict the outputPython

Using the Model class above, what does this print?

try:
  TodoCreate(title=5)
except ValueError as err:
  print(err)
Need a nudge? Hints walk you through it.

Response models: control what leaves

Your database row for a user has a hashed_password. Your API must never return it. Declare the output shape with a return type or response_model, and FastAPI filters the result through it.

app/main.py
class UserRead(BaseModel):
    id: int
    username: str
    email: EmailStr
 
 
@app.get("/users/{user_id}")
def get_user(user_id: int) -> UserRead:
    row = {"id": user_id, "username": "ada", "email": "ada@example.com", "hashed_password": "pbkdf2$..."}
    return row   # hashed_password is filtered out

-> UserRead and @app.get(..., response_model=UserRead) do the same thing. Use response_model when the function returns something whose type does not match, such as a database object. The response model is also what /docs shows as the response schema.

Quick check
A route returns a database User object and has no response model. What is the risk?
Need a nudge? A hint rules out a wrong answer.

Separate schemas for create, read and update

One model per direction is the standard pattern, because the shapes really differ:

app/schemas.py
from pydantic import ConfigDict
 
 
class TodoBase(BaseModel):
    title: Annotated[str, Field(min_length=1, max_length=200)]
    done: bool = False
 
 
class TodoCreate(TodoBase):          # what the client sends to create
    pass
 
 
class TodoRead(TodoBase):            # what the API returns
    id: int
    model_config = ConfigDict(from_attributes=True)   # can read ORM objects
 
 
class TodoUpdate(BaseModel):         # PATCH: every field optional
    title: Annotated[str | None, Field(min_length=1, max_length=200)] = None
    done: bool | None = None

The client never sends id (the server assigns it), so it is only in TodoRead. For a partial update, todo.model_dump(exclude_unset=True) returns only the fields the client actually sent. That is how you tell "set done to false" apart from "did not mention done".

Pythonexclude_unset.py
stored = {"id": 7, "title": "Buy milk", "done": False} def apply_patch(stored, sent): # sent is what model_dump(exclude_unset=True) would give you return {**stored, **sent} print(apply_patch(stored, {"done": True}))print(apply_patch(stored, {"title": "Buy oat milk"}))# Without exclude_unset, defaults of None would wipe real data:print(apply_patch(stored, {"title": None, "done": True}))
Output
Press Run (⌘ Enter) to see what happens.

Strict versus lax mode

Lax mode is friendly, and most of the time it is what you want. It is also where a few surprises live. In lax mode "3" becomes 3, 3.0 becomes 3, 1 becomes True for a bool, and "yes" becomes True as well. A client that sends "active": "false" gets False, which is fine. A client that sends "active": 0 because its language has no booleans also gets False, which may or may not be fine. Lax mode will still refuse anything lossy: 3.5 for an int is an int_from_float error, and 5 for a str is a string_type error, because Pydantic never turns numbers into text.

Strict mode turns conversion off, so a field only accepts its exact type. You can switch it on for a whole model or for one field:

app/schemas.py
from decimal import Decimal
from typing import Annotated
 
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt
 
 
class Transfer(BaseModel):
    from_account: StrictInt                      # "42" is rejected, 42 is fine
    amount: Annotated[Decimal, Field(gt=0)]      # still lax: "19.99" is fine
    notify: StrictBool = False                   # "yes" and 1 are rejected
 
 
class Everything(BaseModel):
    model_config = ConfigDict(strict=True)       # every field is strict
    qty: int

Here is the trap that bites FastAPI teams. FastAPI parses the JSON body into Python objects first and then validates them, so validation runs in Pydantic's Python mode. In Python mode a strict datetime field wants a real datetime object, and a strict UUID field wants a real UUID. JSON has neither; it only has strings. So a model-wide strict=True used as a FastAPI body rejects "2026-10-22T10:00:00Z" with datetime_type and a perfectly good UUID string with is_instance_of. (The same model validated with Everything.model_validate_json(...) would accept them, because JSON mode knows that dates arrive as strings.)

The practical rule: leave models lax, and make individual fields strict where a silent conversion would be a bug. Account ids, quantities and flags that drive money or permissions are good candidates. Dates, UUIDs, decimals and enums should stay lax, because their JSON form is a string.

Quick check
You add model_config = ConfigDict(strict=True) to a FastAPI request body that has created_at: datetime. A client sends {"created_at": "2026-10-22T10:00:00Z"}. What happens?
Need a nudge? A hint rules out a wrong answer.

Rejecting unknown fields with extra="forbid"

You saw that unknown keys are dropped by default. Dropping is safe from a security point of view, but it hides client bugs. A mobile app sends "titel": "Buy milk", the typo is ignored, title is missing, and the user sees a confusing "title: Field required" error. Worse, a client sends "notify": true to an endpoint that has no notify field, gets a 201, and assumes notifications were sent.

extra="forbid" turns every unknown key into a 422 with "type": "extra_forbidden" and the exact key in loc:

app/schemas.py
class TodoCreate(BaseModel):
    model_config = ConfigDict(extra="forbid")
    title: Annotated[str, Field(min_length=1, max_length=200)]
    done: bool = False

Use it on input models: request bodies, query parameter models and messages you consume. Do not use it on models that parse other people's output, such as a payment provider's webhook or a third-party API response. Those providers add fields all the time, and they consider that a non-breaking change. If your parser forbids extras, their harmless release breaks your integration. The general rule, which Evolving an API Without Breaking Clients calls the tolerant reader, is: be strict about what you accept from your own clients, and tolerant about what you read from others.

Validators: field, model and reusable types

Field constraints cover lengths, ranges and patterns. Anything else is a validator. Pydantic v2 gives you three tools, and choosing the right one keeps models readable.

app/schemas.py
from typing import Annotated
 
from pydantic import AfterValidator, AwareDatetime, BaseModel, field_validator, model_validator
 
 
def not_blank(value: str) -> str:
    value = value.strip()
    if not value:
        raise ValueError("must not be blank")
    return value
 
 
Title = Annotated[str, AfterValidator(not_blank)]   # a reusable type, use it anywhere
 
 
class BookingCreate(BaseModel):
    title: Title
    room: str
    start: AwareDatetime
    end: AwareDatetime
 
    @field_validator("room", mode="before")
    @classmethod
    def normalise_room(cls, value: object) -> object:
        return value.upper() if isinstance(value, str) else value
 
    @model_validator(mode="after")
    def end_after_start(self) -> "BookingCreate":
        if self.end <= self.start:
            raise ValueError("end must be after start")
        return self
  • Annotated[str, AfterValidator(fn)] attaches a rule to a type. Define Title once and every model that uses it gets the same rule. This is the most reusable option and the one to reach for first.
  • @field_validator("room", mode="before") runs before type validation, on the raw input. Use before to clean data into shape (strip, upper-case, split a comma list). The default, mode="after", runs on the already-typed value.
  • @model_validator(mode="after") sees the whole, already-validated model, so it is where rules about several fields go. It must return self. Its error has an empty loc, which FastAPI reports as ["body"].

Validators should be pure checks and small transformations. Do not query the database from a validator to check that an email is unique: validators run whenever a model is built (tests, scripts, response filtering), they cannot be awaited, and the check races with other requests anyway. Uniqueness belongs to a unique constraint in the database, as Transactions and Concurrency Bugs in Web Apps shows.

Discriminated unions

Some fields can take several shapes. A payment method is a card or a bank transfer, and each has different fields. A plain union, method: Card | Bank, works, but Pydantic has to try each member in turn. When none fits, the client gets an error for every member: a literal_error from Card and a missing from Bank, which is confusing.

A discriminated union names the field that decides the shape:

app/schemas.py
from decimal import Decimal
from typing import Annotated, Literal
 
from pydantic import BaseModel, Field
 
 
class Card(BaseModel):
    type: Literal["card"]
    token: str
    last4: Annotated[str, Field(pattern=r"^\d{4}$")]
 
 
class BankTransfer(BaseModel):
    type: Literal["bank"]
    iban: str
 
 
class PaymentCreate(BaseModel):
    amount: Annotated[Decimal, Field(gt=0, max_digits=12, decimal_places=2)]
    method: Annotated[Card | BankTransfer, Field(discriminator="type")]

Now Pydantic reads type first and validates against exactly one model. {"type": "bank", "last4": "1234"} produces one clear error at ["method", "bank", "iban"]. An unknown "type": "crypto" is a union_tag_invalid error that lists the allowed tags, and a missing type is union_tag_not_found. It is faster too, and the OpenAPI schema gets a discriminator mapping, so generated TypeScript clients get a proper tagged union. Use this pattern for event payloads, webhook bodies and any "kind" field.

Quick check
Why add Field(discriminator="type") to method: Card | BankTransfer?
Need a nudge? A hint rules out a wrong answer.

Money and time

Two kinds of data cause more production bugs than any other: money and timestamps. Run this to see why.

Pythonmoney_and_time.py
from datetime import datetime, timedelta, timezonefrom decimal import ROUND_HALF_EVEN, Decimal # Money: a float is a binary fraction, so most decimal prices are approximationsprint(0.1 + 0.2)print(Decimal("0.1") + Decimal("0.2"))print(Decimal(0.1)) # built from a float: the float's error comes along price = Decimal("19.99")total = price * 3vat = (total * Decimal("0.20")).quantize(Decimal("0.01"), rounding=ROUND_HALF_EVEN)print(total, vat) cents = 1999 * 3 # or store integer minor unitsprint(cents, f"{cents // 100}.{cents % 100:02d}") # Time: a naive datetime has no zone, so it cannot be compared with a real instantnaive = datetime(2026, 10, 22, 9, 0)aware = datetime(2026, 10, 22, 9, 0, tzinfo=timezone.utc)try: print(naive < aware)except TypeError as err: print("TypeError:", err) paris = aware.astimezone(timezone(timedelta(hours=2)))print(paris.isoformat(), paris == aware)
Output
Press Run (⌘ Enter) to see what happens.

For money, never use float. Use Decimal with max_digits and decimal_places (as in PaymentCreate above), or store integer minor units (amount_cents: int) as Stripe does. Pydantic serialises a Decimal to a JSON string, "19.99", so no JavaScript client turns it back into a float by accident. Clients should send amounts as strings too.

For time, use AwareDatetime on inputs. It rejects "2026-10-22T10:00:00" with timezone_aware, because a time without an offset means different instants in London and Tokyo. Accept any offset, convert to UTC in your code, store timestamptz in Postgres, and send ISO 8601 with an offset back out. If a field is a calendar date with no time (a birthday, a due date), use date, not a midnight datetime.

Predict the outputPython

What does this print?

from decimal import Decimal

a = Decimal("0.10") * 3
b = 0.10 * 3
print(a, b == 0.3)
Need a nudge? Hints walk you through it.

Validating data you did not receive over HTTP

FastAPI validates request bodies for you. Every other way data enters your service is just as untrusted, and nothing validates it unless you do: a JSON response from a partner API, a message from a queue, a row from a CSV import, a webhook, a value from an environment variable. The senior habit is parse at the boundary, trust inside: turn raw data into a typed model the moment it arrives, and pass only models around after that.

For a model you already have, use Model.model_validate(data) or, for raw JSON bytes, Model.model_validate_json(raw) (faster, because it skips building a dict). For anything that is not a model, such as a list of models or a constrained int, use a TypeAdapter:

app/integrations/github.py
from pydantic import BaseModel, TypeAdapter
 
 
class GitHubUser(BaseModel):          # tolerant: no extra="forbid" on someone else's data
    login: str
    id: int
 
 
GitHubUsers = TypeAdapter(list[GitHubUser])   # build once, at import time
 
 
async def fetch_org_members(client, org: str) -> list[GitHubUser]:
    response = await client.get(f"https://api.github.com/orgs/{org}/members")
    response.raise_for_status()
    return GitHubUsers.validate_json(response.content)

If GitHub ever sends a member without an id, you get a ValidationError with loc (0, "id") at the edge of your code, with a clear message, instead of a KeyError three functions later, or a None saved into your database. Build TypeAdapters once at module level: creating one compiles a validator, which is too slow to repeat on every call. The same idea powers settings, which Settings and Config covers with pydantic-settings.

Parse at the boundary, trust inside
  1. HTTP request bodyFastAPI validates it with your request model
  2. Partner API responseTypeAdapter(list[Model]).validate_json(response.content)
  3. Queue message or webhookEvent.model_validate_json(raw), often a discriminated union
  4. Environment and config filespydantic-settings BaseSettings
  5. Your services and domain codeOnly ever see typed, validated models. No dict.get with fallbacks.

The one boundary FastAPI handles for you.

1/3
Match the pairs0/5 matched

Pydantic v2 renamed several v1 methods. Match old to new.

Choose an item, then its match on the other side.

Practice

ChallengeMedium

Validate a signup body like Pydantic

Write validate_signup(data) that validates a JSON body the way this Pydantic model would:

class UserCreate(BaseModel):
    username: Annotated[str, Field(min_length=3, max_length=20)]
    email: str                       # must look like an email
    age: Annotated[int | None, Field(ge=13)] = None

Return {"ok": True, "data": {"username": ..., "email": ..., "age": ...}} on success, or {"ok": False, "errors": [{"loc": field, "type": code}, ...]} with every error, in field order (username, email, age).

Error codes (the same names Pydantic uses):

FieldProblemtype
any requiredkey absentmissing
username, emailnot a stringstring_type
usernameunder 3 / over 20 charactersstring_too_short / string_too_long
emailnot exactly one @ with text before it and a . in the part aftervalue_error
agea string that is not an integer (lax mode accepts "42")int_parsing
agebelow 13greater_than_equal

Unknown keys (like "is_admin") are ignored and must not appear in data. A missing age becomes None.

Python
def validate_signup(data: dict) -> dict: # Check username, email and age in order, collecting {"loc", "type"} errors. pass
Key terms
BaseModel
Pydantic's base class. Subclasses declare fields with type hints and validate data on creation.
request body
JSON sent with POST, PUT or PATCH. A model-typed parameter tells FastAPI to read and validate it.
response_model
The output schema for a route. FastAPI filters the return value through it, so only declared fields are sent.
lax mode
Pydantic's default: safe conversions like "3" to 3 are allowed. Strict mode allows none.
exclude_unset
model_dump(exclude_unset=True) returns only fields the client actually sent. Essential for PATCH.
Field
Adds constraints and metadata to a model field, like min_length, ge or pattern.
extra="forbid"
Model config that turns unknown input keys into a 422 instead of silently dropping them. Use it on inputs you own.
discriminated union
A union where one field, such as type, names which model to validate against. Gives precise errors and a tagged schema.
TypeAdapter
Validates any type, such as list[Model], without a wrapper model. Used to parse data at boundaries other than HTTP.
AwareDatetime
A datetime type that rejects values without a timezone offset.