← All notes

Backend

FastAPI Layered Architecture — Routes, Services, and Repositories

Flat FastAPI routes that do everything are fast to write and painful to maintain. This post covers the three-layer architecture that keeps query logic, business logic, and HTTP concerns cleanly separated.

Published
Reading
5 min
Author
Fidelis Uwem Joseph
Series · Part 1 of 9FastAPI in Production
  1. FastAPI Layered Architecture — Routes, Services, and Repositories
  2. Alembic with SQLAlchemy 2.0 Async — Migrations That Hold in Production
  3. Alembic Async Migrations and Idempotent Database Seeding in FastAPI
  4. Stateless OTP Login in FastAPI with JWT and Redis
  5. Async Email Delivery in FastAPI — Two SMTP Paths, One Jinja2 Template System
  6. Celery + Redis in Production — Task Reliability with acks_late and Retry Backoff
  7. Monitoring Celery with Flower — Local Setup and SSH Tunnel for Remote Servers
  8. Mailpit as a Dev SMTP Catch-All Behind Traefik
  9. MinIO as a Self-Hosted S3 Backend in Docker

Series overviewPart 2 →

The most common FastAPI codebase shape is a set of route functions that import SQLAlchemy directly, run queries, do uniqueness checks, raise HTTP exceptions, and return responses — all in the same function. This works until you need to reuse a query in two routes, write a test that does not spin up an HTTP server, or understand a bug in a 200-line endpoint.

This post covers the three-layer architecture used in production: a thin route layer, a service layer that owns business logic, and a repository layer that owns data access. Each layer has a single job and does not cross into the other’s territory.

Prerequisites

Python 3.11, FastAPI 0.115 or later, and SQLAlchemy 2.x with async support (asyncpg driver). The examples assume fastapi-pagination is installed for the paginated list endpoints.

Background

A single-layer FastAPI codebase puts db.execute(select(User).where(...)) next to if user.email == other.email: raise HTTPException(...) next to return {"id": str(user.id)}. These are three different concerns — data access, business rules, HTTP serialization — sharing the same function scope.

The cost shows up when you need to send a welcome email after creating a user in one endpoint and also after an admin bulk-import in another. Without a service layer, you copy the logic. Without a repository layer, you copy the query. Copy-paste logic diverges silently under maintenance.

Implementation

1. The repository — data access only

BaseRepository is a generic class parameterised by the SQLAlchemy model type. Every concrete repository inherits from it and gets get_by_id, create, update, delete, and several query helpers for free.

app/repositories/base_repository.py
from typing import Generic, TypeVar, Type, Any
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from app.db.base import Base
ModelType = TypeVar("ModelType", bound=Base)
class BaseRepository(Generic[ModelType]):
def __init__(self, model: Type[ModelType], db: AsyncSession):
self.model = model
self.db = db
async def get_by_id(self, id: Any) -> ModelType | None:
return await self.db.get(self.model, id)
async def get_paginated(
self, page: int = 1, page_size: int = 20
) -> tuple[list[ModelType], int]:
query = select(self.model)
count_result = await self.db.execute(
select(func.count()).select_from(query.subquery())
)
total = count_result.scalar() or 0
result = await self.db.execute(
query.offset((page - 1) * page_size).limit(page_size)
)
return result.scalars().all(), total
async def create(self, obj: ModelType) -> ModelType:
self.db.add(obj)
await self.db.flush() # INSERT now, inside the caller's transaction
await self.db.refresh(obj) # load server defaults (id, timestamps)
return obj
async def update(self, obj: ModelType, data: dict) -> ModelType:
for field, value in data.items():
setattr(obj, field, value)
await self.db.flush()
await self.db.refresh(obj)
return obj
async def delete(self, obj: ModelType) -> None:
await self.db.delete(obj)
await self.db.flush()

Repositories flush() but never commit(). Flushing sends the SQL and surfaces constraint errors immediately; committing is the job of whoever owns the unit of work. In this codebase that is the session dependency, which commits once when the request succeeds and rolls back if anything raised:

app/db/session.py
async def get_db() -> AsyncIterator[AsyncSession]:
async with SessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise

Concrete repositories extend BaseRepository and add model-specific queries. The user repository, for example, adds eager-loading of role permissions across the branch assignment join and a case-insensitive search filter:

app/repositories/user.py
def _user_query():
return select(User).options(
selectinload(User.branch_assignments)
.selectinload(UserBranch.role)
.selectinload(Role.permissions),
selectinload(User.branch_assignments).selectinload(UserBranch.branch),
)
async def get_user_by_username(db: AsyncSession, username: str) -> User | None:
result = await db.execute(_user_query().where(User.username == username))
return result.scalar_one_or_none()
async def get_all_users(
db: AsyncSession,
params: Params,
search: str | None = None,
role_id: uuid.UUID | None = None,
):
query = _user_query().order_by(User.updated_at.desc())
if search:
term = f"%{search}%"
query = query.where(
User.username.ilike(term)
| User.first_name.ilike(term)
| User.email.ilike(term)
)
return await paginate(db, query, params=params)

The _user_query() helper centralises the selectinload chain. Every function that returns a User calls it, so the eager-load shape is consistent across all reads. Forgetting to load role.permissions in one query and then accessing user.role.permissions in a route triggers an implicit lazy load, which async SQLAlchemy cannot do: it raises MissingGreenlet. The helper prevents that class of bug entirely.

2. The service — business logic only

The service layer is where uniqueness checks live, where 404s are raised, where ownership is enforced. It calls repository functions and either returns domain objects or raises domain exceptions (NotFoundException, AlreadyExistsException). It never raises HTTPException.

app/services/user_service.py
class UserService:
async def create_user(self, db: AsyncSession, payload: UserCreate) -> User:
if await user_repo.get_user_by_username(db, payload.username):
raise AlreadyExistsException(message="Username already exists")
if await user_repo.get_user_by_email(db, payload.email):
raise AlreadyExistsException(message="Email already exists")
return await user_repo.create_user(db, payload)
async def get_by_id_or_404(self, db: AsyncSession, user_id: uuid.UUID) -> User:
user = await user_repo.get_user_by_id(db, user_id)
if not user:
raise NotFoundException(message="User not found")
return user
async def delete_user(
self, db: AsyncSession, target_username: str, current_username: str
) -> None:
if target_username != current_username:
raise ForbiddenException(message="You can only delete your own account")
user = await user_repo.get_user_by_username(db, target_username)
if not user:
raise NotFoundException(message="User not found")
await user_repo.delete_user(db, user)

AlreadyExistsException and NotFoundException are application-level exceptions that the global exception handler converts to HTTP responses. The service does not know or care that it is running inside FastAPI. A Celery task can call user_service.create_user(db, payload) and get the same exception semantics without any HTTP machinery involved.

3. The route — HTTP concerns only

Route handlers have one job: validate the incoming request, call the service, return the response. No queries. No uniqueness checks. No db.execute calls.

app/api/v1/endpoints/users.py
@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(
payload: UserCreate,
db: DBSession,
_: CurrentAdminUser,
):
user = await user_service.create_user(db, payload)
return user

The route handler is six lines. It declares what it needs (a database session, the current admin user), calls the service, and returns. The service raises if anything is wrong. The exception handler converts it to a structured HTTP response. The route never sees the failure path.

4. How exceptions flow

app/core/exceptions.py
class AppException(Exception):
def __init__(self, status_code: int, message: str, detail: str | None = None):
self.status_code = status_code
self.message = message
self.detail = detail
class NotFoundException(AppException):
def __init__(self, message: str = "Not found", detail: str | None = None):
super().__init__(status_code=404, message=message, detail=detail)
class AlreadyExistsException(AppException):
def __init__(self, message: str = "Already exists", detail: str | None = None):
super().__init__(status_code=409, message=message, detail=detail)

The global handler in main.py catches AppException and returns a consistent JSON envelope. Service code raises typed exceptions. Route code returns success. The HTTP status code is set once, in the exception definition, and applied consistently everywhere that exception is raised.

Testing

The repository and service layers can be tested independently without an HTTP client:

tests/test_user_service.py
@pytest.mark.asyncio
async def test_create_user_rejects_duplicate_username(db_session):
payload = UserCreate(username="alice", email="alice@example.com", ...)
await user_service.create_user(db_session, payload)
with pytest.raises(AlreadyExistsException, match="Username already exists"):
await user_service.create_user(db_session, payload)
Terminal
$ make test-file tests/test_user_service.py
tests/test_user_service.py::test_create_user_rejects_duplicate_username PASSED
tests/test_user_service.py::test_create_user_rejects_duplicate_email PASSED
tests/test_user_service.py::test_get_by_id_or_404_raises_on_missing PASSED
3 passed in 0.84s

Testing the service directly means your tests document business rules, not HTTP behaviour. The route-level tests only need to verify status codes and response shapes.

Pitfalls

Wrapping up

The three-layer shape is not architecture for its own sake. Routes do not know about SQL. Repositories do not know about business rules. Services do not know about HTTP. Each layer can be tested in isolation, reused across different callers, and modified without cascading changes into the others.

The next layer to add is a schema validation layer — specifically, ensuring that service inputs are always validated Pydantic models, never raw dicts, so the service boundary is typed end to end.

Going deeper

Check-then-insert is a race. create_user checks for an existing username, then inserts. Two requests arriving together both pass the check, and both insert. The check is still worth keeping for a friendly error message, but the real guarantee is a unique constraint in the database. Catch IntegrityError from the flush and translate it into the same AlreadyExistsException, so the race fails the same way as the common case.

Services without a session parameter. Passing db into every service method works, but it leaks infrastructure into every signature. A common next step is to give the service its repositories through FastAPI dependencies (UserService(repo=Depends(get_user_repo))). Tests then construct the service with fake repositories and never touch a database.

Where Celery fits. A Celery task has no request, so it has no session dependency. Give it the same unit of work explicitly: open a session with async with SessionLocal() as db, db.begin():, call the service, and let the context manager commit or roll back. The service code is identical in both places, which is the whole point of keeping HTTP out of it.

Pagination that scales. OFFSET pagination re-reads every skipped row, so page 5,000 is slow. For feeds and exports, keyset pagination (WHERE (updated_at, id) < (:last_updated_at, :last_id) ORDER BY updated_at DESC, id DESC LIMIT :n) stays fast at any depth.