Skip to content

Lesson 27 of 59API design in depth

Error Responses Clients Can Rely On

Replace FastAPI's mixed error shapes with RFC 9457 Problem Details: one model, one handler set, precise status codes, no leaked internals.

21 min read0/5 questions

The mobile team files a ticket: "Please document your errors." They have written three parsers for your API. A 404 comes back as {"detail": "Order not found"}. A validation failure comes back as {"detail": [ ... ]}, a list instead of a string under the same key. A crash comes back as the plain text Internal Server Error, which is not JSON at all, so their JSON parser throws inside the error handler and the app shows a blank screen. In Errors and Middleware you learned to raise domain exceptions and translate them in one handler. This lesson picks the format those handlers produce, RFC 9457 Problem Details, and wires it through every path an error can take in FastAPI.

Three shapes from one API

Here is what a stock FastAPI app sends for three different failures:

HTTP/1.1 404 Not Found
content-type: application/json
 
{"detail": "Order not found"}
HTTP/1.1 422 Unprocessable Content
content-type: application/json
 
{"detail": [{"type": "int_parsing", "loc": ["body", "items", 0, "qty"],
             "msg": "Input should be a valid integer", "input": "two"}]}
HTTP/1.1 500 Internal Server Error
content-type: text/plain; charset=utf-8
 
Internal Server Error

Each one is reasonable alone. Together they force every client to inspect the status, then guess the body type, then guess the shape of detail. Worse, nothing in any of them is stable enough to branch on. A client that wants to show "only 2 left in stock" has to match on the English text of a message you might reword next week. The validation shape also echoes input back, which is a problem when the field was a password or a card number.

RFC 9457 in one screen

RFC 9457 (July 2023) defines a standard JSON error body and replaces RFC 7807, which said the same thing with a few gaps. The media type is application/problem+json. A problem document has five standard members, all optional:

MemberMeaningWho reads it
typeA URI identifying the kind of problem. Defaults to about:blankClient code: this is what you switch on
titleA short summary of the kind, the same for every occurrenceHumans, logs
statusThe HTTP status code, copied into the bodyClients that lose the header (queues, logs)
detailAn explanation of this occurrenceHumans; never parse it
instanceA URI reference for this occurrenceSupport tickets, log lookups

Anything else is an extension member: errors for field problems, trace_id for support, available for the stock count. Clients must ignore extensions they do not understand, so you can add context without a new format.

The rule that makes it work: the type is a stable identifier, versioned like a field name. https://api.example.com/problems/insufficient-stock means the same thing for as long as the API lives, and ideally it resolves to a page explaining the problem and what to do. The RFC tells clients to use type as the primary identifier. title and detail are prose and can change. When there is nothing more specific to say than the status code, use about:blank, and then title should be the standard status phrase, such as Not Found.

409 Conflict, content-type: application/problem+json
{
  "type": "https://api.example.com/problems/insufficient-stock",
  "title": "Not enough stock",
  "status": 409,
  "detail": "Only 2 units of MUG-01 are available.",
  "instance": "/v2/orders",
  "sku": "MUG-01",
  "available": 2
}

For validation, the RFC's own example uses an errors extension: a list of objects each with a detail and a pointer, a JSON Pointer (RFC 6901) written as a URI fragment, such as #/items/0/qty. Follow that convention and every client knows which form field to highlight.

Quick check
A client wants to show a special screen when an account is frozen. Which member should its code check?
Need a nudge? A hint rules out a wrong answer.

The model and the exception hierarchy

Start with a Pydantic model for the document and a helper that builds responses with the right media type:

app/api/problems.py
from typing import Any
 
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict
 
PROBLEM_JSON = "application/problem+json"
PROBLEM_BASE = "https://api.example.com/problems/"
 
 
class FieldError(BaseModel):
    detail: str
    pointer: str | None = None    # body fields, "#/items/0/qty"
    parameter: str | None = None  # query, path or header parameters, "limit"
 
 
class ProblemDetail(BaseModel):
    model_config = ConfigDict(extra="allow")  # extension members
 
    type: str = "about:blank"
    title: str
    status: int
    detail: str | None = None
    instance: str | None = None
 
 
def problem(status: int, title: str, type_: str = "about:blank", headers: dict | None = None, **extra: Any) -> JSONResponse:
    body = ProblemDetail(type=type_, title=title, status=status, **extra)
    return JSONResponse(
        body.model_dump(mode="json", exclude_none=True),
        status_code=status,
        media_type=PROBLEM_JSON,
        headers=headers,
    )

Then make the domain exceptions from Errors and Middleware carry what a problem needs. Each subclass fixes its own status, type and title, so a service only supplies the occurrence-specific detail:

app/errors.py
class AppError(Exception):
    status = 400
    slug = "bad-request"
    title = "Bad request"
 
    def __init__(self, detail: str, **extra):
        super().__init__(detail)
        self.detail = detail
        self.extra = extra  # becomes extension members
 
 
class NotFound(AppError):
    status, slug, title = 404, "not-found", "Resource not found"
 
 
class PermissionDenied(AppError):
    status, slug, title = 403, "permission-denied", "Not allowed"
 
 
class Conflict(AppError):
    status, slug, title = 409, "conflict", "Conflicts with current state"
 
 
class InsufficientStock(Conflict):
    slug, title = "insufficient-stock", "Not enough stock"
app/api/handlers.py
from fastapi import FastAPI, Request
 
from app.api.problems import PROBLEM_BASE, problem
from app.errors import AppError
 
 
def install_handlers(app: FastAPI) -> None:
    @app.exception_handler(AppError)
    async def app_error(request: Request, exc: AppError):
        return problem(
            exc.status, exc.title, PROBLEM_BASE + exc.slug,
            detail=exc.detail, instance=request.url.path, **exc.extra,
        )

A service now raises InsufficientStock("Only 2 units of MUG-01 are available.", sku="MUG-01", available=2) and the client gets the document above. The service never imports anything from FastAPI. install_handlers is a function so you can call it on every app, including mounted sub-apps, which do not inherit their parent's handlers (Evolving an API Without Breaking Clients shows why that matters).

Reshaping validation errors

FastAPI raises RequestValidationError before your route runs. Override its handler to turn Pydantic's error list into problem errors. Each Pydantic error has a loc tuple whose first item says where the value came from (body, query, path, header, cookie), followed by the path inside it.

Pythonpointers.py
def to_pointer(loc: tuple) -> str: """Turn a Pydantic error location into a JSON Pointer fragment (RFC 6901).""" parts = [str(p).replace("~", "~0").replace("/", "~1") for p in loc] return "#/" + "/".join(parts) if parts else "#" def to_problem_errors(errors: list[dict]) -> list[dict]: out = [] for e in errors: source, *path = e["loc"] item = {"detail": e["msg"]} if source == "body": item["pointer"] = to_pointer(tuple(path)) else: # query, path, header or cookie item["parameter"] = str(path[0]) if path else source out.append(item) # note: e["input"] is deliberately dropped return out # What FastAPI's RequestValidationError.errors() looks likeerrors = [ {"type": "int_parsing", "loc": ("body", "items", 0, "qty"), "msg": "Input should be a valid integer", "input": "two"}, {"type": "missing", "loc": ("body", "items", 1, "sku"), "msg": "Field required", "input": {"qty": 1}}, {"type": "less_than_equal", "loc": ("query", "limit"), "msg": "Input should be less than or equal to 200", "input": "500"}, {"type": "string_too_short", "loc": ("body", "metadata", "a/b"), "msg": "String should have at least 1 character", "input": ""},]for item in to_problem_errors(errors): print(item)
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

Using to_pointer from above, what does this print?

print(to_pointer(("tags", "x~y")))
Need a nudge? Hints walk you through it.

The handler itself is short:

app/api/handlers.py
from fastapi.exceptions import RequestValidationError
 
    @app.exception_handler(RequestValidationError)
    async def validation_error(request: Request, exc: RequestValidationError):
        return problem(
            422, "Validation failed", PROBLEM_BASE + "validation",
            detail="One or more fields are invalid.",
            errors=to_problem_errors(exc.errors()),
        )

Two details you only find by testing. First, dropping input is a security fix, not tidiness: the default handler sends back whatever the client sent, including passwords, into logs and error trackers. Second, input is not always JSON-safe. A body that FastAPI could not parse arrives as raw bytes, and a handler that puts it straight into JSONResponse crashes with a TypeError inside your error handler. The default handler runs jsonable_encoder for this reason. Not echoing input avoids the problem entirely.

Router errors and the catch-all

Your AppError handler does not see every error. When no route matches, Starlette's router raises Starlette's HTTPException (404 or 405) before FastAPI is involved. FastAPI's own HTTPException is a subclass of it, so register the handler on the Starlette class and you cover both:

app/api/handlers.py
from starlette.exceptions import HTTPException as StarletteHTTPException
 
    @app.exception_handler(StarletteHTTPException)
    async def http_error(request: Request, exc: StarletteHTTPException):
        return problem(exc.status_code, str(exc.detail), headers=exc.headers)

Pass exc.headers through. A 405 from the router carries an Allow header, a 401 needs WWW-Authenticate, and a handler that drops them breaks clients that follow the spec.

Last, the catch-all for bugs. An @app.exception_handler(Exception) handler is special in Starlette: it is installed in ServerErrorMiddleware, the outermost layer of the onion you saw in Errors and Middleware. It runs outside your own middleware, so headers your request-id middleware adds on the way out are not on this response. Read the id from a ContextVar set early in the request, or generate one here:

app/api/handlers.py
import logging
 
log = logging.getLogger("api")
 
    @app.exception_handler(Exception)
    async def unhandled(request: Request, exc: Exception):
        trace_id = current_request_id() or uuid.uuid4().hex
        log.exception("unhandled error", extra={"trace_id": trace_id, "path": request.url.path})
        return problem(500, "Internal Server Error", trace_id=trace_id)

The response says nothing about what broke: no exception class, no SQL, no file paths, no stack. The log line has all of it, keyed by the trace_id the user can read out to support. Uvicorn still logs the traceback too, and in tests TestClient re-raises the exception unless you pass raise_server_exceptions=False, which you want in the test that checks this handler.

Which handler answers which error
  1. ServerErrorMiddlewareException handler: bugs become a generic 500 problem
  2. Your middlewarerequest id, timing, CORS
  3. ExceptionMiddlewarehandlers for StarletteHTTPException, AppError, RequestValidationError
  4. Routerno match raises 404 or 405
  5. Route and dependenciesvalidation, then your code

A body fails validation, or a service raises InsufficientStock. ExceptionMiddleware finds the handler by class and returns a problem. Your middleware still adds its headers on the way out.

1/3

Choosing the status code precisely

The type carries the detail, but the status code is still what proxies, retries, dashboards and alerting read. The cases teams argue about:

  • 400 vs 422. FastAPI uses 422 for any request that fails validation, including invalid JSON. Keep that, and use 400 for requests that parse but make no sense together in ways a schema cannot express, or follow your style guide if it picks one for everything. Consistency matters more than the choice.
  • 401 vs 403. 401 means "who are you?": missing or invalid credentials, and it must include WWW-Authenticate. 403 means "I know who you are, and no".
  • 404 to hide existence. If a user may not even know order ord_42 exists, return 404, not 403. A 403 confirms the id is real, which helps anyone enumerating ids.
  • 409 vs 412. 409 is a conflict with current state (duplicate email, not enough stock). 412 is a failed If-Match precondition.
  • 415. The right code for a body in a media type you do not accept. FastAPI does not send it for you: since 0.132 it refuses to parse a body as JSON unless the Content-Type is JSON, and the result is a 422 saying the body is not a valid object. Old curl examples without -H "Content-Type: application/json" now fail this way. If you want 415, check the header in a dependency.
  • 429 with a Retry-After header, so well-behaved clients know how long to wait.
  • 500 vs 502, 503, 504. 500 is your bug. 502 means an upstream you called returned garbage, 503 means you are deliberately refusing (overload, maintenance, add Retry-After), and 504 means an upstream timed out. The distinction tells the on-call engineer where to look, and tells clients which errors are worth retrying.
Match the pairs0/5 matched

Match each situation to the status code the API should return.

Choose an item, then its match on the other side.

Documenting problems in OpenAPI

Overriding a handler does not change the docs. FastAPI still advertises its default HTTPValidationError schema for 422 and nothing for your 404s and 409s, so generated clients have no type for the error body. Declare them on the route, or once on the router:

app/api/v2/orders.py
PROBLEM_SCHEMA = {"schema": {"$ref": "#/components/schemas/ProblemDetail"}}
PROBLEM_RESPONSES = {
    code: {"model": ProblemDetail, "content": {PROBLEM_JSON: PROBLEM_SCHEMA}}
    for code in (404, 409, 422)
}
 
router = APIRouter(prefix="/v2", responses=PROBLEM_RESPONSES)

model registers the schema under components and replaces the default 422 entry. FastAPI files it under the route's normal media type, application/json, so the content entry adds application/problem+json pointing at the same schema. Generated TypeScript and Python clients then know that a 409 body has type, title and status.

Consuming problems on the client

A good client switches on type, falls back to status, and survives responses that are not problems at all: a load balancer's HTML 502 page will never be application/problem+json.

JavaScriptclient.js
const PROBLEMS = "https://api.example.com/problems/"; function toProblem(status, contentType, bodyText) { if (contentType.startsWith("application/problem+json")) { const p = JSON.parse(bodyText); return { ...p, type: p.type ?? "about:blank", status: p.status ?? status }; } // Not a problem document: a proxy page, a plain-text 500, an old endpoint return { type: "about:blank", status, title: `HTTP ${status}` };} function userMessage(problem) { switch (problem.type) { case PROBLEMS + "insufficient-stock": return `Only ${problem.available} left in stock.`; case PROBLEMS + "validation": return problem.errors.map((e) => `${e.pointer ?? e.parameter}: ${e.detail}`).join("; "); default: if (problem.status === 429) return "Too many requests. Try again shortly."; if (problem.status >= 500) return `Something went wrong (ref ${problem.trace_id ?? "none"}).`; return problem.title; }} const responses = [ [409, "application/problem+json", JSON.stringify({ type: PROBLEMS + "insufficient-stock", title: "Not enough stock", status: 409, available: 2 })], [422, "application/problem+json", JSON.stringify({ type: PROBLEMS + "validation", title: "Validation failed", status: 422, errors: [{ pointer: "#/items/0/qty", detail: "Input should be a valid integer" }] })], [500, "application/problem+json", JSON.stringify({ title: "Internal Server Error", status: 500, trace_id: "7f3a" })], [502, "text/html", "<html>Bad Gateway</html>"],];for (const [status, ct, body] of responses) { console.log(status, "->", userMessage(toProblem(status, ct, body)));}
Output
Press Run (⌘ Enter) to see what happens.
Put it in order5 steps

A route raises InsufficientStock. Order what happens until the client shows a message.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Your app has handlers for AppError and RequestValidationError only. A client calls PATCH /v2/orders on a path that only supports GET and POST. What does it receive?
Need a nudge? A hint rules out a wrong answer.
Key terms
Problem Details
RFC 9457's standard JSON error body, served as application/problem+json. It replaced RFC 7807.
problem type
The type URI that identifies a kind of problem. It is stable, documented, and what client code branches on.
about:blank
The default type, meaning the problem has no meaning beyond its HTTP status code.
extension member
Any extra field in a problem document, such as errors, trace_id or available.
JSON Pointer
RFC 6901 syntax for a location in a JSON document, such as #/items/0/qty, with ~0 and ~1 escapes.
trace id
An id returned in a 500 response and written to the server log, so support can find the stack trace.