FastAPI · Chapter 2 of 6
FastAPI request body and response models with Pydantic
13 min study · Examples checked with FastAPI 0.163 and Pydantic 2.14 on Python 3.14 ·
Path and query parameters carry small values. Creating or changing data needs a request body, usually a JSON object. FastAPI describes bodies with Pydantic models: classes that declare the fields, their types and their rules. One model defines what clients may send; another defines what they get back. Keeping the two apart is how an API avoids accepting fields it shouldn’t, and leaking fields it shouldn’t, such as internal notes or password hashes. This chapter covers both directions and the special case of partial updates.
Declare the input with a model
from typing import Annotated
from fastapi import Body, FastAPI
from pydantic import BaseModel, ConfigDict, Field, field_validator
class Resource(BaseModel):
url: str = Field(pattern=r"^https://")
kind: str = "article"
class LessonCreate(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
title: str = Field(min_length=3, max_length=120)
minutes: int = Field(ge=1, le=180)
tags: list[str] = []
resources: list[Resource] = []
@field_validator("tags")
@classmethod
def normalize_tags(cls, tags: list[str]) -> list[str]:
return sorted({t.strip().casefold() for t in tags if t.strip()})
class LessonRead(BaseModel):
id: int
title: str
minutes: int
tags: list[str]
resources: list[Resource]
app = FastAPI()
@app.post("/lessons", response_model=LessonRead, status_code=201)
def create_lesson(lesson: LessonCreate):
stored = {"id": 1, **lesson.model_dump(), "reviewer_notes": "internal only"}
return stored
@app.post("/notes")
def add_note(text: Annotated[str, Body(embed=True, min_length=1, max_length=500)]):
return {"length": len(text)}
A parameter whose type is a Pydantic model is read from the JSON body. Field adds the same kind of constraints you used for query parameters. ConfigDict sets model-wide behaviour: extra="forbid" rejects unknown keys, so a client typo such as "minuts" fails loudly instead of being dropped, and str_strip_whitespace trims strings before the length checks, which makes " " too short. Models can nest, so each item in resources is validated as a Resource. A @field_validator runs your own code on a field; here it normalizes tags to unique lowercase values. Pydantic copies default values for each instance, so tags: list[str] = [] is safe in a model, unlike in a function signature.
The handler pretends to store the lesson and always returns ID 1; chapter 5 adds real storage.
What validation does with a request
A request with messy but acceptable data:
POST /lessons
{"title": " Loops ", "minutes": "15", "tags": ["Python", " basics", "python", ""],
"resources": [{"url": "https://docs.python.org"}]}
201 {"id": 1, "title": "Loops", "minutes": 15, "tags": ["basics", "python"],
"resources": [{"url": "https://docs.python.org", "kind": "article"}]}
The title was trimmed, the string "15" became the integer 15, the tags were cleaned by the validator, and the nested resource got its default kind. A request that breaks several rules gets all of them reported at once:
POST /lessons {"title": " ", "minutes": 0, "level": "easy"}
422 ["body", "title"] string_too_short String should have at least 3 characters
["body", "minutes"] greater_than_equal Input should be greater than or equal to 1
["body", "level"] extra_forbidden Extra inputs are not permitted
Errors inside nested data carry the full path, such as ["body", "resources", 0, "url"] for a resource URL that doesn’t start with https://.
Converting "15" to 15 is Pydantic’s default lax mode, which is friendly to clients that send numbers as strings. If an API must reject that, set ConfigDict(strict=True) on the model, or use strict types for single fields; "15" then fails with int_type: Input should be a valid integer. Decide this once per API and document it.
The body shape: embedded or not
By default the JSON body is the model itself, not an object with a lesson key around it. A single plain value such as text: str would expect the raw JSON string "remember range" as the whole body. Body(embed=True) wraps it instead, so /notes expects {"text": "remember range"} and returns {"length": 14}. When a handler declares two body models, FastAPI embeds both automatically under their parameter names. If in doubt about what a route expects, check the request schema in /docs.
Filter the output with response_model
LessonCreate has no id, because clients don’t choose it. LessonRead has one. The handler returns a dictionary that also contains reviewer_notes, yet the response above doesn’t include it: response_model=LessonRead validates the return value against LessonRead and keeps only its fields. That makes the public shape of the API a deliberate, reviewed decision rather than whatever the handler happens to return. Credentials, password hashes and internal flags stay out by construction.
You can declare the same thing with a return annotation (def create_lesson(...) -> LessonRead:), which also lets type checkers see it; the response_model parameter is needed when the function returns a dictionary or ORM object rather than an actual LessonRead. If the returned data doesn’t fit the model (say, a missing minutes), FastAPI raises a server error rather than sending broken data. That is a bug in your code, and tests should catch it. Returning a Response object directly skips all of this, so don’t use one to send JSON that should be filtered.
Partial updates with PATCH
PUT conventionally replaces a whole resource, so its body model looks like the create model. PATCH changes only the fields the client sends, which needs a model where every field is optional, and a way to tell “not sent” from “sent”:
from pydantic import BaseModel, ConfigDict, Field
class LessonPatch(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
title: str | None = Field(default=None, min_length=3, max_length=120)
minutes: int | None = Field(default=None, ge=1, le=180)
patch = LessonPatch.model_validate({"minutes": 20})
print(patch.model_dump()) # {'title': None, 'minutes': 20}
print(patch.model_dump(exclude_unset=True)) # {'minutes': 20}
print(LessonPatch.model_validate({"title": None}).model_dump(exclude_unset=True))
# {'title': None}
model_dump(exclude_unset=True) returns only the fields the client actually sent, which is exactly the set of changes to apply. The last line shows the remaining question: a client can explicitly send null. For a title, which can’t be empty, that should be rejected. Chapter 5 shows the check. For an optional field like a description, null might mean “clear it”. Decide per field.
Pydantic 2 renamed several methods from version 1, and old tutorials still use the previous names: .dict() is now model_dump(), parse_obj() is model_validate(), .json() is model_dump_json(), and orm_mode = True became ConfigDict(from_attributes=True).
Practice
Add a level field to LessonCreate that accepts only "beginner", "intermediate" or "advanced" and defaults to "beginner". Add a @model_validator(mode="after") that rejects lessons longer than 60 minutes at beginner level. Write TestClient tests for a valid lesson, a 90-minute beginner lesson and an unknown level.
Answer check: use level: Literal["beginner", "intermediate", "advanced"] = "beginner". The model validator receives the whole model (self) and raises ValueError("beginner lessons are at most 60 minutes"), which FastAPI reports as a 422 with the message prefixed by Value error, and loc ["body"], because the rule belongs to the whole object rather than to one field. Remember to add level to LessonRead too if clients should see it.
Summary
A Pydantic model declares a JSON body: types, Field constraints, nested models, validators, and extra="forbid" for strictness about unknown keys. Lax mode converts compatible values, strict mode doesn’t. Use a separate output model with response_model so only intended fields leave the server, and for PATCH apply model_dump(exclude_unset=True) with an explicit rule for null.