Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Models and Validation

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Models and Validation

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

Two requests reach a gate in front of the add_book function. A book with an empty title and 0 pages is stopped at the gate and gets 400; the function never runs. Matilda with 240 pages passes, is saved, and gets 201. title "", pages 0 bad book Matilda, 240 pages good book gate BookRequest add_book runs saved, 201 400, nothing saved
Check the request before it touches your code.

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])
  • Text is 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 with Annotated lets title and author share the rule.
  • pages has Field(gt=0): the number must be greater than zero.
  • examples only 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 of loc is the field name.
  • MESSAGES maps the rule's type to a sentence a client can show, falling back to Pydantic's own msg. A missing field and an empty one both read "is required".
  • setdefault keeps only the first message per field.
  • The answer is a 400 through problem(), with an extra errors key.

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

KeyMeaningValue here
titlea short summaryInvalid book
statusrepeats the HTTP status400
detailwhat went wrong, in one sentenceThe book has invalid fields
instancethe URL the problem belongs to/api/books
errorsour extra key: one message per fieldtitle, 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"}.

Two error sources lead to one shape. RequestValidationError goes through the invalid handler to a 400 Problem Detail with errors. BookNotFound, an ApiError, goes through the api_error handler to a 404 Problem Detail. Both use problem() and application/problem+json with title, status, detail and instance. RequestValidationError a rule failed BookNotFound raised by the service problem() one function application/problem+json title status (400 or 404) detail instance + errors (400 only)
Two kinds of error, one function, one shape.

The whole run

RequestStatusContent-Type
GET one book (2)200application/json
GET book 99404application/problem+json
POST Matilda201, Location /api/books/4application/json
POST the bad book400application/problem+json
PUT book 99404application/problem+json
DELETE book 3, then again204, then 404none, 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 HTTPException with a different body in every route. Clients then need a parser per error. One handler, one shape.
  • Sending a Problem Detail as application/json. The media_type is what tells a client it's a Problem Detail.
  • Showing Pydantic's raw msg to users. Map the rule type to your own words, as MESSAGES does.

Quick recap

StepCodeResult
Rules on the modelText, Field(gt=0)what counts as valid
Check at the doorbook: BookRequestbad requests never reach the function
Default answernone422, FastAPI's detail list
Our answerRequestValidationError handler400 Problem Detail with errors
Missing bookBookNotFound + ApiError handler404 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 20 of 26

Previous
FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
Next post
FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request

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.

On this page

  • A gate in front of the server
  • The rules sit on the model
  • The type hint turns the check on
  • FastAPI's own answer: 422
  • Our handler: one shape for every error
  • The bad book gets a 400
  • A Problem Detail, taken apart
  • The same shape for 404
  • The whole run
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.