0
0
FastAPIframework~5 mins

Status code control in FastAPI

Choose your learning style9 modes available
Introduction

Status codes tell the client if a request worked or not. Controlling them helps your app communicate clearly.

When you want to say a resource was created successfully with code 201.
When you need to tell the client a request failed with code 400 or 404.
When you want to confirm a request was successful with code 200.
When you want to indicate no content is returned with code 204.
When you want to customize the response status for any API endpoint.
Syntax
FastAPI
from fastapi import FastAPI, status
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/items/{item_id}", status_code=status.HTTP_200_OK)
async def read_item(item_id: int):
    return {"item_id": item_id}

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

Use status_code parameter in route decorators to set response status.

You can also return JSONResponse with a custom status code.

Examples
Returns a 200 OK status with a JSON message.
FastAPI
@app.get("/success", status_code=200)
async def success():
    return {"message": "OK"}
Returns a 201 Created status after creating a resource.
FastAPI
@app.post("/create", status_code=201)
async def create():
    return {"message": "Created"}
Returns a 404 Not Found status with a custom JSON message.
FastAPI
from fastapi.responses import JSONResponse

@app.get("/custom")
async def custom_status():
    return JSONResponse(content={"error": "Not found"}, status_code=404)
Sample Program

This FastAPI app has two endpoints. The GET endpoint returns 200 if the item exists or 404 if not. The POST endpoint returns 201 when an item is created.

FastAPI
from fastapi import FastAPI, status
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/items/{item_id}", status_code=status.HTTP_200_OK)
async def read_item(item_id: int):
    if item_id == 0:
        return JSONResponse(content={"error": "Item not found"}, status_code=status.HTTP_404_NOT_FOUND)
    return {"item_id": item_id, "name": "Sample Item"}

@app.post("/items/", status_code=status.HTTP_201_CREATED)
async def create_item(item: dict):
    return {"message": "Item created", "item": item}
OutputSuccess
Important Notes

Use status module constants for readability, like status.HTTP_404_NOT_FOUND.

Returning a JSONResponse lets you set status codes dynamically inside the function.

Always choose the right status code to help clients understand your API responses.

Summary

Status codes show if a request worked or failed.

Set status codes using status_code in route decorators or by returning JSONResponse.

Use standard codes like 200, 201, 404 for clear communication.