In FastAPI 0.143, what does the default 422 validation response body contain, and which request failures produce it?
answer
- one list under one key
- every problem at once
- type, loc, msg, input, ctx
- loc starts with the parameter source
- malformed JSON is json_invalid
basics
~20 sFastAPI 0.143 answers a RequestValidationError with 422 and {"detail": [...]}, one Pydantic 2 error per problem carrying type, loc, msg, input and sometimes ctx. Invalid path, query, header, cookie or body values and malformed JSON all produce it.
solid answer
~40 sWhen any parameter fails validation, FastAPI 0.143 collects every error from every source, raises `RequestValidationError` and its default handler returns status 422 with `{"detail": [...]}`. Each item is a Pydantic 2 error dict: `type` is a stable machine code such as `int_parsing` or `missing`, `loc` is the path to the bad value starting with its source (`"path"`, `"query"`, `"header"`, `"cookie"` or `"body"`), `msg` is the human message, `input` is what was received and `ctx` holds constraint values such as `{"gt": 0}`. A body that is not valid JSON also lands here, as `json_invalid` with `loc` `["body", <character offset>]`. Other failures while reading the body give 400 `"There was an error parsing the body"`, and an invalid response is a 500, not a 422.
code
python · 16 linesfrom typing import Annotated
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class TransferIn(BaseModel):
amount: Annotated[int, Field(gt=0)]
currency: str
@app.post("/accounts/{account_id}/transfers")
async def create_transfer(account_id: int, transfer: TransferIn):
return {"status": "accepted"}go deeper
Recall that bad input gives 422 with a detail list, and that each item says where (loc), what (msg) and why (type).
Explain that errors from all sources are collected together, how loc encodes the source and nesting, and how malformed JSON becomes json_invalid.
Know the edges: invalid UTF-8 gives a 400, a broken form gives Starlette's 400, a bad response gives a 500, and clients should key on type, not msg.
Treat the 422 item format as a public contract: decide whether clients may depend on type codes and loc paths, and plan for Pydantic upgrades changing messages.
## Where the 422 comes from FastAPI reads a path operation's signature and validates every declared input before the function runs: **path**, **query**, **header** and **cookie** parameters, the **body**, and the same inputs of every dependency. It does not stop at the first failure. It gathers all errors into one list, raises `fastapi.exceptions.RequestValidationError` and lets the default handler, `request_validation_exception_handler` in `fastapi.exception_handlers`, answer: ```python JSONResponse(status_code=422, content={"detail": jsonable_encoder(exc.errors())}) ``` So the client always receives status **422 Unprocessable Content** and a JSON object with a single key, `detail`, whose value is a **list**. That list type is the first thing to notice: an `HTTPException` usually puts a string there, while a validation failure always puts a list there. ## The shape of one error Each list item is an error dictionary in **Pydantic 2's** format, the only one FastAPI 0.143 produces: | Key | Meaning | Example | |---|---|---| | `type` | stable machine-readable error code | `int_parsing`, `missing`, `greater_than` | | `loc` | path to the failing value, source first | `["body", "amount"]` | | `msg` | human-readable message | `"Input should be greater than 0"` | | `input` | the value that failed | `-5` | | `ctx` | constraint parameters, present only for some types | `{"gt": 0}` | Some points that follow from this format: - **`type` is what clients should branch on.** Messages are prose and can change wording; codes such as `missing` are the contract. - **`input` for a `missing` field is the enclosing object**, because the field itself has no value; for `amount` missing from `{"currency": "EUR"}` the input is that whole object. - **Pydantic can attach a documentation `url` to errors**, but FastAPI asks Pydantic for errors without it, so the 422 items carry no `url` key. - **The same shape is documented in the OpenAPI schema** as `HTTPValidationError`, a `detail` list of `ValidationError` items in which `loc`, `msg` and `type` are required and `input` and `ctx` optional. - **The default handler passes the errors through `jsonable_encoder`**, so values that are not JSON-native (for example the exception object a custom validator raised, which Pydantic keeps in `ctx`) are converted before serialization. ## How `loc` tells the client where to look The first element of `loc` is the **parameter source**, and the rest is the path inside it: 1. `["path", "account_id"]`: the path parameter `account_id` was not an integer. 2. `["query", "limit"]`: a query parameter failed a constraint. 3. `["header", "x-request-id"]` or `["cookie", "session"]`: header or cookie values. 4. `["body", "amount"]`: a field of the request body model; nested fields add more names, and list positions appear as integers, as in `["body", "items", 2, "price"]`. With a single body parameter, the model's fields sit right after `"body"`. With several body parameters, or with `Body(embed=True)`, the parameter's own name is inserted first, as in `["body", "transfer", "amount"]`. ## Malformed JSON A request body sent as `application/json` that cannot be decoded never reaches the model. FastAPI catches the decoder's error and raises `RequestValidationError` with one synthetic item: `type` `json_invalid`, `msg` `"JSON decode error"`, `loc` `["body", <character offset>]`, an empty `input` and `ctx.error` holding the decoder's message. The status is still 422, so a client that already handles validation errors handles broken JSON too. ## What is not a 422 - **`HTTPException`** raised by your code keeps its own status and `{"detail": ...}` body. - **Other failures while reading the body**, such as bytes that are not valid UTF-8, end as **400** with `{"detail": "There was an error parsing the body"}`. - **A broken form submission** is rejected by Starlette's form parser as a 400 `HTTPException` with the parser's message. - **An invalid response** (the return value fails `response_model`) raises `ResponseValidationError`, which FastAPI treats as a server bug: the client gets a **500**. ## Reading older material Tutorials written for Pydantic 1 show items like `"msg": "value is not a valid integer", "type": "type_error.integer"` with no `input`. FastAPI dropped `pydantic.v1` support in 0.128, so a 0.143 app never emits that shape; even the error-handling tutorial page still shows the old JSON in one of its examples. Clients and tests written against the old codes need updating.
- In FastAPI, if both a path parameter and the body are invalid, does the client see one error or both?Both. FastAPI validates every parameter source and the body before raising, collects all errors in one list and sends them in a single 422. That lets a client fix everything in one round trip instead of discovering problems one at a time.
- Why should a client branch on type rather than msg in a FastAPI 422 item?`type` is Pydantic's stable error code, such as `missing` or `greater_than`, while `msg` is English prose meant for people. Messages can be reworded between releases or replaced by a custom handler; the code and `loc` are what identify the problem reliably.
- Expects the 422 to report only the first invalid field
- Believes malformed JSON returns a 400 rather than a 422
- Thinks loc holds only the field name, without the source
- Expects detail to be a string, as with HTTPException
- Quotes type_error.integer as the current error type
- Thinks a response_model mismatch is reported to the client as a 422
Assumes FastAPI 0.143 with Pydantic 2; Pydantic 1-era material shows type codes like type_error.integer and no input key, a shape FastAPI cannot produce since dropping pydantic.v1 in 0.128.