skip to content

HTTP Inputs & Outputs

Forms and uploads come in through Form() and UploadFile, responses go out as Response classes, and exceptions become error bodies. Interviewers ask what returning a Response directly skips.

on this pageshow

explore

questions

16

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, when should an uploaded file parameter be bytes and when UploadFile, and what does each hold in memory?

level: middleimportance: must knowfreq 45%

basics

~20 s

Annotated[bytes, File()] hands the endpoint the whole file in memory, which suits small uploads. UploadFile wraps a spooled temporary file that moves to disk past about 1 MB, exposes filename and content_type, and suits large or streamed files.

open as a page

In FastAPI 0.143, what does a path operation give up when it returns a JSONResponse directly instead of plain data?

level: middleimportance: must knowfreq 45%

basics

~20 s

A returned JSONResponse is sent as is: no response_model validation or filtering, no conversion of datetimes or models, no headers or status from a Response parameter, no Pydantic JSON fast path, and docs that may not match the body.

open as a page

In FastAPI, how do you declare form fields with Form(), and what goes wrong when you omit Form() or python-multipart?

level: juniorimportance: should knowfreq 40%

basics

~10 s

Declare each field as Annotated[str, Form()] and install python-multipart. Without Form() a str parameter becomes a query parameter, and without python-multipart FastAPI raises a RuntimeError as soon as the route is declared.

open as a page

In FastAPI, how do you return an HTML page or a CSV file instead of JSON, and what does response_class change?

level: juniorimportance: should knowfreq 38%

basics

~20 s

Pass response_class=HTMLResponse (or PlainTextResponse) to the path operation decorator and return a string, or return a FileResponse for a file. response_class sets the response's class, its Content-Type and the media type FastAPI documents in OpenAPI.

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

In FastAPI, how do you bind a whole HTML form to a Pydantic model, and what changes when that model forbids extra fields?

level: middleimportance: should knowfreq 25%

basics

~20 s

Declare the parameter as Annotated[MyForm, Form()] and FastAPI fills each model field from the form data. With model_config = {"extra": "forbid"}, any undeclared form key is rejected with a 422 extra_forbidden error instead of being ignored.

open as a page

In a FastAPI multipart upload endpoint, why does a plain Pydantic model parameter fail to read JSON metadata, and what works instead?

level: middleimportance: should knowfreq 25%

basics

~20 s

A multipart request has no separate JSON body, so FastAPI treats the model as one more form part, receives a string and answers 422. Send the metadata as a form field declared Annotated[Json[Model], Form()], parse it yourself, or use flat form fields.

open as a page

In a FastAPI create endpoint answering 201 with a Location header, how do you set status, headers and cookies yet keep response_model filtering?

level: middleimportance: should knowfreq 40%

basics

~10 s

Put status_code=status.HTTP_201_CREATED on the decorator, declare a parameter typed Response, set response.headers["Location"] or call response.set_cookie on it, and return plain data. FastAPI copies the status, headers and cookies into the filtered response.

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

A FastAPI bulk CSV import endpoint takes an UploadFile; what limits the upload's size by default, and how would you cap it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Nothing caps a file's size by default: Starlette's parser limits only counts (1000 files, 1000 fields) and non-file parts (1 MB), answering 400. Cap uploads at the reverse proxy and with Starlette's RequestBodyLimitMiddleware, which answers 413.

open as a page

After a FastAPI login form POST returns RedirectResponse("/dashboard"), the browser re-sends the POST and gets 405. Why, and how do you fix it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

FastAPI's RedirectResponse defaults to 307, which tells the browser to repeat the same method and body, so it POSTs to a GET-only /dashboard and gets 405. Pass status_code=status.HTTP_303_SEE_OTHER so the browser follows with a GET.

open as a page

In FastAPI 0.143, why are ORJSONResponse and UJSONResponse deprecated, and what should a team using default_response_class=ORJSONResponse do instead?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Since FastAPI 0.130 a declared return type or response_model makes Pydantic serialize straight to JSON bytes, which is faster than an orjson response class. So 0.131 deprecated both classes; remove default_response_class and declare return types instead.

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