Lesson 9 of 59How backends work
Pydantic Models
Describe request and response shapes with Pydantic models so FastAPI validates input and controls output.
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.
from pydantic import BaseModel
class TodoCreate(BaseModel):
title: str
done: bool = False
priority: int = 1TodoCreate(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.
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 recordSo FastAPI now has three places to look, decided by the type:
| Declaration | Read from |
|---|---|
Name appears in the path, like {todo_id} | Path |
Simple type: int, str, bool, enum | Query string |
| A Pydantic model | JSON body |
Send {"title": 42} and the route never runs. The client gets a 422 whose detail has "loc": ["body", "title"] and "type": "string_type".
def update(todo_id: int, notify: bool, data: TodoCreate) on @app.put("/todos/{todo_id}"), where is notify read from?What happens to a body
The body arrives as bytes and is parsed into a dict. Nothing is trusted yet.
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).
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 valueEmailStr 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"].
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.
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.
Using the Model class above, what does this print?
try: TodoCreate(title=5) except ValueError as err: print(err)
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.
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.
User object and has no response model. What is the risk?Separate schemas for create, read and update
One model per direction is the standard pattern, because the shapes really differ:
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 = NoneThe 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".
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:
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: intHere 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.
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?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:
class TodoCreate(BaseModel):
model_config = ConfigDict(extra="forbid")
title: Annotated[str, Field(min_length=1, max_length=200)]
done: bool = FalseUse 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.
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 selfAnnotated[str, AfterValidator(fn)]attaches a rule to a type. DefineTitleonce 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. Usebeforeto 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 returnself. Its error has an emptyloc, 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:
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.
Field(discriminator="type") to method: Card | BankTransfer?Money and time
Two kinds of data cause more production bugs than any other: money and timestamps. Run this to see why.
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.
What does this print?
from decimal import Decimal
a = Decimal("0.10") * 3
b = 0.10 * 3
print(a, b == 0.3)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:
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.
The one boundary FastAPI handles for you.
Pydantic v2 renamed several v1 methods. Match old to new.
Practice
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)] = NoneReturn {"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):
| Field | Problem | type |
|---|---|---|
| any required | key absent | missing |
| username, email | not a string | string_type |
| username | under 3 / over 20 characters | string_too_short / string_too_long |
not exactly one @ with text before it and a . in the part after | value_error | |
| age | a string that is not an integer (lax mode accepts "42") | int_parsing |
| age | below 13 | greater_than_equal |
Unknown keys (like "is_admin") are ignored and must not appear in data. A missing age becomes None.
- 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"to3are 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,georpattern. - 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.