skip to content

As the lead of a FastAPI payments API, would you keep FastAPI's default {"detail": ...} error bodies or replace them with a team error envelope, and what does replacing them cost?

level: principalimportance: should knowfreq 25%

answer

  1. detail changes type by error
  2. four handlers, not one
  3. the schema still says HTTPValidationError
  4. generated clients follow the schema
  5. a structured detail is a middle path

basics

~10 s

Replace them when clients need one stable shape, but budget for it: handlers for Starlette's HTTPException, RequestValidationError, ResponseValidationError and domain errors, plus declared 422 and error responses, since FastAPI's schema keeps documenting HTTPValidationError otherwise.

solid answer

~40 s

FastAPI's defaults are coherent but uneven: `detail` is a string for most `HTTPException`s, an object if you pass one, and a list for 422s, while an unhandled error is plain text. For a payments API with several client teams I would usually replace them with one envelope, carrying a stable code, a message and field errors, because clients then parse one shape. The cost is real: handlers on `starlette.exceptions.HTTPException`, `RequestValidationError`, `ResponseValidationError` and the domain base class, `exc.headers` forwarded, and declared responses such as `FastAPI(responses={422: {"model": ErrorEnvelope}})`, since overriding a handler does not change the generated schema and clients generated from it would expect `HTTPValidationError`. A cheaper middle path keeps `{"detail": ...}` and standardizes structured details. For an internal API with one consumer, the defaults are often enough.

code

python · 23 lines
python
from fastapi import FastAPI
from pydantic import BaseModel


class FieldError(BaseModel):
    loc: list[str | int]
    msg: str
    type: str


class ErrorBody(BaseModel):
    code: str
    message: str | None = None
    fields: list[FieldError] = []


class ErrorEnvelope(BaseModel):
    error: ErrorBody


app = FastAPI(
    responses={422: {"model": ErrorEnvelope, "description": "Validation failed"}}
)

go deeper

for a junior

Recall that FastAPI's errors use a detail key and that a 422 holds a list, while most other errors hold a string.

for a middle

Explain which handlers a custom envelope needs and why the Starlette HTTPException class is the one to register.

for a senior

Show what goes wrong in practice: schema drift, missing headers, gaps nobody tested, a plain-text 500 left behind.

for a principal

Weigh consumers, migration cost and the team's capacity to maintain schema and tests; pick defaults, middle path or full envelope and write the contract down.

## What the defaults give you Out of the box, a FastAPI app already has a consistent *outer* shape: almost every error is a JSON object with one key, `detail`. The *inner* shape varies by cause: | Cause | Status | Body | |---|---|---| | `HTTPException` with a string | its status | `{"detail": "Account not found"}` | | `HTTPException` with a dict | its status | `{"detail": {"code": "..."}}` | | Unknown path, wrong method | 404, 405 | `{"detail": "Not Found"}`, `{"detail": "Method Not Allowed"}` | | Invalid input | 422 | `{"detail": [{"type", "loc", "msg", "input", ...}]}` | | Response fails its model, unhandled error | 500 | plain text `Internal Server Error` | The generated OpenAPI schema documents the 422 precisely, as `HTTPValidationError` with a list of `ValidationError` items, on every operation that has parameters or a body. Swagger UI and ReDoc show it, and client generators turn it into types. For a single internal consumer that is often good enough, and it has the advantage of being what every FastAPI developer expects. ## Why a payments API often wants more The argument for a **team envelope** such as `{"error": {"code", "message", "fields"}}`: - **One parse path for clients.** With the defaults, `detail` is a string, an object or a list depending on the error, and the 500 is not JSON at all. - **Stable codes.** `INSUFFICIENT_FUNDS` or `ACCOUNT_FROZEN` let clients branch without parsing prose; FastAPI's defaults only give codes for validation errors. - **Controlled exposure.** One place decides what reaches the client, which matters when bodies and errors can contain payment data. ## What replacing it costs The decision is cheap to state and expensive to complete. A full replacement needs: 1. a handler on **`starlette.exceptions.HTTPException`**, not FastAPI's subclass, or routing 404s and 405s keep the default shape; 2. a handler on **`RequestValidationError`** that keeps `loc`, `msg` and `type` and serializes `ctx` safely; 3. a handler on **`ResponseValidationError`**, or an `Exception` handler, or the 500 stays plain text; 4. handlers on the **domain exception bases**; 5. forwarding **`exc.headers`**, so `Allow` and `WWW-Authenticate` survive; 6. **declared responses**: overriding a handler does not touch the generated schema, which keeps documenting `HTTPValidationError` for 422 until you declare your own, for example `FastAPI(responses={422: {"model": ErrorEnvelope}})` or per-router `responses`; 7. **tests** for each gap, because a later middleware or a new exception type quietly reintroduces a second shape. Item 6 is the one teams forget. Clients generated from the schema will expect `{"detail": [...]}` for a 422 the API no longer sends, and the docs will mislead every new integrator. There is also a **migration** cost if the API is already in use: existing clients parse `detail`. Changing the shape is a breaking change, so it needs a versioned rollout or a period in which clients accept both. ## The middle path A team can keep FastAPI's outer shape and standardize the inside: - raise `HTTPException(status_code=409, detail={"code": "INSUFFICIENT_FUNDS", "message": "..."})` everywhere, which the default handler already serializes; - register one handler on `starlette.exceptions.HTTPException` that wraps router strings into the same object; - leave the 422 list as it is, since its schema is already documented. A `RequestValidationError` handler could go one step further and wrap the list as `{"detail": {"code": "VALIDATION_FAILED", "fields": [...]}}`, making `detail` always an object, at the price of declaring that 422 response too. This costs less and keeps the schema honest, at the price of `detail` still being an object for most errors and a list for validation. ## How I would decide - **Who consumes the API?** Several external or mobile clients favour a full envelope; one internal frontend favours the defaults or the middle path. - **Is the API already public?** If yes, the migration plan is part of the decision. - **Can the team keep the schema in sync?** If nobody will maintain declared responses and gap tests, a half-replaced envelope is worse than the defaults: it looks consistent and is not. - **What must never leak?** For payments, the single choke point of a full envelope is a strong argument on its own. Whatever is chosen, write it down as the team's error contract, with an example body per status, and enforce it with tests rather than reviews.

  • In FastAPI, if you override the RequestValidationError handler, why does Swagger UI still show the old 422 body?
    FastAPI generates the 422 entry from the route's parameters, not from the handler: every operation with parameters or a body gets a 422 referencing `HTTPValidationError` unless a 422, `4XX` or `default` response is already declared. Declaring `responses={422: {"model": ErrorEnvelope}}` on the app or router replaces it.
  • How would you roll out a new FastAPI error envelope to clients that already parse detail?
    Treat it as a breaking change: announce it, offer the new shape on a new API version or behind an opt-in, update the declared responses and generated clients first, and keep a test suite that asserts both shapes until the old consumers have moved.

  • Assumes overriding a handler updates the OpenAPI 422 schema
  • Replaces only the HTTPException handler and calls the envelope done
  • Changes the error shape of a live API without a migration plan
  • Insists one approach is right for every API regardless of its consumers
  • Hides validation details entirely to make the envelope look uniform