FastAPI makes writing an endpoint so easy that it makes writing one badly easy too. You validate with a Pydantic schema, fine, but then the business logic goes in there as well, and the SQLAlchemy query too, and the call to the external service too, and suddenly the function is two hundred lines long, does six things, and testing the rule for “when is X allowed” means starting the whole application and a database.

This connects to something I argue in the article on tenant isolation. An invariant that cannot be checked automatically is not an invariant — it is an intention. And the most common reason a business rule cannot be checked is not that the rule is hard. It is that the rule lives somewhere you cannot reach without standing up half your infrastructure. Hexagonal architecture is, among other things, the answer to that placement problem.

The short version: separate the domain from the plumbing, and in FastAPI that means three folders and Depends. The long version — the layout, one feature end to end, and the tests — is what follows.

Why FastAPI tempts you to get this wrong

The problem is not FastAPI; it is how comfortable it is. The path operation receives the request already validated and typed, has the database session one Depends away, and returning JSON is return object. Everything invites you to do it right there. And for a “give me this record” endpoint, right there is the correct place.

It starts to hurt when the endpoint has rules. When “create a booking” is not an INSERT but “check the slot is free, check the customer is under their limit, price it by time band, record the event”. That is no longer plumbing: that is the business. And if it lives in the path operation, it lives tangled up with request parsing, the SQLAlchemy session and response serialization. The result: you cannot read the rule without reading everything else, you cannot check it without standing up the infrastructure, and you cannot change the infrastructure without touching the rule.

The hexagonal map, and the layout

The idea behind hexagonal: the domain at the centre, with no dependencies. Everything outside — HTTP, the database, outbound clients — are adapters implementing ports that the domain or the application layer defines. Dependencies point inwards: the adapter knows the domain, never the other way round.

Applied to FastAPI, per module:

bookings_module/
├── domain/
│   ├── booking.py            # entity: the rules
│   ├── value_objects.py      # TimeSlot, BookingPrice, BookingId...
│   └── ports.py              # BookingRepository (interface)
├── application/
│   ├── create_booking.py     # use case: orchestrates
│   └── commands.py           # CreateBookingCommand
└── adapters/
    ├── http/
    │   ├── router.py         # the FastAPI routes
    │   └── schemas.py        # Pydantic in/out
    ├── persistence/
    │   └── sqlalchemy_repo.py # implements BookingRepository
    └── outbound/
        └── client.py          # if the use case needs an external service

No pointless arguments about where each thing goes: domain/ imports nothing from FastAPI or SQLAlchemy; application/ imports domain/; adapters/ import application/ and domain/. That is the whole rule.

One feature end to end

Take “create a booking” through the layers. The HTTP adapter translates the outside world:

# adapters/http/router.py
@router.post("/bookings", status_code=201)
async def create_booking(
    body: CreateBookingIn,                                     # Pydantic schema (adapter)
    use_case: CreateBooking = Depends(get_create_booking),     # injection
) -> BookingOut:
    booking = use_case.execute(CreateBookingCommand(
        customer_id=body.customer_id, slot=body.slot,
    ))
    return BookingOut.from_domain(booking)

The use case orchestrates, but does not decide the rules — those belong to the domain:

# application/create_booking.py
class CreateBooking:
    def __init__(self, repo: BookingRepository, clock: Clock):
        self._repo, self._clock = repo, clock

    def execute(self, cmd: CreateBookingCommand) -> Booking:
        if self._repo.overlaps(cmd.slot):
            raise SlotUnavailable(cmd.slot)
        booking = Booking.create(cmd.customer_id, cmd.slot, self._clock.now())
        self._repo.save(booking)
        return booking

The domain holds the rules and knows nothing about HTTP or databases:

# domain/booking.py
@dataclass
class Booking:
    id: BookingId
    customer_id: CustomerId
    slot: TimeSlot
    price: BookingPrice

    @classmethod
    def create(cls, customer_id: CustomerId, slot: TimeSlot, now: datetime) -> "Booking":
        if not slot.starts_after(now):
            raise SlotInThePast(slot)
        return cls(BookingId.new(), customer_id, slot, BookingPrice.for_slot(slot))

And the repository: an interface in domain/ports.py, an implementation in adapters/persistence/. Composition happens at startup:

# composition — get_create_booking() returns the use case with its real dependencies
def get_create_booking(session: Session = Depends(get_session)) -> CreateBooking:
    return CreateBooking(repo=SqlAlchemyRepo(session), clock=SystemClock())

Depends acts as the injection container without adding a DI framework. For more involved cases you can bring one in, but most of the time this is enough.

And a note that matters if the system is multi-tenant: that composition function is exactly where tenant context belongs. If instead of get_session you inject a session already scoped to the tenant, no use case can be constructed without that context — which is the second of the three isolation levels I describe in the article on tenant isolation. Composition is not plumbing: it is where you decide what is impossible to build wrongly.

The tests, which is where it shows

Here is the return on all the ceremony above:

→ The domain gets checked with nothing running. Booking.create(...) with a date in the past raises SlotInThePast. That is a test running in memory: no app, no database, no network. You can afford many, and they are fast.

→ Use cases, with in-memory doubles. CreateBooking with a fake BookingRepository — a dict — and a fixed Clock: you test the orchestration, whether it checks for overlap and whether it saves, without touching SQLAlchemy. Fast.

→ Adapters, with contract tests. SqlAlchemyRepo satisfies the BookingRepository interface against a real database or a testcontainer. These are slow, so you keep few: just enough to guarantee the adapter does what the port promises.

That split is what makes verification viable in practice rather than only in principle. A rule checked with no infrastructure gets checked on every push, across all its edge cases. The same rule inside an endpoint needs the app running and a database with data in it: that is slow, so in the real world you will write a few cases, not all of them. The architecture does not make you more disciplined — it removes your excuse.

3folders: domain, application, adapters. Not one more
0infrastructure needed to check a domain rule
1adapter, plus its line in the composition function: what you touch to swap persistence engines

When not to

If your service is three CRUD endpoints, a script, or a prototype, hexagonal is overhead. The three folders and the ports solve the problem of a domain with rules worth isolating; if there are no rules, if it only reads and writes, you end up with more files, more indirection and more composition for the same work.

The honest threshold: if you cannot name the business rules living in that service, do not make it hexagonal yet. When the rules show up — and in a real domain they do — you will be glad. Before that, it is ceremony.

Closing

FastAPI does not stop you doing hexagonal; it just makes it very easy not to. Three folders, dependencies pointing inwards, and Depends acting as the container. The price is more files and some composition.

The return usually gets described as “a clean domain”, and that is the part of the standard argument I do not buy, because clean means nothing operational. The real return is this: a rule that lives in the domain can be checked automatically and cheaply, and a rule that lives in the endpoint cannot. In a system where some rules admit no failure, that difference stops being an aesthetic one.

In a domain with real rules, the trade pays. In a three-endpoint CRUD, it does not. Know which one you have.