6. Status Codes & HTTP Semantics

Why 200 Is Not Always Correct

Returning HTTP 200 for every successful request obscures the true outcome of an operation. HTTP status codes communicate intent and result semantics to clients, intermediaries, and monitoring systems. Using precise status codes improves clarity, debuggability, and protocol-level correctness.


Understanding 201, 204, 400, 404, and 422

Status code 201 indicates successful resource creation, while 204 signals a successful operation with no response body. Codes such as 400 and 404 represent client-side errors related to invalid input or missing resources, whereas 422 is used by FastAPI to indicate semantic validation failures. Correct usage enables clients to react appropriately without inspecting response bodies.

from fastapi import FastAPI, status

app = FastAPI()

@app.post("/items", status_code=status.HTTP_201_CREATED)
def create_item(item: dict):
    return item

Aligning Responses with Intent

Each endpoint should return a status code that accurately reflects its purpose and outcome. Read operations, creations, updates, and deletions each carry distinct semantic meaning at the HTTP level. Aligning responses with intent ensures APIs behave predictably across different clients and tools.


Error Signaling vs Exception Throwing

FastAPI encourages explicit error signaling through HTTP responses rather than unhandled exceptions. Controlled error responses provide consistent structure and meaning, while exceptions are reserved for truly unexpected failures. This separation improves reliability and makes error handling easier for both servers and clients.

Last updated