In FastAPI route functions, the status_code parameter is used to specify the HTTP status code to be returned in the response. This parameter allows you to customize the status code returned by your API endpoints based on the outcome of the request processing.
Here's how the
status_code parameter
is used in FastAPI route functions :
* Default Status Code : By default, FastAPI route functions return a status code of
200 OK
for successful responses.
* Customizing Status Code : You can specify a different status code using the
status_code
parameter in the route function decorator.
from fastapi import FastAPI, status
app = FastAPI()
@app.get("/items/", status_code=status.HTTP_201_CREATED)
def create_item():
# Logic to create an item
return {"message": "Item created successfully"}?
In this example, the
/items/
endpoint returns a status code of
201 Created
instead of the default
200 OK
.
* Error Handling : You can use the
status_code
parameter to specify the appropriate HTTP status code for error responses, such as
404 Not Found
,
400 Bad Request
, or
500 Internal Server Error
.
from fastapi import FastAPI, HTTPException, status
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
# Logic to retrieve item from database
item = ...
if not item:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found")
return item?
In this example, if the requested item is not found, the route function raises an
HTTPException
with a status code of
404 Not Found
.
* Semantic Meaning : Specifying the appropriate status code enhances the semantic meaning of your API endpoints and communicates the outcome of the request to the client in a standardized way.
Using the
status_code
parameter in FastAPI route functions allows you to customize the HTTP status codes returned by your API endpoints, providing clear and consistent communication of the request outcomes to clients.