Performance: HTTPException usage
This affects server response time and client perceived latency by controlling error handling and response generation.
Jump into concepts and practice - no test required
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=400, detail='Invalid ID') 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': 'Invalid ID'} # returns JSON but no proper HTTP status return {'item_id': item_id}
| Pattern | Server Processing | Response Status | Client Handling | Verdict |
|---|---|---|---|---|
| Manual JSON error return | Continues processing | 200 OK (incorrect) | Client must parse error manually | [X] Bad |
| Raise HTTPException | Stops processing early | Correct HTTP error code | Client receives clear error fast | [OK] Good |
HTTPException in FastAPI?raise HTTPException(status_code=404, detail="Item not found").from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {"apple": "A juicy fruit"}
@app.get("/items/{item_name}")
async def read_item(item_name: str):
if item_name not in items:
raise HTTPException(status_code=404, detail="Item not found")
return {"item": items[item_name]}from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
if user_id < 0:
HTTPException(status_code=400, detail="Invalid user ID")
return {"user_id": user_id}