In FastAPI, how do you send an error such as 404 from a path operation with HTTPException, and what does the client receive?
answer
- raise it, never return it
- status_code, detail, headers
- a JSON object with one key
- helpers and dependencies can raise it
basics
~10 sRaise 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 sYou `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 linesfrom 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
Recall the three constructor arguments, that you raise rather than return, and that the client sees {"detail": ...} with your status code.
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.
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.
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