skip to content

Error Handlers & 422 Bodies

HTTPException becomes a JSON error, a bad request a 422 RequestValidationError, a bad response a 500. Interviewers ask how to reshape the 422 body without hiding what the client got wrong.

on this pageshow

explore

questions

6

In FastAPI, how do you send an error such as 404 from a path operation with HTTPException, and what does the client receive?

level: juniorimportance: must knowfreq 80%

answer

  1. raise it, never return it
  2. status_code, detail, headers
  3. a JSON object with one key
  4. helpers and dependencies can raise it

basics

~10 s

Raise fastapi.HTTPException with a status_code, an optional detail and optional headers. FastAPI's default handler answers with that status, those headers and a JSON body {"detail": ...}; the rest of the path operation never runs.

solid answer

~40 s

You `raise HTTPException(status_code=404, detail="Account not found")` rather than returning it, because it is a normal Python exception. FastAPI installs a default handler that turns it into a `JSONResponse` with that status and the body `{"detail": "Account not found"}`. `detail` may be any JSON-able value, so a dict or list works too, and `headers` adds response headers such as `WWW-Authenticate` or an error code. Since it is an exception, raising it from a helper function or a dependency stops the whole request at once, which keeps lookups like `load_account()` reusable. If `detail` is omitted, the standard reason phrase is used (`"Not Found"`), and for status codes that may not carry a body (below 200, 204, 205, 304) only the status and headers are sent.

code

python · 21 lines
python
from fastapi import FastAPI, HTTPException

app = FastAPI()

ACCOUNTS = {"acc_1": {"id": "acc_1", "balance": 120}}


def load_account(account_id: str) -> dict:
    account = ACCOUNTS.get(account_id)
    if account is None:
        raise HTTPException(
            status_code=404,
            detail="Account not found",
            headers={"X-Error-Code": "ACCOUNT_NOT_FOUND"},
        )
    return account


@app.get("/accounts/{account_id}")
async def read_account(account_id: str):
    return load_account(account_id)

go deeper

for a junior

Recall the three constructor arguments, that you raise rather than return, and that the client sees {"detail": ...} with your status code.

for a middle

Explain that a default handler builds the JSON response, that detail can be any JSON-able value, and why raising from helpers and dependencies stops the request.

for a senior

Show judgment about what belongs in detail and headers: stable error codes, WWW-Authenticate or Retry-After, never internals, and real server faults left to surface as 500s.

for a principal

Weigh plain string details against a structured detail convention the whole team follows, since clients will branch on whatever shape you ship first.

## What `HTTPException` is `fastapi.HTTPException` is an ordinary Python exception class that carries the data an HTTP error needs: a **status code**, a **detail** for the body and optional **headers**. Its docstring frames it as the tool for *client* errors (a missing resource, failed authentication, invalid data), not for bugs in your own code. Because it is an exception, you **raise** it; you never return it. Returning an exception object from a path operation makes FastAPI serialize it like any other return value, as a successful 200. ```python raise HTTPException(status_code=404, detail="Account not found") ``` ## What the client receives FastAPI registers a default exception handler, `fastapi.exception_handlers.http_exception_handler`, when the app is created. It builds the response from the exception's attributes: | You raise | Status | Body | Headers | |---|---|---|---| | `HTTPException(404, detail="Account not found")` | 404 | `{"detail": "Account not found"}` | content type `application/json` | | `HTTPException(409, detail={"code": "DUPLICATE"})` | 409 | `{"detail": {"code": "DUPLICATE"}}` | as above | | `HTTPException(404)` with no detail | 404 | `{"detail": "Not Found"}` | as above | | `HTTPException(304)` | 304 | no body | only the headers you passed | Two details in that table are worth remembering: - When `detail` is left as `None`, Starlette's base class fills in the standard reason phrase for the status code, so the body is still a readable string. - For status codes that must not carry a body (anything below 200, plus 204, 205 and 304), the default handler sends a bare `Response` with the status and headers only. ## `detail` and `headers` **`detail`** accepts any value that can be converted to JSON: a string, a dict, a list. That is the one difference between FastAPI's `HTTPException` and Starlette's, whose `detail` is typed as a string. A structured detail such as `{"code": "ACCOUNT_FROZEN", "message": "..."}` lets clients branch on a stable code instead of parsing prose. **`headers`** is a mapping of header names to string values that the handler copies onto the error response. Typical uses: - `WWW-Authenticate` on a 401, which authentication schemes expect; - `Retry-After` on a 429 or 503; - an application error code such as `X-Error-Code` that a gateway or client can read without parsing the body. Headers set on an injected `Response` parameter are not part of this: they are merged into the normal response, and the error response is built fresh from the exception, so put error headers on the exception itself. ## Raising from helpers and dependencies The biggest practical benefit of raising is that the exception unwinds through every function between the `raise` and FastAPI. A helper such as `load_account(account_id)` can raise a 404 when the account does not exist, and every path operation that calls it gets the same behaviour without checking a return value. The code after the call never runs. The same holds for dependencies: a `get_current_account` dependency that raises `HTTPException(status_code=403, ...)` stops the request before the path operation body starts. This is why authentication helpers raise rather than return error values: FastAPI's own security classes build an `HTTPException` with status 401 and a `WWW-Authenticate` header when credentials are missing. ## Common mistakes 1. **Returning instead of raising.** `return HTTPException(...)` sends a 200 whose JSON body is the exception's own attributes (`status_code`, `detail`, `headers`), so the client sees success. 2. **Using it for server faults.** A failed database call is not a client error; let it propagate (or map it with a dedicated handler) so it becomes a 500 and is logged, instead of dressing it up as a 400. 3. **Putting internals in `detail`.** The detail goes straight to the client, so a stack trace, an SQL statement or another customer's balance must never be placed there. 4. **Expecting a different body key.** For any status that may carry a body, the default body is always `{"detail": ...}`; an `error` or `message` key only appears if you install your own handler. 5. **Magic numbers.** `from fastapi import status` provides named constants such as `status.HTTP_404_NOT_FOUND`, which read better in review than a bare `404` and are the same integers. ## Worked example In a payments API, a shared lookup raises the 404 with a machine-readable header, and any path operation that calls it inherits the behaviour. A request for an unknown account receives status 404, the header `X-Error-Code: ACCOUNT_NOT_FOUND` and the body `{"detail": "Account not found"}`.

  • Why does FastAPI's HTTPException accept a dict as detail when Starlette's is typed as a string?
    FastAPI's default handler puts `detail` into a `JSONResponse`, so any JSON-able value works: a dict with an error code, a list of problems. Starlette's own default handler sends `detail` as plain text, which is why its class types it as a string. Raising FastAPI's class in your code and letting FastAPI's handler answer is what makes structured details possible.
  • What does a FastAPI client receive for HTTPException(status_code=204)?
    Only the status and any headers you passed. The default handler checks whether the status code may carry a body; codes below 200 and 204, 205 and 304 may not, so it sends a bare `Response` without the `{"detail": ...}` JSON.

  • Returns the HTTPException from the path operation instead of raising it
  • Expects FastAPI's default error body to use an error or message key
  • Thinks HTTPException raised in a helper function becomes a 500
  • Uses HTTPException with a 400 to hide a database failure
  • Puts a stack trace or SQL text into detail for easier debugging
open as a page

In FastAPI 0.143, what does the default 422 validation response body contain, and which request failures produce it?

level: middleimportance: must knowfreq 62%

basics

~20 s

FastAPI 0.143 answers a RequestValidationError with 422 and {"detail": [...]}, one Pydantic 2 error per problem carrying type, loc, msg, input and sometimes ctx. Invalid path, query, header, cookie or body values and malformed JSON all produce it.

open as a page

In FastAPI, how do you turn a custom InsufficientFunds exception into a 409 JSON response, and what must the exception handler accept and return?

level: middleimportance: should knowfreq 50%

basics

~20 s

Register a function taking (request, exc) with @app.exception_handler(InsufficientFunds) and return a Response such as JSONResponse(status_code=409, content=...). FastAPI finds it by walking the raised exception's class MRO, so a handler on a base class covers subclasses.

open as a page

In FastAPI, how do you override the RequestValidationError handler to return your own error envelope without hiding what the client got wrong?

level: middleimportance: should knowfreq 55%

basics

~10 s

Register @app.exception_handler(RequestValidationError), map exc.errors() into your envelope keeping each loc, msg and type, and return a JSONResponse with 422. Never return str(exc) or echo exc.body, which carry endpoint details and possibly sensitive request data.

open as a page

A FastAPI payments API registers its error envelope with @app.exception_handler(HTTPException), yet unknown paths still return {"detail": "Not Found"} and a broken response model returns plain-text 500. Why?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Starlette's router raises Starlette's HTTPException for 404 and 405, and a handler on FastAPI's subclass never matches its parent, so FastAPI's default answers. ResponseValidationError has no default handler and falls through to Starlette's plain-text 500.

open as a page

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%

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.

open as a page