Only the Route Layer of a FastAPI App Should Raise HTTP Errors
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
- FastAPI MOC - hub for FastAPI notes.
- Relative Template Directories Resolve Against the Working Directory, Not the Source File - the route in this example builds
Jinja2Templates(directory="templates"), which has that problem. - FastAPI documentation: Handling Errors -
HTTPExceptionand custom exception handlers. - FastAPI documentation: Bigger Applications - splitting an app with
APIRouter. - OWASP Error Handling Cheat Sheet - why error details stay server-side.
- Pydantic documentation: Migration guide -
.dict()renamed tomodel_dump()in v2.
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.
Flashcard What is the recommended way to handle exceptions in a service layer?
Re-raise with a bare raise or raise ... from e to preserve the original type and traceback.