Status codes tell the client if a request worked or not. Controlling them helps your app communicate clearly.
Status code control in 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.
@app.get("/success", status_code=200) async def success(): return {"message": "OK"}
@app.post("/create", status_code=201) async def create(): return {"message": "Created"}
from fastapi.responses import JSONResponse @app.get("/custom") async def custom_status(): return JSONResponse(content={"error": "Not found"}, status_code=404)
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.
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}
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.
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.
Practice
status_code in a FastAPI route?Solution
Step 1: Understand HTTP status codes
Status codes communicate the result of a request, like success (200) or error (404).Step 2: Role of
Settingstatus_codein FastAPIstatus_codein a route tells the client what happened with their request.Final Answer:
To tell the client if the request was successful or if there was an error -> Option CQuick Check:
Status code = success or error info [OK]
- Confusing status_code with URL path
- Thinking status_code sets response data type
- Mixing status_code with server settings
Solution
Step 1: Check FastAPI decorator usage
FastAPI allows settingstatus_codedirectly in the route decorator.Step 2: Analyze each option
@app.post('/items', status_code=201) def create_item(): return {'message': 'Created'} correctly setsstatus_code=201in the decorator. @app.post('/items') def create_item(): status_code = 201 return {'message': 'Created'} wrongly assigns inside function without effect. @app.post('/items') def create_item(): return {'message': 'Created'}, 201 returns a tuple which FastAPI does not accept. @app.post('/items') def create_item(): return JSONResponse({'message': 'Created'}, status=201) usesJSONResponsebut with wrong parameter name (statusinstead ofstatus_code).Final Answer:
@app.post('/items', status_code=201) def create_item(): return {'message': 'Created'} -> Option DQuick Check:
Set status_code in decorator = @app.post('/items', status_code=201) def create_item(): return {'message': 'Created'} [OK]
- Trying to set status_code inside function without response object
- Returning tuple with status code (not supported)
- Using wrong parameter name in JSONResponse
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
@app.get('/data')
async def get_data():
return JSONResponse(content={'info': 'ok'}, status_code=202)Solution
Step 1: Identify the response type and status code
The route returns aJSONResponsewithstatus_code=202.Step 2: Understand HTTP status code 202
Status code 202 means "Accepted" indicating the request is accepted but not completed yet.Final Answer:
202 Accepted -> Option AQuick Check:
JSONResponse with status_code=202 = 202 Accepted [OK]
- Assuming default 200 OK without checking status_code
- Confusing 201 Created with 202 Accepted
- Ignoring status_code parameter in JSONResponse
from fastapi import FastAPI
app = FastAPI()
@app.get('/item/{item_id}', status_code=404)
async def read_item(item_id: int):
return {'item_id': item_id}Solution
Step 1: Understand status_code in decorator
Settingstatus_code=404in the decorator makes every response return 404 status regardless of logic.Step 2: Why this is a problem
The route returns data but status 404 means "Not Found" which is misleading if item exists.Final Answer:
Setting status_code=404 in decorator always returns 404 even if item exists -> Option BQuick Check:
Decorator status_code sets fixed response code [OK]
- Using status_code=404 in decorator to signal missing item
- Not raising HTTPException for 404 errors
- Assuming status_code in decorator is dynamic
Solution
Step 1: Understand status code control methods
Settingstatus_code=201in decorator sets default success code. RaisingHTTPExceptionsends error with desired status.Step 2: Evaluate options
Usestatus_code=201in decorator and raiseHTTPException(status_code=400)if username missing uses decorator for success and exception for error, which is correct. Setstatus_code=201in decorator and returnJSONResponsewithstatus_code=400inside function mixes decorator and response status codes causing confusion. Return a tuple with data and status code 201 or 400 returning tuple is invalid in FastAPI. Setstatus_code=400in decorator and return 201 in response body sets wrong default status code and misuses response body.Final Answer:
Use status_code=201 in decorator and raise HTTPException(status_code=400) if username missing -> Option AQuick Check:
Decorator for success, exceptions for errors [OK]
- Returning tuples with status codes (not supported)
- Setting error status_code in decorator instead of raising exception
- Mixing response status codes inconsistently
Ready to prove it?
Pass the test and this pattern moves unknown
