Declare endpoint response status
A route declaration needs an explicit response code without embedding a magic number.
FastAPI · Module
FastAPI's status module provides named integer constants for HTTP and WebSocket status codes. Import it from fastapi to use readable values such as status.HTTP_200_OK in application code.
The module exposes named integer constants for HTTP and WebSocket status codes. Import it from fastapi and use a descriptive constant, such as status.HTTP_200_OK, wherever a status-code value is needed.
from fastapi import statusThe module provides named integer status-code constants.
from fastapi import FastAPI, status
app = FastAPI()
@app.get("/items/", status_code=status.HTTP_200_OK)
def read_items():
return [{"name": "Plumbus"}]
This runnable FastAPI app uses a named HTTP status constant in the route declaration.
A route declaration needs an explicit response code without embedding a magic number.
Application logic must compare or return an HTTP status value using a descriptive identifier.
An editor's completion support can replace memorizing numeric HTTP or WebSocket codes.
Import status from fastapi and select a named constant such as status.HTTP_200_OK. These constants represent integer HTTP or WebSocket status codes while making code completion and readability better than raw numbers.
Follow-up: Why use named constants instead of literals? Named constants communicate intent and reduce the need to memorize numeric codes.
Set a route's status_code argument to a status constant, for example status.HTTP_418_IM_A_TEAPOT. FastAPI then uses that value as the operation's configured response status code.
Follow-up: Can the same constants be used outside decorators? Yes; they are integer values and can be passed anywhere an HTTP status code is accepted.
The module contains named integer constants for both HTTP and WebSocket status codes. Examples include HTTP_200_OK and HTTP_403_FORBIDDEN.
Follow-up: Where does this module originate? The documentation states that status is provided directly by Starlette.
FastAPIResponse Status CodeHTTP_100_CONTINUEHTTP_200_OKHTTP_403_FORBIDDENHTTP_418_IM_A_TEAPOT