status_code
| Since: | FastAPI 0.1(2019) |
|---|
FastAPI decorators (@app.get, @app.post, etc.) accept a status_code parameter that sets the default HTTP status code returned when an endpoint completes successfully. If omitted, all endpoints return 200 by default, but when designing a RESTful API it is recommended to explicitly specify an appropriate code based on the type of resource operation.
Syntax
from fastapi import FastAPI
from starlette import status # Import status code constants
app = FastAPI()
@app.post(
"/items/",
status_code=status.HTTP_201_CREATED, # Specify the status code to return on success
)
def 関数名():
# Processing logic
return {"message": "作成しました"}
Common Status Codes
| Constant | Code | Description |
|---|---|---|
HTTP_200_OK | 200 | The request completed successfully. Primarily used with GET, PUT, and PATCH. |
HTTP_201_CREATED | 201 | A resource was created successfully. Used when a POST request creates a new resource. |
HTTP_204_NO_CONTENT | 204 | The request succeeded but there is no content to return. Primarily used with DELETE. |
HTTP_301_MOVED_PERMANENTLY | 301 | The resource has moved permanently. The redirect destination is returned in the Location header. |
HTTP_302_FOUND | 302 | The resource has moved temporarily. Used for temporary redirects. |
HTTP_400_BAD_REQUEST | 400 | The request is malformed. Used when the client sends invalid parameters. |
HTTP_401_UNAUTHORIZED | 401 | Authentication is required. Used when an unauthenticated user attempts to access a resource. |
HTTP_403_FORBIDDEN | 403 | Access is forbidden. Used when an authenticated user lacks the required permissions. |
HTTP_404_NOT_FOUND | 404 | The resource was not found. Used when no data exists for the specified ID. |
HTTP_422_UNPROCESSABLE_ENTITY | 422 | The request is well-formed but cannot be processed. Returned automatically by FastAPI on validation errors. |
HTTP_500_INTERNAL_SERVER_ERROR | 500 | An error occurred on the server. Used when an unexpected exception is raised. |
Sample Code
The following example shows how to assign appropriate status codes to each HTTP method using CRUD operations on an item resource.
# ---- main.py ----
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from starlette import status
# Create a FastAPI instance
app = FastAPI()
# Define the request body schema
class ItemCreate(BaseModel):
name: str
price: float
class ItemUpdate(BaseModel):
name: str
price: float
# Sample data store (use a real database in production)
items: dict = {
1: {"id": 1, "name": "りんご", "price": 150.0},
2: {"id": 2, "name": "みかん", "price": 80.0},
}
next_id: int = 3
# GET: Returns a list of all items
# Returns 200 OK on success (this is the default, so it can be omitted)
@app.get("/items/", status_code=status.HTTP_200_OK)
def get_items():
return list(items.values())
# GET: Returns the item with the specified ID
# Raises an HTTPException with 404 if the item is not found
@app.get("/items/{item_id}", status_code=status.HTTP_200_OK)
def get_item(item_id: int):
if item_id not in items:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="商品が見つかりません")
return items[item_id]
# POST: Creates a new item
# Returns 201 Created on success
@app.post("/items/", status_code=status.HTTP_201_CREATED)
def create_item(item: ItemCreate):
global next_id
new_item = {"id": next_id, "name": item.name, "price": item.price}
items[next_id] = new_item
next_id += 1
return new_item
# PUT: Updates an existing item
# Returns 200 OK on success
@app.put("/items/{item_id}", status_code=status.HTTP_200_OK)
def update_item(item_id: int, item: ItemUpdate):
if item_id not in items:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="商品が見つかりません")
items[item_id] = {"id": item_id, "name": item.name, "price": item.price}
return items[item_id]
# DELETE: Deletes the item with the specified ID
# Returns 204 No Content on success (no response body is returned)
@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item(item_id: int):
if item_id not in items:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="商品が見つかりません")
del items[item_id]
# Return None because 204 responses must not include a response body
return None
Overview
status_code is a parameter passed to the decorator that sets the HTTP status code returned to the client when an endpoint completes successfully. You can specify a numeric value directly, but using constants from the starlette.status module (such as HTTP_201_CREATED) makes the intent clearer. In RESTful API design, it is conventional to return 200 for GET, 201 for resource creation with POST, and 204 for DELETE. Note that status_code is only the default value — if HTTPException is raised inside an endpoint, it overrides the specified code. For endpoints that specify 204, FastAPI automatically removes the response body, so it is recommended to use return None or a bare return.
If you find any errors or copyright issues, please contact us.