Only the Route Layer of a FastAPI App Should Raise HTTP Errors

In progress

Splitting a FastAPI app into routes, services and data access keeps each concern in one place: routes speak HTTP, services hold business rules, the data layer talks to the database. The split only pays off if HTTP stays in the routes. A service that raises HTTPException can't be reused from a CLI, a background job or a test without dragging HTTP status codes along.

Three Layers, Three Jobs

Layer Example file Knows about
Route routes/web/book.py requests, forms, status codes, templates
Service service/book.py business rules: what a valid book is, who may create it
Data data/book.py the SQLAlchemy session: add, commit, rollback
# data/book.py
def db_create_book(book_data: BookCreate, db: Session) -> Book:
    db_book = Book(**book_data.model_dump())  # .dict() in Pydantic v1
    try:
        db.add(db_book)
        db.commit()
        db.refresh(db_book)
        return db_book
    except Exception:
        db.rollback()
        raise

Translate Errors Once, at the Edge

Services raise domain exceptions (BookAlreadyExists, BookNotFound); the route, or an @app.exception_handler, maps each one to a status code. Re-raise with a bare raise or raise ... from e so the original type and traceback survive, instead of wrapping each error in a new Exception(f"...{e}") at every layer.

When the Split Is Overkill

A handful of endpoints with no business rules gains little from three layers: a route that calls the session directly is easier to read. Introduce the service layer when rules appear, or when something other than HTTP (a job, a CLI) needs the same logic.

References

Review cards

Flashcard Why should HTTP errors be raised only in the route layer of a FastAPI app?

To keep concerns separated: routes handle HTTP, services handle business rules, and the data layer handles database operations. Raising HTTP errors in services would mix concerns and make reusing services in non-HTTP contexts difficult.

Flashcard What should a service raise instead of an HTTP error?

A domain exception like BookAlreadyExists or BookNotFound.

Flashcard Why not put str(e) in an HTTPException's detail?

For a database error it sends the failing SQL, table and constraint names, sometimes submitted values, to the client. Log the exception server-side and return a generic message.