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?
answer
- the model is the body's contract
- parse, validate, then instantiate
- 422 before your code runs
- a list of models is a top-level array
- a None default makes the body optional
basics
~20 sFastAPI 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 sDeclaring `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 linesfrom 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
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.
Walk through the outcomes for a wrong type, a missing field, malformed JSON and an unknown key, and show list and optional bodies.
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.
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