FastAPI is deliberately unopinionated about layout. That is a strength for small apps and a cost for business backends. Someone has to decide where things go, and if nobody does, the codebase decides for you.
This guide sets out the layout we use for every business service in ZENLEAF, the FastAPI framework we use to deliver Python backends. Each service gets one folder with the same eight files. The pattern is not new: it borrows from layered architecture and the repository pattern. What matters is applying it the same way to every service, so any engineer can open any folder and know where to look.
What “service” means here
A service is one business capability with its own data: orders, invoices, customers, subscriptions. It owns its tables, exposes its own endpoints and publishes events when something important happens to its data.
A service is a folder first. Whether it also runs as its own process is a deployment decision you can make later. Many teams start with several service folders inside one FastAPI app and split them into separate deployments only when one needs to scale or release on its own. The folder pattern works for both. That is the point: the code does not need rewriting when the deployment changes.
The eight files
Each service folder holds the same eight files.
| File | What it holds | What it must not hold |
|---|---|---|
model.py |
Database models (SQLAlchemy) for this service’s tables | Business decisions, HTTP concerns |
schema.py |
Pydantic models for requests and responses | Database access |
event.py |
Events this service publishes, and handlers for events it listens to | Direct calls into another service’s code |
dependency.py |
FastAPI dependencies: the current user, a database session, permission checks | Business rules |
service.py |
The steps of each use case, in order | SQL, HTTP request objects |
repository.py |
Reads and writes to this service’s tables | Business decisions |
rule.py |
Business rules as plain functions | Database access, HTTP, events |
router.py |
The API endpoints | Logic beyond calling the service |
The folder tree for a project with three services looks like this:
app/
main.py
core/
config.py
database.py
security.py
logging.py
services/
orders/
__init__.py
model.py
schema.py
event.py
dependency.py
service.py
repository.py
rule.py
router.py
invoices/
...same eight files...
customers/
...same eight files...
tests/
orders/
test_rule.py
test_service.py
test_router.py
core/ holds the shared platform parts: settings, the database engine, authentication and logging. Services import from core/. Services never import from each other.
Why business rules get their own file
This is the decision that pays back most. A business rule is a statement your product owner would recognize: “An order over the customer’s credit limit needs approval.” “An invoice cannot be edited after it is sent.” “A discount cannot exceed the margin floor.”
In most FastAPI codebases these rules live inside route handlers or service functions, mixed with database calls and HTTP status codes. That causes three problems:
- They are hard to find. To learn how approval works, you read every handler that touches orders.
- They are hard to test. Testing one rule needs a database, a request and a user.
- They drift. Two handlers check the same rule in slightly different ways, and nobody notices until a customer does.
Putting rules in rule.py as plain Python functions fixes all three. A rule takes values and returns a decision. It does not know about the database or the request. It can be read by someone who is not a FastAPI expert, and it can be tested on its own, without a database.
service.py then reads like a recipe: load the data, apply the rules, save the result, publish the event. When a rule changes, you change one function and its test.
A worked example: the orders service
The code below is a simplified example written for this post. It shows the shape of each file, not production code. Imports and error handling are trimmed to keep it readable.
model.py
# Simplified example
from sqlalchemy import Numeric, String
from sqlalchemy.orm import Mapped, mapped_column
from app.core.database import Base
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int]
total: Mapped[float] = mapped_column(Numeric(12, 2))
status: Mapped[str] = mapped_column(String(20), default="draft")
schema.py
# Simplified example
from pydantic import BaseModel, Field
class OrderCreate(BaseModel):
customer_id: int
total: float = Field(gt=0)
class OrderRead(BaseModel):
id: int
customer_id: int
total: float
status: str
model_config = {"from_attributes": True}
rule.py
# Simplified example: plain functions, no database, no HTTP
def needs_approval(order_total: float, credit_limit: float) -> bool:
return order_total > credit_limit
def can_cancel(status: str) -> bool:
return status in {"draft", "pending_approval"}
repository.py
# Simplified example
from sqlalchemy.ext.asyncio import AsyncSession
from .model import Order
class OrderRepository:
def __init__(self, session: AsyncSession):
self.session = session
async def add(self, order: Order) -> Order:
self.session.add(order)
await self.session.flush()
return order
async def get(self, order_id: int) -> Order | None:
return await self.session.get(Order, order_id)
service.py
# Simplified example: the steps, in order
from . import rule
from .event import publish_order_created
from .model import Order
from .repository import OrderRepository
from .schema import OrderCreate
class OrderService:
def __init__(self, repo: OrderRepository, credit_limit_lookup):
self.repo = repo
self.credit_limit_lookup = credit_limit_lookup
async def create(self, data: OrderCreate) -> Order:
limit = await self.credit_limit_lookup(data.customer_id)
status = "pending_approval" if rule.needs_approval(data.total, limit) else "confirmed"
order = await self.repo.add(Order(customer_id=data.customer_id, total=data.total, status=status))
await publish_order_created(order)
return order
dependency.py
# Simplified example
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_session
from .repository import OrderRepository
from .service import OrderService
async def get_order_service(session: AsyncSession = Depends(get_session)) -> OrderService:
return OrderService(OrderRepository(session), credit_limit_lookup=lookup_credit_limit)
lookup_credit_limit is the interesting part. The orders service needs a customer’s credit limit, but the customers service owns that data. Orders must not import the customers repository. The dependency decides how to get the value. It could be an internal API call, a read model kept up to date by events, or a query the customers service exposes. The service code does not care which.
router.py
# Simplified example: endpoints only call the service
from fastapi import APIRouter, Depends
from .dependency import get_order_service
from .schema import OrderCreate, OrderRead
from .service import OrderService
router = APIRouter(prefix="/orders", tags=["orders"])
@router.post("", response_model=OrderRead, status_code=201)
async def create_order(data: OrderCreate, svc: OrderService = Depends(get_order_service)):
return await svc.create(data)
event.py
# Simplified example: publish facts, not commands.
# event_bus stands for the shared event publisher (Kafka in ZENLEAF).
async def publish_order_created(order) -> None:
await event_bus.publish("orders.created", {
"order_id": order.id,
"customer_id": order.customer_id,
"total": str(order.total),
"status": order.status,
})
Read the router, and you see the API. Read the service, and you see the steps. Read the rules, and you see the business. Nothing is in two places.
Start your FastAPI backend from this pattern
ZENLEAF is the framework we use to deliver Python backends. Every service follows this layout, with login, roles, logging and events already in place. Tell us what you are building in a 30-minute call.
How services talk to each other
The rule “services never import from each other” raises the obvious question: how does the invoices service learn that an order was confirmed?
There are two channels, and each has a job.
Events, for things that happened. When an order is confirmed, the orders service publishes orders.confirmed. The invoices service listens and creates a draft invoice. Orders does not know invoices exists. You can add a notifications service next month that also listens, without touching orders. In ZENLEAF the event channel is Apache Kafka, set up the same way on every project.
Dependencies, for questions that need an answer now. When orders needs a credit limit before it can save, it cannot wait for an event. A dependency fetches the answer through a defined interface. Keep these calls few. Every synchronous call between services is a place where one service being down takes the other with it.
A useful test: if service A needs to call service B synchronously on most requests, the two may belong in one service. Splitting too early is a more common mistake than splitting too late.
Where the shared parts live
Some things every service needs: a database session, the current user, permission checks, logging, pagination, background jobs. These belong in core/, built once.
In ZENLEAF the shared layer includes:
- SQLAlchemy 2 in async mode for database access.
- fastapi-users for login with OAuth2 and JWT tokens.
- Single sign-on across applications over OpenID Connect.
- fastapi-query for consistent paging and filtering.
- Role-based access control, applied per service.
- Loguru for logging, Prefect for workflows, Kafka for events and rrule for recurring schedules.
A service’s dependency.py pulls these in. Its service.py never sets them up itself.
The benefit is consistency. Every list endpoint pages and filters the same way. Every log line has the same shape. Every permission check goes through the same code. When a security reviewer asks how access control works, the answer is one place, not twenty.
Testing the pattern
The layout makes a three-level test plan natural.
- Rules, with plain unit tests. No database, no app, no fixtures. These are the cheapest tests you will ever write and they cover the logic that matters most to the business.
- Services, with a fake repository. Pass an in-memory repository and a stub credit-limit lookup into
OrderService. Check that the right status is saved and the right event is published. - Routers, with FastAPI’s test client against a test database. A few tests per endpoint for status codes, validation errors and permissions. These are slower, so keep them focused on the HTTP contract.
# Simplified example: a rule test needs nothing but Python
from app.services.orders import rule
def test_order_over_limit_needs_approval():
assert rule.needs_approval(order_total=1200, credit_limit=1000)
def test_order_within_limit_does_not():
assert not rule.needs_approval(order_total=800, credit_limit=1000)
Mirror the service folders in tests/, so the test for orders/rule.py is always tests/orders/test_rule.py.
Mistakes that make FastAPI codebases hard to change
Fat routers. Database queries and business decisions inside @router.post functions. It works until two endpoints need the same logic. Keep routers to validation in, service call, response out.
One models file for the whole app. A single models.py with every table invites every service to join every other service’s tables. Each service should own its models and expose data through its repository or its events.
Rules hidden in schemas. Pydantic validators are good for shape: a positive number, a valid email. They are the wrong place for business decisions like “this customer cannot order this product”. Put those in rule.py, where the product owner can find them.
Importing across services. One from app.services.customers.repository import ... in the orders service and the boundary is gone. Add a lint rule or an import check to CI that fails on cross-service imports.
Splitting deployments on day one. Separate processes, separate databases and network calls between everything, before anyone knows where the real boundaries are. Start with service folders in one app. Split a service out when you have a reason.
Events that carry commands. invoices.create_invoice_please is a remote procedure call wearing an event’s clothes. Publish facts (orders.confirmed) and let listeners decide what to do.
A different layout per service. The pattern only pays off if it is applied everywhere. A generator helps. In ZENLEAF we describe a service in JSON, and the generator writes its folder with the eight files and basic create, read, update and delete endpoints. Every service starts the same way.
How this fits deployment
Because services share nothing but core/ and the event channel, moving one into its own container is mostly a packaging change. Our guide to deploying AI microservices with Docker and Kubernetes covers the container side. The structure in this post is what keeps that move small.
Frequently Asked Questions
What is the best folder structure for a FastAPI project?
For a business backend, group code by service rather than by type. Give each service its own folder with the same files for models, schemas, events, dependencies, service steps, repository, business rules and router. Keep shared platform code such as configuration, database setup, security and logging in a separate core folder that every service imports.
Should a FastAPI project use the repository pattern?
For anything beyond a small app, yes. A repository keeps SQL and ORM calls in one place per service, which makes service logic testable with an in-memory fake and keeps database changes contained. It adds a thin layer of code, and that cost is repaid the first time you change a query or a table.
Where should business logic go in FastAPI?
Not in the route function. Put the steps of each use case in a service class and the business rules in plain functions in their own file. The route function should validate input, call the service and return the response. Rules written as plain functions can be read by non-engineers and tested without a database.
Do I need separate deployments to use a microservices structure?
No. Start with several service folders inside one FastAPI application. Each service still owns its data and talks to others through events and defined interfaces. Split a service into its own deployment only when it needs to scale, release or fail independently of the rest.
Build It With Andolasoft
This is the structure we use on every Python backend we deliver. ZENLEAF is our FastAPI framework. It gives each project the same eight-file service pattern and a generator that writes new service folders from a JSON description. Login, single sign-on, roles, logging, events, workflows and scheduling are shared services. Our engineers then write your business rules on top. After handover, you own the code built for your project. It sits under our Python development and custom software work, and our Python developers can join your team to apply the same pattern to a codebase you already run.
If you are starting a FastAPI backend, or your current one has outgrown its layout, talk to us. Book a 30-minute call, describe the problem, and we will tell you how we would structure it and what a first release could cover.
