Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 50 ยท Request parameters

Request bodies

Receive JSON in FastAPI with Pydantic models: body validation, nested data, multiple body parameters, Body(), embedding, and reading 422 error details.

Path and query parameters are fine for short values, but to create or change something you usually send a structured request body, most often JSON. A new user, an order with several lines, a blog post with tags. FastAPI reads the body for you, checks it against a Pydantic model you define, and passes your function a ready-to-use Python object.

You will write models in depth in Pydantic models for APIs. This lesson focuses on how bodies arrive in endpoints. A model is just a class with typed attributes, which is all you need for now.

A body from a Pydantic model

Declare a class that inherits from BaseModel, then use it as the type of a function parameter. FastAPI sees a model type and concludes the data comes from the JSON body.

Python Your first request body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Inside the function, book is a real Book object: book.title, book.pages and so on, with autocomplete in your editor. Fields with defaults (in_stock, subtitle) are optional in the JSON. The helper model_dump() turns the object back into a dictionary.

The client's json= argument encodes a dictionary as JSON and sets the content-type header to application/json. A real client such as curl must send that header itself.

Validation and the error format

If the JSON does not match the model, the request is rejected with 422 and your function never runs. See what that looks like for several mistakes at once:

Python Reading validation errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All problems are reported at once, not just the first. Each entry's loc starts with "body" and then names the field. Missing fields have the type missing.

Notice the second request: "474" became the integer 474. Pydantic's default lax mode converts compatible values, so a numeric string is accepted for an int. A string such as "many" is not. If you want strictness, see Pydantic models for APIs. Broken JSON gives a 422 of a different type, json_invalid.

Mixing path, query and body

FastAPI decides where each parameter comes from using simple rules:

Where does each parameter come from?

Path The name appears in the route string.
Query A plain type (int, str, bool) not in the path.
Body A Pydantic model parameter.

You never mark them by hand; the signature is enough.

1 / 2

That means one endpoint can use all three at once:

Python Path + query + body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

book_id is a path parameter, notify a query parameter and update the body.

Multiple body parameters

When a function declares two or more model parameters, FastAPI expects the JSON body to contain a key for each parameter name. The body becomes a wrapper object:

Python Two models in one body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second call sends a flat object. FastAPI looked for item and buyer keys and reported both as missing, with locations ["body", "item"] and ["body", "buyer"].

Body() for single values and embedding

A plain value such as an int is normally read from the query string. To read it from the body instead, mark it with Body(). You can also force a single model to be wrapped under its parameter name with embed=True, which keeps the JSON shape stable when you add parameters later.

Python Body() and embed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Body(ge=1, le=5) also adds validation: 9 stars is rejected. Use embedding when you want clients to send {"item": {...}} even though only one model is declared.

Nested models and lists

Models can contain other models and lists of them, so real-world JSON maps directly to classes:

Python
class Line(BaseModel):
    sku: str
    quantity: int

class Order(BaseModel):
    customer: str
    lines: list[Line]

A body of {"customer": "Ada", "lines": [{"sku": "A1", "quantity": 2}]} validates the whole tree. An error deep inside has a loc such as ["body", "lines", 0, "quantity"], pointing at the exact element. The next lessons cover nesting properly: Pydantic models for APIs and Response models and nested data.

Do not use GET with a body. Some clients and proxies drop or reject it. Use POST, PUT or PATCH when the request carries data, and put filters for GET in the query string.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does FastAPI know a parameter comes from the JSON body?

    A parameter typed as a BaseModel subclass is read from the request body. Plain types are read from the path or query string.
  2. 2. What does the loc of a validation error for a missing field title look like?

    Errors name where the data was expected. For body fields the location starts with body, followed by the field name.
  3. 3. An endpoint declares two model parameters, item and buyer. What must the JSON body look like?

    With several body parameters, FastAPI uses the parameter names as keys in a wrapper object.
  4. 4. What is Body(embed=True) for?

    Embedding makes the client send {"item": {...}} even for one model, keeping the shape stable if more parameters are added later.
  5. 5. A client posts {"title": "Emma", "pages": "474"} to a model where pages is an int. What happens in default (lax) mode?

    Pydantic's lax mode converts compatible values such as numeric strings. Only values that cannot be converted fail.

Summary

  • A parameter typed as a Pydantic model is read from the JSON request body.
  • Invalid bodies give a 422 listing every problem with loc, type and msg.
  • Path, query and body parameters mix freely in one signature.
  • Several model parameters expect a wrapper object keyed by parameter name.
  • Body() reads plain values from the body and adds constraints; embed=True wraps a single model.
  • Nested models and lists validate whole JSON trees, with precise error locations.

Next, read metadata and files with Headers, cookies, forms and uploads.