FastAPI 422: Custom Validation Errors and Response Models
Three exceptions share the 422 path and only one is handled by default. A single handler that strips input and flattens loc gives clients a contract that survives a Pydantic version change.

Introduction & Quick Summary
Symptom. A client posts to a FastAPI endpoint and gets 422 Unprocessable Entity with {"detail":[{"type":"missing","loc":["body","email"],"msg":"Field required","input":{...}}]}. Sometimes the payload looks correct and the error points at body with loc: ["body"]; sometimes the request succeeds but the response fails with ResponseValidationError and a 500; sometimes the client team asks for a stable error format and the default list changes shape between Pydantic versions.
Cause. Two different exceptions share the 422 path. RequestValidationError is raised by FastAPI before your handler runs when the body, query, path, or header does not match the declared model. pydantic.ValidationError is raised inside your code when you validate something yourself, and it is not handled as a 422 by default — it becomes a 500. A third, ResponseValidationError, fires after your handler returns, when the value does not match response_model, and that is a 500 by design.
Fix. Register an exception handler for RequestValidationError that returns a documented shape, and call jsonable_encoder on exc.errors() so non-JSON values in input do not break serialization. Validate inside services with a Pydantic model and raise the same 422 yourself, or let Depends do it.
Core Mechanics, Signatures & Reproducible Setup
FastAPI validates parameters against their type annotations and Pydantic models before calling the endpoint. On failure it raises RequestValidationError carrying errors() in Pydantic's format: a list of {type, loc, msg, input, ctx?, url?}. The default handler renders that list under detail with status 422. Because the format is Pydantic's, it changed between v1 ({"loc":…, "msg":…, "type":…} with string types) and v2 (structured type strings such as missing, string_type, greater_than, plus input and url).
Reproduce all three cases:
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class UserIn(BaseModel):
email: str
age: int = Field(ge=13)
class UserOut(BaseModel):
id: int
email: str
@app.post("/users", response_model=UserOut)
async def create(user: UserIn):
return {"id": 1, "email": user.email, "age": user.age} # age not in UserOutcurl -s -X POST localhost:8000/users -H 'content-type: application/json' -d '{"age": 20}'
# {"detail":[{"type":"missing","loc":["body","email"],"msg":"Field required","input":{"age":20}}]}
curl -s -X POST localhost:8000/users -H 'content-type: application/json' -d '{"email":"a@b.c","age":12}'
# {"detail":[{"type":"greater_than","loc":["body","age"],"msg":"Input should be greater than or equal to 13",...}]}
curl -s -X POST localhost:8000/users -H 'content-type: application/json' -d '{"email":"a@b.c","age":20}'
# 500 ResponseValidationError (extra fields are stripped, so this one passes)Key Comparison Table
| Exception | Raised when | Default status | Handler |
|---|---|---|---|
RequestValidationError | Request body/query/path/header mismatch | 422 | @app.exception_handler(RequestValidationError) |
pydantic.ValidationError in your code | Manual Model(**data) | 500 | Catch it, or re-raise as RequestValidationError |
ResponseValidationError | Return value ≠ response_model | 500 | Fix the handler's return type |
HTTPException | Your own rejection | As specified | @app.exception_handler(HTTPException) |
StarletteHTTPException | Routing, 404, 405 | 404/405 | Same handler family |
| Pydantic version | type value example | Extra keys |
|---|---|---|
| v1 | "value_error.missing" | ctx |
| v2 | "missing" | input, url |
| v2 with custom error | "value_error" | ctx: {"error": …} |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. A stable error contract
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
app = FastAPI()
def field_path(loc: tuple) -> str:
return ".".join(str(p) for p in loc if p not in ("body", "query", "path", "header"))
@app.exception_handler(RequestValidationError)
async def validation_handler(request: Request, exc: RequestValidationError):
errors = [
{
"field": field_path(e["loc"]),
"code": e["type"],
"message": e["msg"],
}
for e in exc.errors()
]
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content=jsonable_encoder({"errors": errors, "request_id": request.state.request_id}),
)Dropping the body/query prefix and the raw input gives clients a stable shape and avoids echoing a password field back in the response — the default handler includes input, which is a data leak in a login endpoint.
2. Body versus query versus path: reading loc
| Request | loc | Meaning |
|---|---|---|
| Missing JSON field | ["body", "email"] | Body key absent |
| Bad query type | ["query", "page"] | ?page=abc |
| Bad path type | ["path", "item_id"] | /items/x |
| Wrong JSON entirely | ["body"] | Body is not an object, or not JSON |
loc: ["body"] with type: "json_invalid" means the request was not valid JSON — often a missing content-type: application/json or a body sent as a form. The message is JSON decode error, and no amount of model changes will fix it.
3. Validating inside a service
from pydantic import BaseModel, ValidationError
from fastapi.exceptions import RequestValidationError
class Row(BaseModel):
amount: int
def parse_row(raw: dict) -> Row:
try:
return Row.model_validate(raw)
except ValidationError as exc:
# re-raise in the request-validation channel so clients see one format
raise RequestValidationError(exc.errors()) from excWithout the re-raise, a ValidationError from a service becomes a 500 with a traceback — correct for a bug, wrong for user input. Decide by origin: data from the request → 422; data from your own database → 500.
4. Depends that validates and returns
from fastapi import Depends, HTTPException, Query
def pagination(limit: int = Query(20, ge=1, le=100), offset: int = Query(0, ge=0)):
return {"limit": limit, "offset": offset}
@app.get("/items")
async def list_items(page: dict = Depends(pagination)):
return pageA failure inside a dependency still produces a 422 through RequestValidationError, because the parameter validation happens in the same machinery. If you raise HTTPException(422, detail=[...]) instead, the response shape is yours but it bypasses the handler — pick one path and use it consistently.
5. Response model mismatches
class UserOut(BaseModel):
id: int
email: str
model_config = {"from_attributes": True}
@app.get("/users/{uid}", response_model=UserOut)
async def get_user(uid: int):
return {"id": uid} # 500 ResponseValidationError: email missingResponseValidationError is a server bug, not a client error, so the 500 is right; the message names the field and the model. With ORM objects, from_attributes=True is what lets response_model read attributes instead of dict keys — without it the same 500 appears with Input should be a valid dictionary.
6. Documenting the 422 in OpenAPI
class ErrorItem(BaseModel):
field: str
code: str
message: str
class ErrorBody(BaseModel):
errors: list[ErrorItem]
@app.post("/users", response_model=UserOut, responses={422: {"model": ErrorBody}})
async def create(user: UserIn): ...FastAPI still generates its own 422 schema for validated endpoints unless you override it, and with a custom handler the generated schema is wrong. Declaring responses={422: …} replaces it, which is what makes a generated client match the real payload.
Common Compilation/Runtime Mistakes & Version Gotchas
| Mistake | Result | Correct approach |
|---|---|---|
Catching ValidationError as RequestValidationError | 500 instead of 422 | Handler per exception type |
Returning exc.errors() without jsonable_encoder | Serialization error inside the handler | Encode the payload |
Echoing input to the client | Secrets in logs and responses | Strip input |
response_model with a missing field | 500 ResponseValidationError | Match the model or make fields optional |
Assuming loc[0] is always body | Wrong field names in the client | Map by parameter source |
Using HTTPException(422) for validation | Inconsistent error shape | One handler for all 422s |
Version notes: Pydantic v2 changed the error structure — type is a short code (missing, int_parsing), ctx moved into the error dict, and url points at the docs for that code. Clients that parsed v1's "value_error.missing" break silently by matching nothing. FastAPI 0.100+ is built on Pydantic v2; a project that pins pydantic<2 with a current FastAPI fails at import with PydanticImportError. FastAPI 0.115 also stopped adding the body prefix in some nested-model cases, so a client that indexed loc[1] positionally should switch to joining the path as shown above.
For the surrounding work, the JSON formatter turns a 422 body into something readable before you diff two clients' expectations, the regex tool builds the pattern that strips input from logged error bodies, and the diff tool compares two OpenAPI documents when a generated client starts sending a different payload after an upgrade.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.