- Book: Hexagonal Architecture in Python
- Companion code: hexagonal-python-examples — every listing from the book, free on GitHub
- My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools
- Me: xgabriel.com | GitHub
You add "cancel an order" to a FastAPI service. The pull request touches routers/orders.py, services/order_service.py, repositories/order_repository.py, schemas/orders.py and tests/test_orders.py. That's five files in five folders for one feature, and the reviewer has to open every one of them to see what the feature does. The next feature touches the same five files again, so two branches working on orders collide in the same service class.
That layout starts in the docs. FastAPI's Bigger Applications guide splits code into an app/routers/ package with one module per resource, and plenty of teams carry that one step further into services/ and repositories/ folders. It works fine for small services. The author of the widely shared fastapi-best-practices guide writes that organizing by file type "didn't scale well for our monolith with many domains and modules", and moved to one package per domain.
One folder per use case goes further still. Jimmy Bogard described the idea as Vertical Slice Architecture in a 2018 post, with one rule: "Minimize coupling between slices, and maximize coupling in a slice."
The layout
Here is the tree for three order use cases. Each folder under orders/ is a slice. It holds its HTTP route, its request and response models, its handler, its port, its adapter and its test.
app/ ├── __init__.py ├── main.py ├── db.py ├── shared/ │ ├── __init__.py │ ├── ports.py │ └── sql_status_store.py └── orders/ ├── __init__.py ├── place_order/ │ ├── __init__.py │ ├── request.py │ ├── handler.py │ ├── adapter.py │ ├── route.py │ └── test_place_order.py ├── cancel_order/ │ └── ... └── ship_order/ └── ... Two things sit outside the slices from day one. db.py holds the engine, the session dependency and the one ORM table, because there is one orders table and every slice reads it. shared/ starts empty and only fills up under the rule further down.

Layers spread one feature across the tree. Slices keep it in one folder.
Install what the code needs:
pip install fastapi uvicorn "sqlalchemy[asyncio]" aiosqlite \ httpx pytest import-linter Uvicorn serves the app, aiosqlite gives SQLAlchemy an async SQLite driver, and httpx is there because FastAPI's TestClient needs it. pytest runs the tests and Import Linter guards the boundaries (more on that below).
app/db.py uses the SQLAlchemy 2 typed mapping style from the ORM quick start and the async engine from the asyncio extension:
from collections.abc import AsyncIterator from sqlalchemy.ext.asyncio import ( AsyncSession, async_sessionmaker, create_async_engine, ) from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column engine = create_async_engine("sqlite+aiosqlite:///./orders.db") SessionLocal = async_sessionmaker(engine, expire_on_commit=False) class Base(DeclarativeBase): pass class OrderRow(Base): __tablename__ = "orders" id: Mapped[int] = mapped_column(primary_key=True) sku: Mapped[str] quantity: Mapped[int] status: Mapped[str] = mapped_column(default="placed") async def get_session() -> AsyncIterator[AsyncSession]: async with SessionLocal() as session: yield session expire_on_commit=False matters here. A commit normally expires every attribute, and reloading one needs implicit I/O, which asyncio sessions don't allow. With it off, the adapter below can return row.id straight after committing.
One complete slice: place_order
Start with the request and response models. They belong to this use case only, so they live in app/orders/place_order/request.py. The constraints use Pydantic's Field():
from pydantic import BaseModel, Field class PlaceOrderRequest(BaseModel): sku: str = Field(min_length=3, max_length=32) quantity: int = Field(gt=0, le=100) class PlaceOrderResponse(BaseModel): order_id: int status: str The handler is the core of the slice. It knows nothing about HTTP or SQL. Its port is a typing.Protocol, so any object with a matching add method satisfies it. The port sits in the slice, because only this slice writes new orders. handler.py:
from dataclasses import dataclass from typing import Protocol class OrderWriter(Protocol): async def add(self, sku: str, quantity: int) -> int: ... class OrderRejected(Exception): pass @dataclass(frozen=True) class PlaceOrder: sku: str quantity: int async def handle(cmd: PlaceOrder, orders: OrderWriter) -> int: if cmd.sku.startswith("DISC-"): raise OrderRejected(f"{cmd.sku} is discontinued") return await orders.add(cmd.sku, cmd.quantity) The adapter is the SQL side of that port. adapter.py:
from sqlalchemy.ext.asyncio import AsyncSession from app.db import OrderRow class SqlOrderWriter: def __init__(self, session: AsyncSession) -> None: self._session = session async def add(self, sku: str, quantity: int) -> int: row = OrderRow(sku=sku, quantity=quantity) self._session.add(row) await self._session.commit() return row.id The route wires them together with FastAPI dependencies. It uses an APIRouter so the slice can be mounted on any app. route.py:
from typing import Annotated from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.ext.asyncio import AsyncSession from app.db import get_session from .adapter import SqlOrderWriter from .handler import OrderRejected, OrderWriter, PlaceOrder, handle from .request import PlaceOrderRequest, PlaceOrderResponse router = APIRouter() def get_writer( session: Annotated[AsyncSession, Depends(get_session)], ) -> OrderWriter: return SqlOrderWriter(session) @router.post("/orders", status_code=201) async def place_order( body: PlaceOrderRequest, orders: Annotated[OrderWriter, Depends(get_writer)], ) -> PlaceOrderResponse: cmd = PlaceOrder(sku=body.sku, quantity=body.quantity) try: order_id = await handle(cmd, orders) except OrderRejected as exc: raise HTTPException( status_code=422, detail=str(exc) ) from exc return PlaceOrderResponse(order_id=order_id, status="placed") If you read that with hexagonal eyes, each slice is a very small hexagon. The handler is the core, the route is the driving adapter, and SqlOrderWriter is the driven adapter behind the port.
The test lives next to the code
test_place_order.py sits in the slice folder. It mounts only this slice's router on a throwaway app and swaps the writer through app.dependency_overrides, the documented way to replace a dependency in tests. No database file gets touched, because get_session is only reached through get_writer, and get_writer is overridden.
import asyncio import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from app.orders.place_order.handler import ( OrderRejected, PlaceOrder, handle, ) from app.orders.place_order.route import get_writer, router class FakeWriter: def __init__(self) -> None: self.rows: list[tuple[str, int]] = [] async def add(self, sku: str, quantity: int) -> int: self.rows.append((sku, quantity)) return len(self.rows) def test_places_an_order() -> None: fake = FakeWriter() api = FastAPI() api.include_router(router) api.dependency_overrides[get_writer] = lambda: fake resp = TestClient(api).post( "/orders", json={"sku": "ABC-1", "quantity": 2} ) assert resp.status_code == 201 assert resp.json() == {"order_id": 1, "status": "placed"} assert fake.rows == [("ABC-1", 2)] The business rule needs no HTTP at all. In the same file, call the handler with the fake:
def test_rejects_discontinued_sku() -> None: fake = FakeWriter() with pytest.raises(OrderRejected): asyncio.run(handle(PlaceOrder("DISC-9", 1), fake)) assert fake.rows == [] One pytest detail to know before you copy this layout. In pytest's default prepend import mode, the good-practices page says test files need unique basenames. One fix it offers is __init__.py files that turn the folders into packages, which is why every folder in the tree has one. For new projects it recommends --import-mode=importlib instead. Name the tests after the slice either way, so test_place_order.py never meets a second test_handler.py.
app/main.py is the only file outside the slice that knows the slice exists:
from contextlib import asynccontextmanager from fastapi import FastAPI from app.db import Base, engine from app.orders.place_order.route import router as place_order @asynccontextmanager async def lifespan(app: FastAPI): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) yield await engine.dispose() app = FastAPI(lifespan=lifespan) app.include_router(place_order) The lifespan creates the table on startup. run_sync is there because, as the SQLAlchemy asyncio docs note, create_all has no awaitable hook. Run it with uvicorn app.main:app and the tests with pytest.
When a port moves into shared/
Here is the rule: a port lives in its slice until a second slice needs the same port. Then, and only then, it moves to app/shared/.
cancel_order arrives first. It needs to read an order's status and write a new one. Nothing else needs that yet, so it gets its own OrderStatusStore port and SQL adapter inside cancel_order/. Moving it to shared/ now would be speculative: a shared module with one caller.
Then ship_order arrives and needs exactly those two methods. That's the second caller. The port moves to app/shared/ports.py:
from typing import Protocol class OrderStatusStore(Protocol): async def get_status(self, order_id: int) -> str | None: ... async def set_status( self, order_id: int, status: str ) -> None: ... Its adapter moves with it to app/shared/sql_status_store.py, along with the dependency function, so both slices override the same key in tests:
from typing import Annotated from fastapi import Depends from sqlalchemy import select, update from sqlalchemy.ext.asyncio import AsyncSession from app.db import OrderRow, get_session from app.shared.ports import OrderStatusStore class SqlOrderStatusStore: def __init__(self, session: AsyncSession) -> None: self._session = session async def get_status(self, order_id: int) -> str | None: stmt = select(OrderRow.status).where(OrderRow.id == order_id) return await self._session.scalar(stmt) async def set_status(self, order_id: int, status: str) -> None: stmt = ( update(OrderRow) .where(OrderRow.id == order_id) .values(status=status) ) await self._session.execute(stmt) await self._session.commit() def get_status_store( session: Annotated[AsyncSession, Depends(get_session)], ) -> OrderStatusStore: return SqlOrderStatusStore(session) The ship_order handler then imports from shared, never from cancel_order:
from app.shared.ports import OrderStatusStore class CannotShip(Exception): pass async def handle(order_id: int, store: OrderStatusStore) -> None: status = await store.get_status(order_id) if status != "placed": raise CannotShip(f"order {order_id} is {status}") await store.set_status(order_id, "shipped") cancel_order changes two import lines and deletes its local copies. The business rules stay where they were: "you can't cancel a shipped order" stays in cancel_order/handler.py, and "you can only ship a placed order" stays in ship_order/handler.py. Only the port moved, because the port was the thing two slices needed.

The port moves to shared/ when a second slice needs it.
Stop slices from importing each other
The layout only holds while nobody writes from app.orders.cancel_order.handler import ... inside ship_order. Don't leave that to code review. Import Linter has an independence contract that, per its docs, checks "that there are no imports in any direction between the modules, even indirectly". Its forbidden contract stops shared/ from reaching back into a slice. Put this in .importlinter at the project root:
[importlinter] root_package = app [importlinter:contract:slices] name = Slices do not import each other type = independence modules = app.orders.place_order app.orders.cancel_order app.orders.ship_order [importlinter:contract:shared] name = Shared code never imports a slice type = forbidden source_modules = app.shared forbidden_modules = app.orders Run lint-imports in CI next to pytest. This is also why each test mounts its own throwaway app instead of importing app.main: main.py imports every slice, so a test that imported it would create an indirect path between slices, and the independence contract would flag it.
What a new feature costs now
Go back to the opening pull request. With slices, "refund an order" is a new orders/refund_order/ folder with its own request model, handler, adapter, route and test, plus one include_router line in main.py. If it needs OrderStatusStore, it imports it from shared/. If it needs something only it uses, that stays in its folder. The reviewer opens one folder.
You pay for that with some repetition. Two slices may each have a small Pydantic model that looks alike, and that's fine until they need to change together. Bogard's post puts the payoff this way: "New features only add code, you're not changing shared code and worrying about side effects." The second-caller rule for ports is how you keep the shared part small enough for that to stay true.
If this was useful
Vertical slice is one of the five shapes in Hexagonal Architecture in Python. The book builds one async FastAPI and SQLAlchemy 2 service as Hexagonal, Clean, Onion, layered and vertical slice, then measures what each one costs you when the code changes. Every listing runs from the free companion repo, so you can diff the slice version against the hexagonal one yourself.
