FastAPI

Lesson 07

HTTPException handling

Raise `HTTPException` for expected client-facing failures instead of returning mixed success and error shapes.

Good Code

api/reviews.py
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 review

Bad Code

api/reviews.py
from 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}

Review Notes

What to review

Good Code

The good version returns a real 404 with a clear detail when the resource does not exist.

Bad Code

The bad version returns an error envelope with a successful HTTP status. Clients, logs, and monitoring can all misread the failure.

Takeaways

  • Expected API failures should use explicit HTTP status codes and response shapes.