Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readPython
#Python#FastAPI#Pydantic#API Design
3D illustration of a request card rejected at a validation gate with an error list panel

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:

python
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 UserOut
bash
curl -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

ExceptionRaised whenDefault statusHandler
RequestValidationErrorRequest body/query/path/header mismatch422@app.exception_handler(RequestValidationError)
pydantic.ValidationError in your codeManual Model(**data)500Catch it, or re-raise as RequestValidationError
ResponseValidationErrorReturn value ≠ response_model500Fix the handler's return type
HTTPExceptionYour own rejectionAs specified@app.exception_handler(HTTPException)
StarletteHTTPExceptionRouting, 404, 405404/405Same handler family
Pydantic versiontype value exampleExtra 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

python
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

RequestlocMeaning
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

python
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 exc

Without 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

python
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 page

A 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

python
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 missing

ResponseValidationError 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

python
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

MistakeResultCorrect approach
Catching ValidationError as RequestValidationError500 instead of 422Handler per exception type
Returning exc.errors() without jsonable_encoderSerialization error inside the handlerEncode the payload
Echoing input to the clientSecrets in logs and responsesStrip input
response_model with a missing field500 ResponseValidationErrorMatch the model or make fields optional
Assuming loc[0] is always bodyWrong field names in the clientMap by parameter source
Using HTTPException(422) for validationInconsistent error shapeOne 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 tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.