Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
A book with an empty title and 0 pages is stopped at the door. See FastAPI's own 422 answer, then turn it into a 400 Problem Detail with field errors, and give the 404 for a missing book the same shape.
What you will learn
- Put validation rules on a Pydantic request model with StringConstraints and Field(gt=0)
- Explain how one type hint makes FastAPI check every request before your function runs
- Read FastAPI's default 422 body, then replace it with a 400 Problem Detail from an exception handler
- Answer a missing resource with the same application/problem+json shape
Before you start
- FastAPI request and response models
- HTTP status codes 400, 404 and 422
A client sends a book with no title. What should the API do? Not crash, and certainly not save an empty record. It should give a clear answer that says what's wrong. This article checks the request at the door, looks at FastAPI's own answer, and then gives every error in the Book API one standard shape, called a Problem Detail.
A gate in front of the server
Imagine a gate in front of the server. Every request has to pass it. A book with an empty title and 0 pages is stopped right there, and the function never runs. Matilda passes, gets saved, and the client gets 201.
The rules sit on the model
library/schemas.py:
from typing import Annotated
from pydantic import BaseModel, ConfigDict, Field, StringConstraints
# text that must have at least one character once the spaces around it are cut off
Text = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)]
class BookRequest(BaseModel):
"""What a client may send: no id, no shelf code, and rules the data must follow."""
title: Text = Field(examples=["Matilda"])
author: Text = Field(examples=["Roald Dahl"])
pages: int = Field(gt=0, examples=[240])
Textis a string with at least one character once the spaces around it are cut off. An empty title, or one made only of spaces, is turned away. Defining it once withAnnotatedletstitleandauthorshare the rule.pageshasField(gt=0): the number must be greater than zero.examplesonly fill in sample values in Swagger UI.
The rules sit next to the fields they check. (Why a separate request model at all is covered in request and response models.)
The type hint turns the check on
@router.post("", response_model=BookResponse, status_code=201, summary="Add a book", operation_id="create")
def add_book(book: BookRequest, response: Response, service: BookService = Depends(get_service)):
saved = service.create(models.Book(**book.model_dump()))
response.headers["Location"] = f"/api/books/{saved.id}"
return saved
book: BookRequest is the whole switch. FastAPI sees the type hint and checks every request body against the model before anything else happens. Only then does the next line run, so your code never sees a bad book. The PUT route uses the same model, so the same rules apply there.
FastAPI's own answer: 422
Without any handler, here's what FastAPI answers to the bad book:
POST http://localhost:8080/api/books
Content-Type: application/json
{"title": "", "author": "Roald Dahl", "pages": 0}
INFO: 127.0.0.1:49338 - "POST /api/books HTTP/1.1" 422 Unprocessable Content
{"detail":[{"type":"string_too_short","loc":["body","title"],"msg":"String should have at least 1 character","input":"","ctx":{"min_length":1}},{"type":"greater_than","loc":["body","pages"],"msg":"Input should be greater than 0","input":0,"ctx":{"gt":0}}]}
422 means the request was understood but the values aren't acceptable. The body is a list called detail, one entry per broken rule. Each entry has a type (the rule's code), a loc (where: the body, then the field), a msg, the input that failed, and ctx with the rule's settings. It's a clear no, but in FastAPI's own shape, and with application/json as its content type.
Our handler: one shape for every error
We want every error in our API to look the same. That's what library/errors.py does. First, the function that builds the shape:
def problem(request: Request, status: int, title: str, detail: str, **more) -> JSONResponse:
"""Problem Details (RFC 9457): one shape for every error."""
body = {"detail": detail, "instance": request.url.path, "status": status, "title": title, **more}
return JSONResponse(body, status_code=status, media_type="application/problem+json")
Then the validation handler, with a small table of client-friendly messages:
# what a failed rule says, in words a client can show
MESSAGES = {
"missing": "{field} is required",
"string_too_short": "{field} is required",
"greater_than": "{field} must be more than 0",
}
def register_handlers(app: FastAPI) -> None:
@app.exception_handler(ApiError)
async def api_error(request: Request, error: ApiError):
return problem(request, error.status, error.title, error.detail)
@app.exception_handler(RequestValidationError)
async def invalid(request: Request, error: RequestValidationError):
errors = {}
for item in error.errors():
field = item["loc"][-1] if isinstance(item["loc"][-1], str) else "body"
message = MESSAGES.get(item["type"], item["msg"]).format(field=field)
errors.setdefault(field, message) # the first message of each field
return problem(request, 400, "Invalid book", "The book has invalid fields", errors=errors)
Line by line:
@app.exception_handler(RequestValidationError)catches the error FastAPI raises when the check fails, the same one that produced the 422.error.errors()is that same list of broken rules. For each one, the last part oflocis the field name.MESSAGESmaps the rule'stypeto a sentence a client can show, falling back to Pydantic's ownmsg. A missing field and an empty one both read "is required".setdefaultkeeps only the first message per field.- The answer is a 400 through
problem(), with an extraerrorskey.
It's registered in main.py with one line after the router: register_handlers(app) # every error leaves the API as application/problem+json.
The bad book gets a 400
Same bad book, now with the handler in place. The answer: status 400, Content-Type: application/problem+json, 175 bytes:
{"detail":"The book has invalid fields","instance":"/api/books","status":400,"title":"Invalid book","errors":{"title":"title is required","pages":"pages must be more than 0"}}
400 says the request has a problem and it's the client's job to fix it. The content type application/problem+json marks it as a Problem Detail, a standard format for HTTP errors (RFC 9457).
A Problem Detail, taken apart
| Key | Meaning | Value here |
|---|---|---|
title | a short summary | Invalid book |
status | repeats the HTTP status | 400 |
detail | what went wrong, in one sentence | The book has invalid fields |
instance | the URL the problem belongs to | /api/books |
errors | our extra key: one message per field | title, pages |
The standard lets you add keys like errors. A form can put each message under its field. Because the shape is standard, any client can read it.
The same shape for 404
This isn't only for bad input. A missing book gets the same shape. In errors.py:
class ApiError(Exception):
"""An error the API answers on purpose: a status, a short title and a sentence."""
def __init__(self, status: int, title: str, detail: str):
self.status, self.title, self.detail = status, title, detail
class BookNotFound(ApiError):
def __init__(self, book_id: int):
super().__init__(404, "Book not found", f"No book with id {book_id}")
and the service raises it when the repository finds nothing:
def get(self, book_id: int) -> Book:
book = self.repository.find_by_id(book_id)
if book is None:
raise BookNotFound(book_id)
return book
The ApiError handler above turns it into a Problem Detail. GET /api/books/99 answers 404, application/problem+json:
{"detail":"No book with id 99","instance":"/api/books/99","status":404,"title":"Book not found"}
Compare the two bodies. detail, instance, status and title are in both; the 400 adds errors. A 400 says "fix the request". A 404 says "nothing lives at that address". The routes got simpler too: get_book, replace_book and delete_book no longer check for None, because the service raises and the handler answers. A second DELETE of book 3, for example, answered {"detail":"No book with id 3","instance":"/api/books/3","status":404,"title":"Book not found"}.
The whole run
| Request | Status | Content-Type |
|---|---|---|
| GET one book (2) | 200 | application/json |
| GET book 99 | 404 | application/problem+json |
| POST Matilda | 201, Location /api/books/4 | application/json |
| POST the bad book | 400 | application/problem+json |
| PUT book 99 | 404 | application/problem+json |
| DELETE book 3, then again | 204, then 404 | none, then application/problem+json |
The React course uses this same 400 shape to show errors under form fields: see the Book API contract for a React client and React Hook Form with server errors.
Common mistakes
- Checking fields by hand inside the route. Put the rules on the model; the type hint runs them before your code.
- Raising
HTTPExceptionwith a different body in every route. Clients then need a parser per error. One handler, one shape. - Sending a Problem Detail as
application/json. Themedia_typeis what tells a client it's a Problem Detail. - Showing Pydantic's raw
msgto users. Map the ruletypeto your own words, asMESSAGESdoes.
Quick recap
| Step | Code | Result |
|---|---|---|
| Rules on the model | Text, Field(gt=0) | what counts as valid |
| Check at the door | book: BookRequest | bad requests never reach the function |
| Default answer | none | 422, FastAPI's detail list |
| Our answer | RequestValidationError handler | 400 Problem Detail with errors |
| Missing book | BookNotFound + ApiError handler | 404 Problem Detail |
Fail early, and say clearly why.
Try it yourself
Send a book with "title": " " (only spaces) and one with no author key at all. Before you look, predict the errors map for each.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
Stop sending your database rows to clients. A BookRequest model decides what may come in, a BookResponse model decides what goes out, and an internal shelf_code stays in the database.
FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
One small posts app shows the three places data travels in a request. post_id comes from the path, q and limit from the query string, and a PostIn body is checked by Pydantic. You'll read every 422, cut the output with response_model and count Depends calls.
