← Back to FastAPI, page 1

fastapi-0006 · Easy fresher

How do you set status codes and return errors in FastAPI? Explain status_code and HTTPException.

Set the success status with the status_code argument on the route decorator, for example 201 for creation or 204 for no content. To return an error, raise HTTPException(status_code=..., detail=...); FastAPI stops the handler and sends a JSON body {"detail": ...}. Validation errors produce 422 automatically, and you can add headers to errors such as WWW-Authenticate for 401.

Full answer

Success codes

The default is 200. Change it on the decorator:

python
@app.post("/books", status_code=status.HTTP_201_CREATED)
@app.delete("/books/{id}", status_code=204)

For 204 No Content, return nothing (None); the response must not have a body. For a code that depends on logic, accept a response: Response parameter and set response.status_code, or return a JSONResponse(status_code=...).

Errors

Raise, do not return:

python
raise HTTPException(status_code=404, detail="Book not found")
  • Raising stops the function immediately, even from deep inside helper functions or dependencies.
  • The client gets {"detail": "Book not found"}. detail can be any JSON-serialisable value, such as a dict with an error code.
  • headers={"WWW-Authenticate": "Bearer"} adds headers, needed for 401 responses.

Common codes for an API:

  • 400 bad request (business rule violated), 401 not authenticated, 403 authenticated but not allowed, 404 not found, 409 conflict (duplicate or state clash), 422 validation error (automatic), 429 too many requests, 500 server error.

Use fastapi.status constants for readability. In current Starlette, 422's constant is HTTP_422_UNPROCESSABLE_CONTENT (the older HTTP_422_UNPROCESSABLE_ENTITY name is deprecated), so using the number 422 avoids churn.

Document error responses with responses={404: {"description": "Book not found"}} on the decorator so clients see them in /docs. For a consistent error format across the app, add custom exception handlers.

python
from fastapi import FastAPI, HTTPException, status
from fastapi.testclient import TestClient
from pydantic import BaseModel

app = FastAPI()
BOOKS = {1: "Wings of Fire"}


class BookIn(BaseModel):
    title: str


def get_or_404(book_id: int) -> str:
    if book_id not in BOOKS:
        raise HTTPException(status_code=404, detail={"code": "BOOK_NOT_FOUND", "id": book_id})
    return BOOKS[book_id]


@app.post("/books", status_code=status.HTTP_201_CREATED)
def create_book(book: BookIn):
    if book.title in BOOKS.values():
        raise HTTPException(status_code=409, detail="This title already exists")
    new_id = max(BOOKS) + 1
    BOOKS[new_id] = book.title
    return {"id": new_id, "title": book.title}


@app.get("/books/{book_id}", responses={404: {"description": "Book not found"}})
def read_book(book_id: int):
    return {"id": book_id, "title": get_or_404(book_id)}


@app.delete("/books/{book_id}", status_code=204)
def delete_book(book_id: int):
    get_or_404(book_id)
    del BOOKS[book_id]


c = TestClient(app)
r = c.post("/books", json={"title": "Ignited Minds"}); print(r.status_code, r.json())
r = c.post("/books", json={"title": "Ignited Minds"}); print(r.status_code, r.json())
r = c.get("/books/99"); print(r.status_code, r.json())
r = c.delete("/books/2"); print(r.status_code, repr(r.text))

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): 201 {'id': 2, 'title': 'Ignited Minds'} 409 {'detail': 'This title already exists'} 404 {'detail': {'code': 'BOOK_NOT_FOUND', 'id': 99}} 204 ''

Key points

  • status_code on the decorator sets the success code
  • Raise HTTPException for errors; it stops the handler
  • Error body is {'detail': ...}
  • 204 responses must not have a body
  • Document errors with responses= for clients

Common mistakes

  • Returning an error dict with status 200 instead of raising HTTPException
  • Returning a body from a 204 endpoint
  • Using 401 when the user is logged in but not allowed (that is 403)
  • Not documenting error responses for API clients

Follow-ups

  • How would you return the same error format for every error in the app?
  • When is 409 better than 400?
  • How do you change the status code based on logic inside the handler?

Tips

  • Say raise, not return, and explain why
  • Map common situations to codes
  • Mention documenting error responses