← Back to FastAPI, page 4

fastapi-0074 · Medium mid

How do you return RFC 9457 problem details (application/problem+json) from a FastAPI application with custom exception handlers?

RFC 9457 (which replaces RFC 7807) defines a JSON error format with type, title, status, detail and instance, served as application/problem+json, plus extension members such as errors. In FastAPI you register exception handlers for HTTPException, RequestValidationError and your own domain exceptions, and return a JSONResponse with the problem media type. Clients then parse one stable shape for all failures.

Full answer

Default FastAPI errors are inconsistent: {"detail": "text"} for HTTPException and {"detail": [ ... ]} for validation. A standard envelope simplifies clients and monitoring.

Problem object members:

  • type: a URI identifying the problem kind (stable; may link to docs). about:blank means "see the HTTP status".
  • title: short, human-readable and the same for all instances of the type.
  • status: the HTTP status code (repeated in the body).
  • detail: explanation specific to this occurrence.
  • instance: URI of this occurrence (the request path or an error ID to quote to support).
  • Extensions: errors (list of field problems), trace_id, balance, etc.

Handlers:

python
@app.exception_handler(StarletteHTTPException)
async def http_problem(request, exc): return problem(exc.status_code, detail=str(exc.detail), instance=request.url.path)

@app.exception_handler(RequestValidationError)
async def validation_problem(request, exc): return problem(422, "Validation failed", errors=jsonable_encoder(exc.errors()))

@app.exception_handler(FeeClosed)       # domain exception raised from services
async def fee_closed(request, exc): return problem(409, ...)

Register for starlette.exceptions.HTTPException (not only FastAPI's subclass) so errors from routing, such as 404 and 405, are also covered. Add a catch-all for Exception that logs and returns a generic 500 problem without internal messages. Use media_type="application/problem+json" and include Content-Language if you localise.

Also document errors in OpenAPI with responses={404: {"model": Problem, "content": {"application/problem+json": {}}}} so generated clients know the shape. Never leak stack traces, SQL or input values with secrets, and keep type URIs stable because clients switch on them.

python
from fastapi import FastAPI, HTTPException
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
from starlette.exceptions import HTTPException as StarletteHTTPException

app = FastAPI()
BASE = "https://schoolabe.example/problems/"


def problem(status, title, type_="about:blank", detail=None, instance=None, **extra):
    body = {"type": type_, "title": title, "status": status, "detail": detail, "instance": instance, **extra}
    return JSONResponse({k: v for k, v in body.items() if v is not None}, status_code=status,
                        media_type="application/problem+json")


class FeeWindowClosed(Exception):
    pass


@app.exception_handler(StarletteHTTPException)
async def http_problem(request, exc):
    return problem(exc.status_code, "HTTP error", detail=str(exc.detail), instance=request.url.path)


@app.exception_handler(RequestValidationError)
async def validation_problem(request, exc):
    errors = [{"field": ".".join(str(p) for p in e["loc"][1:]), "code": e["type"], "message": e["msg"]} for e in exc.errors()]
    return problem(422, "Validation failed", BASE + "validation", "One or more fields are invalid.", request.url.path, errors=errors)


@app.exception_handler(FeeWindowClosed)
async def closed(request, exc):
    return problem(409, "Fee window closed", BASE + "fee-window-closed", "Fees cannot be paid after 31 March.", request.url.path)


@app.exception_handler(Exception)
async def unexpected(request, exc):
    return problem(500, "Internal error", detail="Something went wrong.", instance=request.url.path)


class Payment(BaseModel):
    amount: int = Field(gt=0)


@app.post("/pay/{mode}")
def pay(mode: str, payment: Payment):
    if mode == "late":
        raise FeeWindowClosed()
    if mode == "boom":
        raise RuntimeError("secret internal detail")
    if mode == "missing":
        raise HTTPException(status_code=404, detail="No such student")
    return {"ok": True}


c = TestClient(app, raise_server_exceptions=False)
for mode, body in (("ok", {"amount": 0}), ("late", {"amount": 5}), ("missing", {"amount": 5}), ("boom", {"amount": 5})):
    r = c.post(f"/pay/{mode}", json=body)
    print(r.status_code, r.headers["content-type"], r.json())
print(c.get("/nope").json())

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 422 application/problem+json {'type': 'https://schoolabe.example/problems/validation', 'title': 'Validation failed', 'status': 422, 'detail': 'One or more fields are invalid.', 'instance': '/pay/ok', 'errors': [{'field': 'amount', 'code': 'greater_than', 'message': 'Input should be greater than 0'}]} 409 application/problem+json {'type': 'https://schoolabe.example/problems/fee-window-closed', 'title': 'Fee window closed', 'status': 409, 'detail': 'Fees cannot be paid after 31 March.', 'instance': '/pay/late'} 404 application/problem+json {'type': 'about:blank', 'title': 'HTTP error', 'status': 404, 'detail': 'No such student', 'instance': '/pay/missing'} 500 application/problem+json {'type': 'about:blank', 'title': 'Internal error', 'status': 500, 'detail': 'Something went wrong.', 'instance': '/pay/boom'} {'type': 'about:blank', 'title': 'HTTP error', 'status': 404, 'detail': 'Not Found', 'instance': '/nope'}

Key points

  • Problem details: type, title, status, detail, instance plus extensions
  • Serve with application/problem+json
  • Handle Starlette HTTPException so 404 and 405 are covered
  • Add a catch-all that hides internals
  • Document error models in OpenAPI

Common mistakes

  • Handling only FastAPI's HTTPException and missing routing errors
  • Leaking exception messages, SQL or stack traces in detail
  • Changing type URIs after clients depend on them
  • Not documenting error shapes in OpenAPI
  • Logging nothing in the catch-all handler

Follow-ups

  • How does RFC 9457 differ from RFC 7807?
  • How do you attach a trace ID to every error?
  • How would you localise titles and details?

Tips

  • List the standard members
  • Say which exception classes to handle
  • Mention the media type