Lesson 13 of 28Architecture
Python Backend Architecture
Structure a FastAPI service into thin routers, services, repositories and schemas, wired with Depends and a unit of work.
A FastAPI tutorial fits in one main.py. A real service with payments, emails, background jobs and 200 tests does not. This lesson turns the layered idea from Layered Architecture into an actual folder layout, the one you will see (with small variations) in most production FastAPI codebases, and the one reviewers expect in a backend take-home.
A real service layout
- orders-service/
- app/
- main.pycreate_app(): include routers, middleware
- settings.pySettings(BaseSettings), read from env
- api/
- deps.pyDepends providers: session, services, current user
- routers/
- orders.pythin: parse, call service, return schema
- health.py
- schemas/
- orders.pyPydantic DTOs: OrderCreate, OrderOut
- services/
- orders.pyuse cases: place_order, refund_order
- domain/
- order.pyOrder entity + rules, pure Python
- errors.pyOrderNotFound, InvalidTransition
- repositories/
- orders.pySqlOrderRepository (SQLAlchemy)
- db/
- models.pySQLAlchemy ORM tables
- session.pyengine + async_sessionmaker
- uow.pyUnit of Work: one transaction
- adapters/
- stripe_gateway.pyimplements PaymentGateway
- ses_mailer.pyimplements Mailer
- migrations/Alembic
- tests/
- unit/services with fakes, milliseconds
- integration/real Postgres in Docker
- pyproject.toml
Read it top to bottom as the request travels: routers → services → domain and repositories → db. schemas sit at the HTTP edge, adapters at the edges to other companies' APIs.
Each layer in FastAPI terms
Routers stay thin. They declare the HTTP shape and delegate everything else. If a router has an if about business rules, it belongs in a service.
from fastapi import APIRouter, Depends, HTTPException, status
from app.api.deps import get_order_service
from app.domain.errors import InvalidTransition, OrderNotFound
from app.schemas.orders import OrderCreate, OrderOut
from app.services.orders import OrderService
router = APIRouter(prefix="/orders", tags=["orders"])
@router.post("", response_model=OrderOut, status_code=status.HTTP_201_CREATED)
async def create_order(body: OrderCreate, service: OrderService = Depends(get_order_service)):
return await service.place_order(body.customer_id, body.items)
@router.post("/{order_id}/refund", response_model=OrderOut)
async def refund(order_id: int, service: OrderService = Depends(get_order_service)):
try:
return await service.refund_order(order_id)
except OrderNotFound:
raise HTTPException(status.HTTP_404_NOT_FOUND)
except InvalidTransition as e:
raise HTTPException(status.HTTP_409_CONFLICT, str(e))Schemas are Pydantic v2 DTOs. They validate input and shape output. from_attributes=True lets OrderOut read fields straight off a domain or ORM object.
from pydantic import BaseModel, ConfigDict, Field
class OrderItemIn(BaseModel):
sku: str
qty: int = Field(gt=0)
class OrderCreate(BaseModel):
customer_id: int
items: list[OrderItemIn] = Field(min_length=1)
class OrderOut(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
status: str
total_cents: intServices hold the use cases. Repositories hold the SQLAlchemy queries and return domain objects. The service never sees a select().
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.models import OrderRow
from app.domain.order import Order
class SqlOrderRepository:
def __init__(self, session: AsyncSession):
self.session = session
async def get(self, order_id: int) -> Order | None:
row = await self.session.scalar(select(OrderRow).where(OrderRow.id == order_id))
return row.to_domain() if row else None
async def add(self, order: Order) -> None:
self.session.add(OrderRow.from_domain(order))Where does each piece of code belong?
Wiring with Depends
FastAPI's Depends is a small dependency injection system. You write provider functions; FastAPI calls them per request, caches each result within that request, and passes them in. Providers can depend on other providers, so the whole object graph builds itself.
from collections.abc import AsyncIterator
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.adapters.stripe_gateway import StripeGateway
from app.db.session import SessionLocal
from app.db.uow import SqlUnitOfWork
from app.services.orders import OrderService
from app.settings import Settings, get_settings
async def get_session() -> AsyncIterator[AsyncSession]:
async with SessionLocal() as session:
yield session # closed after the response is sent
def get_order_service(
session: AsyncSession = Depends(get_session),
settings: Settings = Depends(get_settings),
) -> OrderService:
return OrderService(uow=SqlUnitOfWork(session), gateway=StripeGateway(settings.stripe_key))A request hits refund. Put what FastAPI does with the dependencies in order.
- Tap the steps below in the right order.
In tests you swap any provider with app.dependency_overrides[get_order_service] = lambda: OrderService(FakeUoW(), FakeGateway()). No monkeypatching, no real Stripe.
Settings come from environment variables through pydantic-settings, built once and cached:
from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env")
database_url: str
stripe_key: str
refund_window_days: int = 30
@lru_cache
def get_settings() -> Settings:
return Settings()if order.total_cents > 100_000 and not user.is_verified: raise HTTPException(403). Why?Unit of work: one transaction per use case
Placing an order may write to orders, order_items and outbox. Either all of them commit or none do. A Unit of Work (UoW) wraps one database transaction and exposes the repositories that share it. The service says when to commit; the UoW knows how.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.The real SqlUnitOfWork does the same with session.commit() and session.rollback(). Only order 1 survived: the failing use case left nothing half-written.
Ports and adapters (hexagonal), simply
Hexagonal architecture, also called ports and adapters (Alistair Cockburn, 2005), draws the app as a core surrounded by plugs. A port is an interface the core owns ("I need a way to charge cards", "I need a way to save orders"). An adapter is a concrete plug that fits a port: Stripe, Postgres, an HTTP router, or a fake for tests. Clean architecture is the same idea drawn as rings: entities in the middle, use cases around them, adapters outside, with every dependency pointing inward. The next lesson, Hexagonal and Clean Architecture, takes this idea all the way.
The core is plain Python: services and domain. It imports no FastAPI, SQLAlchemy or Stripe code.
You already built most of this: repositories/ and adapters/ are the driven adapters, routers/ the driving ones, services/ + domain/ the core. The vocabulary just helps you explain it.
Where async goes
FastAPI is async, but not every layer needs to be. A good rule: async at the I/O edges, sync in the middle.
- Routers, repositories and API adapters are
async defbecause they wait on the network or database (AsyncSession,httpx.AsyncClient). - Domain logic is plain
def. Checking whether a refund is allowed does no I/O, soasyncwould add noise and nothing else. - Never call a blocking library (sync
requests, sync SQLAlchemySession) insideasync def. It freezes the whole event loop and every other request with it. Either use the async version, or declare the route as plaindefso FastAPI runs it in a threadpool.
async def route calls requests.get(...) to a slow partner API that takes 2 seconds. What happens under load?How Django differs
Django organises a project into apps: self-contained feature folders (orders/, billing/, accounts/), each with its own models.py, views.py, admin.py, urls.py and migrations. That is a feature-first split, while the FastAPI layout above is layer-first.
Django models are active record: the model class is both the table mapping and the place for behaviour (order.save(), Order.objects.filter(...)). The Django convention is "fat models, thin views", and most Django code skips a separate repository layer. Teams that want stricter boundaries add a services.py per app for use cases. Both styles work. Pick one and apply it consistently.
| FastAPI layout above | Django default | |
|---|---|---|
| Top-level split | By layer | By feature (apps) |
| Data access | Repository over SQLAlchemy | Active-record models and managers |
| Validation | Pydantic schemas | Forms / DRF serializers |
| DI | Depends | Mostly imports and settings |
Repository with an in-memory fake
Write an InMemoryUserRepository (the fake you would use in unit tests) and a service function that only talks to it through its methods.
Repository methods:
add(user)stores aUserget(user_id)returns the user orNone/nullget_by_email(email)(TypeScript:getByEmail) finds a user by email, ignoring caselist_all()(TypeScript:listAll) returns all users sorted byid
Service:
register_user(repo, email, name) (TypeScript: registerUser) normalises the email (strip and lowercase) and the name (strip), raises ValueError (TypeScript: throws an Error) if that email is already taken, otherwise creates a User with the next id (1, 2, 3...), adds it, and returns it.
Each repository instance must have its own storage. Two repositories must never see each other's users.
- thin router
- A route handler that only parses input, calls a service, and maps the result or error to HTTP.
- Depends
- FastAPI's dependency injection: provider functions run per request and can be overridden in tests.
- unit of work
- An object wrapping one transaction so a use case's writes all commit together or all roll back.
- port
- An interface the core of the app defines for something it needs, like saving orders or charging cards.
- adapter
- A concrete implementation of a port (Postgres, Stripe, a fake) or an entry point that drives the core (HTTP, CLI).
- active record
- A pattern where the model class both maps the table and carries behaviour, as in Django's ORM.