skip to content

Payload Schemas

FastAPI reads Pydantic models to parse request bodies and filter responses, and documents both in OpenAPI. Interviewers ask how a response model keeps a password hash out of the output.

on this pageshow

explore

questions

11

In FastAPI, what does an endpoint receive from a parameter typed with a Pydantic model, and what happens when the JSON body does not fit the model?

level: juniorimportance: must knowfreq 70%

answer

  1. the model is the body's contract
  2. parse, validate, then instantiate
  3. 422 before your code runs
  4. a list of models is a top-level array
  5. a None default makes the body optional

basics

~20 s

FastAPI reads the body as JSON, validates it against the model and passes a model instance. Malformed JSON, a missing required field or a wrong type gets a 422 before the function runs, so the endpoint only ever sees valid data.

solid answer

~40 s

Declaring `order: Order`, where `Order` is a `BaseModel`, makes `Order` the contract for the JSON body. On each request FastAPI reads the body, parses it as JSON, validates it against the model, converting values where Pydantic allows, and calls the function with an `Order` instance, so the code uses `order.sku` rather than dictionary lookups. If the body is not valid JSON, a required field is missing or a value cannot be converted, FastAPI answers 422 and the function never runs; the error names the failing field's path, nested fields included. Keys the model does not declare are dropped under the default config. `orders: list[Order]` expects a top-level JSON array, and `order: Order | None = None` makes the body optional. The same model is the request schema in `/docs`.

code

python · 34 lines
python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel


class Buyer(BaseModel):
    email: str


class Order(BaseModel):
    sku: str
    quantity: int = 1
    buyer: Buyer | None = None


app = FastAPI()


@app.post("/orders")
async def create_order(order: Order):
    # order is an Order instance, already validated
    return {"sku": order.sku, "items": order.quantity}


@app.post("/orders/bulk")
async def create_orders(orders: list[Order]):
    # the whole body must be a top-level JSON array of orders
    return {"count": len(orders)}


client = TestClient(app)
print(client.post("/orders", json={"sku": "LAMP-01", "quantity": 2}).json())  # {'sku': 'LAMP-01', 'items': 2}
print(client.post("/orders", json={"sku": "LAMP-01", "quantity": "two"}).status_code)  # 422
print(client.post("/orders/bulk", json=[{"sku": "A"}, {"sku": "B"}]).json())  # {'count': 2}

go deeper

for a junior

Say that a model-typed parameter is the JSON body, that the function gets a validated instance, and that bad input is answered with 422 before the code runs.

for a middle

Walk through the outcomes for a wrong type, a missing field, malformed JSON and an unknown key, and show list and optional bodies.

for a senior

Explain why validating at the edge lets the code behind the endpoint drop shape checks, and where a dict or raw Request parameter quietly gives that up.

for a principal

Argue for typed request models as the default for every write endpoint, and what a team loses in documentation and safety when handlers read raw bodies.

## What declaring a model buys you In FastAPI, typing a path operation parameter with a Pydantic model is the whole contract for a JSON request body. You never parse anything yourself. Declaring `order: Order`, where `Order` subclasses `BaseModel`, tells FastAPI three things at once: the body must be JSON, it must fit `Order`, and the function wants an `Order` instance, not a dictionary. ## The request, step by step For `POST /orders` with `async def create_order(order: Order)`, FastAPI: 1. reads the request body; 2. parses it as JSON; 3. validates the result against `Order`, converting values where Pydantic's rules allow it, such as the string `"2"` into the integer `2` in its default lax mode; 4. builds an `Order` instance and calls your function with it. Inside the function you use attributes, `order.sku` and `order.quantity`, with editor completion and type checking. The same model also becomes the request body schema that `/docs` shows and that client generators read. ## What fails, and when Steps 2 and 3 run **before** your function. When they fail, FastAPI answers **422** and your code never runs: | What the client sends | Result | |---|---| | `{"sku": "LAMP-01", "quantity": 2}` | 200; the function gets `Order(sku='LAMP-01', quantity=2)` | | `{"sku": "LAMP-01", "quantity": "two"}` | 422; `quantity` cannot become an integer | | `{"quantity": 2}` | 422; the required `sku` is missing | | `{"sku": "x",` (cut off) | 422; the body is not valid JSON | | `{"sku": "x", "coupon": "FREE"}` | 200; `coupon` is not declared, so the default model config drops it | | no body at all | 422; a model parameter without a default is required | Each error names the path of the field that failed, including fields inside nested models, so the client can tell which value to fix. The exact shape of that error body is a topic of its own. The table is the reason to validate at the edge: business code below the endpoint can trust that an `Order` has a string `sku` and an integer `quantity`, and no defensive checks are needed for shape. ## Shapes other than one object - **A nested model.** A field typed `buyer: Buyer | None = None` expects a nested JSON object under `buyer`, validated recursively, and documented as its own schema. - **A list of models.** A lone parameter `orders: list[Order]` makes the whole body a **top-level JSON array**: `[{"sku": "A"}, {"sku": "B"}]`. An object such as `{"orders": [...]}` is rejected with a 422. - **An optional body.** `order: Order | None = None` passes `None` when the request has no body and a validated `Order` when it has one. - **A plain value in the body.** A singular type like `priority: int` is not a body field unless it is marked `Annotated[int, Body()]`. ## Why not a dict or the raw request `payload: dict` is still read from the JSON body, but nothing checks its keys or types, and `/docs` shows only a generic object. Reading `await request.json()` from a `Request` parameter goes further and skips FastAPI's validation and documentation entirely. Both push shape checks into hand-written code that tends to be incomplete; the model keeps them declarative and in one place. ## Mistakes interviewers listen for - Saying the model is "just for the docs". FastAPI validates every request against it. - Expecting a bad value to arrive as `None`. Invalid input never reaches the function. - Wrapping a list body in an object key the endpoint did not declare. - Treating an unknown key as an error by default. It is silently dropped unless the model forbids extra keys. A junior answer says "JSON in, validated model instance out, 422 otherwise"; a stronger one adds the table above, the list and optional cases, and why validation at the edge simplifies the code behind it.

  • In FastAPI, why prefer an Order model parameter over `payload: dict` or reading `await request.json()` yourself?
    A `dict` parameter is still read from the JSON body, but nothing checks its keys or types, and `/docs` shows only a generic object. Reading `request.json()` from a `Request` skips FastAPI's validation and schema entirely. A model gives a 422 for bad input before your code runs, a typed object in the editor, and a documented request schema that client generators can use.
  • In FastAPI, what must a client send for a model field that is itself typed with another model?
    A nested JSON object under that field's key. For `buyer: Buyer | None = None`, the body carries `"buyer": {"email": "..."}`; FastAPI validates it recursively, documents `Buyer` as its own schema, and reports a bad nested value against its full path, `buyer` then `email`.

A model parameter is a customs form checked at the border: a parcel that does not match the form is turned back there, so nobody inside the country has to open boxes to see what is in them.

  • FastAPI passes the raw JSON dict and the model only feeds the docs
  • A value of the wrong type reaches the function as None
  • Malformed JSON surfaces as a 500 raised inside the endpoint
  • A lone list[Order] parameter expects an object with an orders key
  • Any key the model does not declare is rejected with a 422 by default
open as a page

In FastAPI, how does a separate output model keep a sign-up endpoint from returning the user's password hash?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Declare an output model without password fields, such as UserOut, as the endpoint's response_model or return type. FastAPI validates the returned data against it and sends only its declared fields, so hashed_password never reaches the JSON.

open as a page

In FastAPI, what JSON body does an endpoint expect with several body parameters, and what does Body(embed=True) change for a single one?

level: middleimportance: must knowfreq 62%

basics

~20 s

With 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.

open as a page

In FastAPI, how do response_model and a return type annotation differ, and which one wins when a path operation declares both?

level: middleimportance: must knowfreq 60%

basics

~20 s

Both declare the response model FastAPI validates, filters and documents. The return annotation also satisfies type checkers; response_model is a decorator parameter for when the function returns something else. If both are set, response_model wins; response_model=None disables it.

open as a page

In FastAPI, how do you implement a PATCH endpoint that changes only the product fields the client actually sent?

level: middleimportance: should knowfreq 52%

basics

~10 s

Declare an update model whose fields all default to None, then merge only patch.model_dump(exclude_unset=True) into the stored product. Fields the client omitted never appear in that dict, so they keep their stored values.

open as a page

In FastAPI, how do you declare a paginated list-of-users endpoint so every returned row is validated and stripped to the public fields?

level: middleimportance: should knowfreq 45%

basics

~20 s

Declare the response model as list[UserOut] or a page model with items: list[UserOut]. FastAPI validates every item, reads ORM rows by attribute, and sends only UserOut's fields; one invalid row makes the whole response a 500.

open as a page

After upgrading FastAPI to 0.143, an internal client's JSON POSTs sent without a Content-Type header now fail with 422; why did FastAPI add this check, and how do you fix it?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Since FastAPI 0.132, strict_content_type defaults to True, so a body without a Content-Type header is not parsed as JSON and fails validation with 422. It blocks header-less cross-site browser requests that skip the CORS preflight; make the client send application/json.

open as a page

A FastAPI endpoint sets response_model_exclude_unset=True, yet returning the stored user model still sends every default field; why, and how do you fix it?

level: seniorimportance: should knowfreq 25%

basics

~20 s

FastAPI rebuilds a returned object of another class into the response model by reading its attributes, so every field it finds counts as set and nothing is excluded. Return the response model itself or a subclass, or return stored.model_dump(exclude_unset=True).

open as a page

In FastAPI 0.143, when does Pydantic write a declared response model straight to JSON bytes, and why does any response_class, even an app-wide default, take a route off that path?

level: seniorimportance: should knowfreq 20%

basics

~20 s

Since 0.130, a return type or response_model with no response_class lets Pydantic's dump_json write the JSON bytes in one pass. Any explicit class, even JSONResponse or an app-wide default, makes Pydantic build Python data first for the class to render.

open as a page

As a lead, would you require every JSON endpoint in a FastAPI codebase to declare a response model, and how would you enforce it?

level: principalimportance: should knowfreq 30%

basics

~20 s

Yes, for APIs others consume: the model filters output to listed fields, documents it for generated clients and, since 0.130, is the fast JSON path. The costs are model upkeep and a 500 when a return stops fitting; a schema test enforces it.

open as a page

In FastAPI, how do you add example request bodies to /docs, and how do Body(examples=...) and Body(openapi_examples=...) differ?

level: middleimportance: nice to knowfreq 18%

basics

~20 s

Field(examples=...), json_schema_extra and Body(examples=[...]) put example lists into the JSON Schema. Body(openapi_examples={...}) adds named examples with a summary and value beside the schema, which Swagger UI shows better. FastAPI validates none of them against the model.

open as a page