Skip to content

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.

20 min read0/4 questions

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
  • 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.

app/api/routers/orders.py
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.

app/schemas/orders.py
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: int

Services hold the use cases. Repositories hold the SQLAlchemy queries and return domain objects. The service never sees a select().

app/repositories/orders.py
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))
Match the pairs0/5 matched

Where does each piece of code belong?

Choose an item, then its match on the other side.

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.

app/api/deps.py
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))
Put it in order5 steps

A request hits refund. Put what FastAPI does with the dependencies in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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:

app/settings.py
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()
Quick check
A reviewer flags this router line: if order.total_cents > 100_000 and not user.is_verified: raise HTTPException(403). Why?
Need a nudge? A hint rules out a wrong answer.

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.

Python
class FakeUnitOfWork: def __init__(self): self.orders: dict[int, dict] = {} self._pending: dict[int, dict] = {} self.committed = False def __enter__(self): self._pending = {} return self def __exit__(self, exc_type, exc, tb): if exc_type is not None: self._pending = {} # rollback on any error print("rolled back") def add(self, order: dict) -> None: self._pending[order["id"]] = order def commit(self) -> None: self.orders.update(self._pending) self.committed = True def place_order(uow: FakeUnitOfWork, order_id: int, cents: int) -> None: with uow: uow.add({"id": order_id, "cents": cents}) if cents <= 0: raise ValueError("empty order") uow.commit() uow = FakeUnitOfWork()place_order(uow, 1, 4999)try: place_order(uow, 2, 0)except ValueError: passprint(sorted(uow.orders))
Output
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.

Ports and adapters around the order core
Your code, framework-freeFastAPI router: driving adapterFastAPI routerdriving adapterCLI / cron job: driving adapterCLI / cron jobdriving adapterOrder service + domain: the coreOrder service + domainthe corePostgres: OrderRepository portPostgresOrderRepository portStripe: PaymentGateway portStripePaymentGateway portAmazon SES: Mailer portAmazon SESMailer portTest fakes: same portsTest fakessame portscallscallsportportportplugs in

The core is plain Python: services and domain. It imports no FastAPI, SQLAlchemy or Stripe code.

1/4

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 def because 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, so async would add noise and nothing else.
  • Never call a blocking library (sync requests, sync SQLAlchemy Session) inside async def. It freezes the whole event loop and every other request with it. Either use the async version, or declare the route as plain def so FastAPI runs it in a threadpool.
Quick check
An async def route calls requests.get(...) to a slow partner API that takes 2 seconds. What happens under load?
Need a nudge? A hint rules out a wrong answer.

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 aboveDjango default
Top-level splitBy layerBy feature (apps)
Data accessRepository over SQLAlchemyActive-record models and managers
ValidationPydantic schemasForms / DRF serializers
DIDependsMostly imports and settings
ChallengeMedium

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 a User
  • get(user_id) returns the user or None / null
  • get_by_email(email) (TypeScript: getByEmail) finds a user by email, ignoring case
  • list_all() (TypeScript: listAll) returns all users sorted by id

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.

from dataclasses import dataclass @dataclassclass User: id: int email: str name: strclass InMemoryUserRepository: def __init__(self): pass def add(self, user: User) -> None: pass def get(self, user_id: int) -> User | None: pass def get_by_email(self, email: str) -> User | None: pass def list_all(self) -> list[User]: pass def register_user(repo, email: str, name: str) -> User: # Use only repo methods: no reaching into its internals. pass
Key terms
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.