Performance: Status code control
This affects how quickly the server responds and how efficiently the client handles the response, impacting perceived speed and interaction responsiveness.
from fastapi import FastAPI, HTTPException app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id == 0: raise HTTPException(status_code=404, detail="Item not found") # Proper status code return {"item_id": item_id}
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id == 0: return {"error": "Item not found"} # No status code set, defaults to 200 return {"item_id": item_id}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No explicit status code (default 200) | No direct DOM ops | No reflows triggered by status | Potential extra paint due to error UI updates | [X] Bad |
| Explicit status code with HTTPException | No direct DOM ops | No reflows triggered by status | Minimal paint cost due to clear error handling | [OK] Good |
status_code in a FastAPI route?status_code in FastAPIstatus_code in a route tells the client what happened with their request.status_code directly in the route decorator.status_code=201 in 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) uses JSONResponse but with wrong parameter name (status instead of status_code).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)JSONResponse with status_code=202.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}status_code=404 in the decorator makes every response return 404 status regardless of logic.status_code=201 in decorator sets default success code. Raising HTTPException sends error with desired status.status_code=201 in decorator and raise HTTPException(status_code=400) if username missing uses decorator for success and exception for error, which is correct. Set status_code=201 in decorator and return JSONResponse with status_code=400 inside 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. Set status_code=400 in decorator and return 201 in response body sets wrong default status code and misuses response body.Pass the test and this pattern moves unknown