- Courses
- 📚Libraries & Frameworks
- ⚡FastAPI
- Foundations of FastAPI
- Pydantic Models
- Request Models
On this page
Defining and Validating Request Bodies with Pydantic
Published on August 9, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
A request body is the data a client sends along with a request, typically as JSON, and it's how POST, PUT, and PATCH endpoints receive structured input that a URL alone can't carry — a path parameter or a query string works fine for a single value like an ID, but a whole object like a new task or a new user needs somewhere else to go. FastAPI reads request bodies through Pydantic models: a class whose fields describe exactly what shape the incoming JSON is expected to have, validated the same way a path or query parameter's type hint is validated, just applied to an entire object at once instead of a single value.
What a Request Body Is​
A request body is the payload attached to an HTTP request, distinct from anything embedded in the URL itself:
{
"title": "Buy milk",
"completed": false
}
This is different from a path parameter, which is part of the URL's structure (/tasks/42), and from a query parameter, which is appended after a ? (/tasks?completed=false). A request body can carry an entire structured object in a single request, which is what makes it the right fit for creating or updating a resource that has more than one field.
Why FastAPI Uses Pydantic for Request Bodies​
Pydantic models exist to describe a data shape once and get validation, parsing, and documentation from that single definition, rather than writing three separate things by hand. A model class states which fields are expected and what type each one should be; FastAPI uses that same class to parse the incoming JSON against it, reject anything that doesn't match with a structured error, and contribute that shape directly to the OpenAPI schema that powers both Swagger UI and ReDoc. The type hints on a Pydantic model's fields aren't a separate concept from the type hints already used on path and query parameters — they're the exact same validation system, just applied to a full JSON object instead of one URL value.
Defining a Request Body with a Pydantic Model​
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Task(BaseModel):
title: str
completed: bool
@app.post("/tasks")
def create_task(task: Task):
return {"message": "Task created", "task": task}
Task inherits from Pydantic's BaseModel, and its two fields — title as str, completed as bool — define the exact shape a request body must match. Declaring task: Task as the function's parameter tells FastAPI to read the request body as JSON, validate it against Task, and pass in a fully validated Task instance if it matches — the function itself never touches raw JSON directly.
Testing the endpoint​
fastapi dev main.py
Visiting http://127.0.0.1:8000/docs and sending this body to /tasks:
{
"title": "Buy milk",
"completed": false
}
returns:
{
"message": "Task created",
"task": {
"title": "Buy milk",
"completed": false
}
}
What a Validation Failure Actually Returns​
Sending a body where the types don't match —
{
"title": 123,
"completed": "nope"
}
— produces a 422 Unprocessable Entity response with a structured error for each field that failed:
{
"detail": [
{
"type": "string_type",
"loc": ["body", "title"],
"msg": "Input should be a valid string",
"input": 123
},
{
"type": "bool_parsing",
"loc": ["body", "completed"],
"msg": "Input should be a valid boolean, unable to interpret input",
"input": "nope"
}
]
}
loc identifies exactly which field failed and where it came from (body, here, rather than path or query), type is a stable error code that can be checked in code, msg explains the problem in plain language, and input echoes back the exact value that was rejected. Both fields fail here for a reason worth being precise about: 123 sent for title isn't silently converted into the string "123" — a JSON number is a different type from a JSON string, and Pydantic rejects the mismatch outright rather than guessing at an implicit conversion. "nope" fails for a different reason — it's a string, which is a type bool fields do accept, but only for a specific recognized set of values (true, false, 1, 0, yes, no, and a few case variants), and "nope" isn't one of them.
Optional Fields and Defaults​
class Task(BaseModel):
title: str
completed: bool = False
description: str | None = None
completed = False gives the field a default, so a request body that omits completed entirely still validates successfully, with the field filled in as False — but if completed is present in the body, it still has to be a valid boolean. description: str | None = None goes a step further: str | None means the field accepts either a string or the value null/None, and defaulting to None means the field can be left out of the request body altogether. Together, these two patterns cover the two common shapes "optional" takes in a request body: a field that's always present but falls back to a sensible value, and a field that may not be sent at all.
Practice: Building the User Model and Endpoint​
class User(BaseModel):
username: str
email: str
is_active: bool = True
bio: str | None = None
@app.post("/users")
def create_user(user: User):
return {"message": "User created", "user": user}
username and email are required str fields, since neither has a default — a request body missing either one fails validation with a "missing" error rather than falling back to anything. is_active defaults to True, so a request that omits it is treated as an active user by default while still rejecting a non-boolean value if one is sent. bio follows the same optional pattern as description above — accepted as a string, accepted as None, or left out of the body entirely. Sending {"username": "alice", "email": "[email protected]"} to POST /users returns {"message": "User created", "user": {"username": "alice", "email": "[email protected]", "is_active": true, "bio": null}}, with both defaults filled in automatically.
Key Takeaways​
A Pydantic model turns request body validation into the same kind of type-hint-driven check already used for path and query parameters, just applied to a whole JSON object at once — a field's type is both its validation rule and its contribution to the generated API docs. A validation failure returns the same structured 422 error shape regardless of which part of the request failed, with loc identifying the field, type giving a stable error code, and input echoing back the rejected value. Pydantic does not coerce mismatched JSON types into the expected one — a number sent where a string is expected fails rather than converting — which makes "optional" worth defining precisely: a field with a default value like completed: bool = False can be omitted but must still match its type if present, while a field typed as str | None = None can be omitted, sent as null, or sent as an actual string.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Pydantic Models
Next
Response Models
-
What a Request Body Is
-
Why FastAPI Uses Pydantic for Request Bodies
-
Defining a Request Body with a Pydantic Model
- Testing the endpoint
-
What a Validation Failure Actually Returns
-
Optional Fields and Defaults
-
Practice: Building the User Model and Endpoint
-
Key Takeaways
