Good Code
The good version returns a real 404 with a clear detail when the resource does not exist.
Lesson 07
Raise `HTTPException` for expected client-facing failures instead of returning mixed success and error shapes.
from fastapi import APIRouter, HTTPException, status
router = APIRouter()
@router.get("/reviews/{review_id}")
async def get_review(review_id: int):
review = await reviews.find(review_id)
if review is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Review not found",
)
return reviewfrom fastapi import APIRouter
router = APIRouter()
@router.get("/reviews/{review_id}")
async def get_review(review_id: int):
review = await reviews.find(review_id)
if review is None:
return {"ok": False, "error": "Review not found"}
return {"ok": True, "review": review}The good version returns a real 404 with a clear detail when the resource does not exist.
The bad version returns an error envelope with a successful HTTP status. Clients, logs, and monitoring can all misread the failure.