In FastAPI, what JSON body does an endpoint expect with several body parameters, and what does Body(embed=True) change for a single one?
answer
- one body, several parameters
- keys are the parameter names
- scalars need Body()
- embed forces the wrapper key
- dependencies count too
basics
~20 sWith more than one body parameter, FastAPI expects one JSON object keyed by the parameter names, each holding its own value. A single model parameter is the whole body; Body(embed=True) wraps it under its parameter name instead.
solid answer
~40 sA request has one body, so FastAPI picks a shape for all body parameters. With one model parameter, `order: Order`, the JSON body is the order itself. With several, for example `order: Order`, `buyer: Buyer` and `priority: Annotated[int, Body()]`, FastAPI expects one object with `order`, `buyer` and `priority` keys and validates each part separately. A scalar needs `Body()`, otherwise it is a query parameter. `Body(embed=True)` forces the wrapper for a single parameter, so `{"order": {...}}` is expected instead of the bare order. FastAPI counts body parameters across the endpoint's dependencies too, so a dependency that reads a body model switches the endpoint to the embedded shape.
code
python · 30 linesfrom typing import Annotated
from fastapi import Body, FastAPI
from pydantic import BaseModel
app = FastAPI()
class Order(BaseModel):
sku: str
quantity: int = 1
class Buyer(BaseModel):
email: str
full_name: str | None = None
@app.post("/orders")
async def create_order(
order: Order,
buyer: Buyer,
priority: Annotated[int, Body()],
):
return {"order": order, "buyer": buyer, "priority": priority}
@app.post("/orders/draft")
async def create_draft(order: Annotated[Order, Body(embed=True)]):
return ordergo deeper
Remember that a single model parameter is the whole JSON body, and that several body parameters become keys named after the parameters.
Explain the embedding rule, why a scalar needs Body() to join the body, what Body(embed=True) changes for one parameter, and how /docs shows the generated Body_ schema.
Diagnose the client break when a body-reading dependency is added: the endpoint switches to the embedded shape although its own signature did not change. Treat body shape as a contract.
Weigh a team convention of always embedding bodies, which lets an endpoint gain another body parameter later without a shape change, against flat bodies that match common client expectations, and decide how the contract is reviewed.
## One request, one body An HTTP request carries at most one body. FastAPI still lets a path operation declare several **body parameters**, for example an `Order`, a `Buyer` and a `priority` number in a create-order endpoint. To make that work it decides on a single JSON shape that holds all of them, validates each part separately, and hands each part to its own parameter. The shape depends on how many body parameters there are and on one switch, `Body(embed=True)`. ## A single model is the whole body With exactly one body parameter, `order: Order`, FastAPI expects the JSON body **to be** the order: ```json {"sku": "LAMP-01", "quantity": 2} ``` There is no wrapper key. Sending `{"order": {"sku": "LAMP-01"}}` fails validation, because FastAPI looks for `sku` at the top level and finds only `order`. ## Several body parameters are keyed by name As soon as more than one body parameter is declared, FastAPI **embeds** every one of them under its parameter name: ```json { "order": {"sku": "LAMP-01", "quantity": 2}, "buyer": {"email": "[email protected]"}, "priority": 2 } ``` Three points make this work: - **Models are body parameters automatically.** `order: Order` and `buyer: Buyer` need no marker. - **Scalars need `Body()`.** A plain `priority: int` would be a query parameter; `priority: Annotated[int, Body()]` makes it a key in the body object. - **Each part validates on its own.** An error in the buyer is reported against the `buyer` key, and the order still arrives as an `Order` instance when the whole request is valid. FastAPI documents the combined object in the OpenAPI schema as a generated model whose name starts with `Body_` and is derived from the operation, so `/docs` shows the client the exact wrapper it must send. ## Body(embed=True) for a single parameter Sometimes you want the wrapper even with one body parameter, for example to match an existing client or to leave room for more keys later. `Body(embed=True)` asks for it: ```python async def create_draft(order: Annotated[Order, Body(embed=True)]): ... ``` | Declaration | Body FastAPI expects | |---|---| | `order: Order` | `{"sku": "LAMP-01"}` | | `order: Annotated[Order, Body(embed=True)]` | `{"order": {"sku": "LAMP-01"}}` | | `order: Order, buyer: Buyer` | `{"order": {...}, "buyer": {...}}` | | `priority: Annotated[int, Body()]` alone | `2` | | `priority: Annotated[int, Body(embed=True)]` alone | `{"priority": 2}` | `embed` changes only where the value sits in the JSON. It does not change how the model's fields validate, and setting it on one parameter among several changes nothing, because they are already embedded. ## Body parameters inside dependencies FastAPI counts body parameters across the **whole dependency tree**, not only the endpoint's own signature. Suppose the create-order endpoint took a flat `order: Order` body, and a teammate adds a dependency `current_buyer(buyer: Buyer)` to it. There are now two body parameter names, so both are embedded, and every existing client that sends the flat order body starts receiving 422 responses for a missing `order` key. Nothing in the endpoint's own signature changed. The schema in `/docs` reveals it: the request body becomes a `Body_...` object with `order` and `buyer` keys. Treat adding a body-reading dependency as a contract change for the endpoint. ## Body, path and query together Body parameters combine freely with path and query parameters: 1. Names in the path template bind from the path. 2. Models, containers and anything marked `Body()` bind from the JSON body, embedded by name when there are several. 3. Remaining scalars bind from the query string. So `create_order(store_id: int, order: Order, buyer: Buyer, priority: Annotated[int, Body()], dry_run: bool = False)` on `/stores/{store_id}/orders` takes `store_id` from the path, `dry_run` from the query string, and an object with `order`, `buyer` and `priority` keys from the body. ## Mistakes to avoid - Expecting two models to be merged into one flat object. They are nested under their names. - Forgetting `Body()` on a scalar that clients send inside the JSON; FastAPI then waits for it in the query string. - Adding a second body parameter, directly or through a dependency, without telling clients the body shape changed. - Reaching for `embed=True` on every parameter of a multi-body endpoint; it is already automatic there. The interview answer is the shape rule plus its edges: keyed by name when there are several, the bare value when there is one, `embed=True` to force the key, and dependencies counting toward the total.
- Why does a FastAPI endpoint that accepted a flat Order body start answering 422 after a dependency declaring a Buyer body parameter is added?FastAPI collects body parameters from the whole dependency tree. Two distinct body parameter names mean every body parameter is embedded, so the client must now send `{"order": {...}, "buyer": {...}}`; the old flat body fails as a missing `order` key. Either update the clients and the contract, or have the dependency read the buyer from somewhere other than the body.
- What does a FastAPI endpoint whose only parameter is `priority: Annotated[int, Body()]` expect as its body?The bare JSON value, for example `2`, because a single body parameter is not embedded unless `embed=True` is set. With `Body(embed=True)` it expects `{"priority": 2}`. Adding any second body parameter embeds both automatically.
A courier box with one item ships the item loose; with several items, each goes into its own labelled pouch inside the same box. Body(embed=True) asks for the labelled pouch even when only one item is inside.
- Two model parameters are merged into one flat JSON object
- Every parameter of a multi-body endpoint needs Body(embed=True)
- A plain int beside two models is read from the body automatically
- Body(embed=True) changes how the model's fields are validated
- Body parameters declared in dependencies never affect the endpoint's body shape