You set the default with the status_code parameter on the decorator, and you change it per request through a Response parameter.
from fastapi import FastAPI, status, Response
app = FastAPI()
@app.post("/items/", status_code=status.HTTP_201_CREATED)
def create_item():
return {"message": "Item created"}
@app.get("/items/{item_id}")
def get_item(item_id: int, response: Response):
if item_id == 404:
response.status_code = status.HTTP_404_NOT_FOUND
return {"error": "Item not found"}
return {"item_id": item_id}
The status_code on the decorator is what FastAPI returns when the function succeeds, and it also documents that code in the OpenAPI schema. The status module holds named constants such as status.HTTP_201_CREATED. They are the same numbers, but the names read better and your editor can complete them.
Declaring a Response parameter gives you a temporary response object. Set its status_code and FastAPI copies that code into the real response, while the returned data still goes through any response_model.
For errors, raising HTTPException with a status_code and a detail is the more common pattern, because it stops the function at once.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓