Skip to content

Lesson 52 of 59Production

Structuring a FastAPI Project

Lay out a FastAPI codebase by layer or by feature, keep schemas and ORM models apart, avoid circular imports, and manage config with pydantic-settings.

25 min read0/6 questions

You have now built every part of a backend, and seen how Django and Flask do the same jobs. This last unit is about running a FastAPI service for real, starting with how its code is organised. Every FastAPI tutorial fits in one main.py. Every real API outgrows it within weeks: routes, models, SQL, auth and config tangled together, and nobody can find anything. A clear structure makes features easy to add, tests easy to write, and a take-home assignment easy for a reviewer to read. This lesson gives you a layout used by many production teams and the reasoning behind each folder.

A production layout

todo-api
  • todo-api/
  • app/
  • __init__.py
  • main.pycreates the FastAPI app, includes routers, middleware
  • api/
  • __init__.py
  • deps.pyshared dependencies: get_db, get_current_user
  • routes/
  • __init__.py
  • auth.pyPOST /token, /refresh
  • todos.py/todos endpoints
  • users.py/users endpoints
  • core/
  • config.pySettings class (pydantic-settings)
  • security.pypassword hashing, JWT helpers
  • db/
  • session.pyengine, SessionLocal, get_db
  • models/
  • __init__.py
  • todo.pySQLAlchemy table classes
  • user.py
  • schemas/
  • todo.pyPydantic TodoCreate, TodoRead, TodoUpdate
  • user.py
  • services/
  • todo_service.pybusiness rules
  • repositories/
  • todo_repository.pyall SQL for todos
  • tests/
  • conftest.pyfixtures: test db, client, users
  • factories.py
  • test_todos.py
  • alembic/
  • versions/migration scripts
  • env.py
  • alembic.ini
  • pyproject.tomldependencies and tool config
  • uv.lock
  • .envlocal secrets, never committed
  • .env.examplethe variable names, committed
  • Dockerfile

Some teams group by feature instead (app/todos/ holding that feature's router, schemas, service and repository). Both work. Grouping by layer is easier to learn; grouping by feature scales better once there are dozens of features. What matters is that each kind of code has exactly one obvious home.

Layer-first or feature-first

The tree above is layer-first: one folder per kind of code. To add "invoices" you touch routes/, schemas/, models/, services/ and repositories/, five folders for one feature. With five features that is fine. With forty, each folder holds forty files, and a change to one feature is spread across the whole tree in review.

Feature-first (also called by domain, or vertical slices) turns it round: one folder per business area, each with the same small set of files inside.

shop-api (feature-first)
  • shop-api/
  • app/
  • main.pycreates the app, includes each feature's router
  • core/
  • config.pySettings
  • db.pyengine, session, get_db
  • security.pyhashing, tokens
  • errors.pyAppError, NotFound, Conflict
  • users/
  • router.py/users endpoints
  • schemas.pyUserCreate, UserRead
  • models.pyUser table
  • service.pysign-up rules
  • repository.py
  • orders/
  • router.py
  • schemas.py
  • models.pyOrder, OrderItem tables
  • service.pycheckout, refunds
  • repository.py
  • events.pyOrderPlaced, published for other features
  • billing/
  • router.py
  • service.py
  • stripe_client.pyadapter for the external API
  • tests/
  • users/
  • test_signup.py
  • orders/
  • test_checkout.py

What you gain: a feature is one folder, so a pull request for "refunds" touches orders/ and its tests, and a new teammate can own billing/ without learning the rest. Deleting a feature means deleting a folder. It also makes boundaries visible: when billing/service.py imports orders.models.Order directly, that is a coupling you can see in an import line and question in review.

What you pay: some code is genuinely shared (config, database session, security, error types), and it needs a home that is not a feature. That is core/ here. The temptation is to let core/ grow into a junk drawer, so keep it to infrastructure, never business rules.

A pragmatic path many teams take: start layer-first while the app is small, and move to feature-first when the layer folders pass a dozen files each. The layering rule from the next section applies inside each feature folder either way: router calls service, service calls repository. Feature-first changes where files live, not how they depend on each other.

The layers and their jobs

The folders map to layers. A request flows down through them and the result flows back up.

A request through the layers
  1. Route (api/routes)HTTP only: parse input, call a service, map errors to status codes
  2. Service (services)Business rules: limits, permissions, workflows. No HTTP, no SQL
  3. Repository (repositories)Data access: every query for one model lives here
  4. Models and session (models, db)SQLAlchemy tables, engine, transactions
  5. DatabasePostgreSQL

PATCH /todos/7 arrives. The route validates the body with TodoUpdate, gets the user and session from dependencies, and calls todo_service.update(...).

1/5

Each layer only calls the one below it. Routes never write SQL; repositories never raise HTTPException; services never import Request. That one rule is what makes the code testable: you can unit-test a service with a fake repository, and swap a repository's database without touching business rules.

app/services/todo_service.py
from app.errors import Conflict, NotFound
from app.repositories.todo_repository import TodoRepository
from app.schemas.todo import TodoUpdate
 
MAX_OPEN_TODOS = 500
 
 
class TodoService:
    def __init__(self, repo: TodoRepository):
        self.repo = repo
 
    def update(self, user_id: int, todo_id: int, changes: TodoUpdate):
        todo = self.repo.get_for_user(user_id, todo_id)
        if todo is None:
            raise NotFound("Todo not found")
        data = changes.model_dump(exclude_unset=True)
        if "title" in data and self.repo.title_exists(user_id, data["title"], exclude_id=todo_id):
            raise Conflict("You already have a todo with that title")
        return self.repo.update(todo, data)
app/api/routes/todos.py
from fastapi import APIRouter
 
from app.api.deps import CurrentUser, TodoServiceDep
from app.schemas.todo import TodoRead, TodoUpdate
 
router = APIRouter(prefix="/todos", tags=["todos"])
 
 
@router.patch("/{todo_id}")
def update_todo(todo_id: int, body: TodoUpdate, user: CurrentUser, service: TodoServiceDep) -> TodoRead:
    return service.update(user.id, todo_id, body)

The route is three lines because everything else has a home. TodoServiceDep is a dependency that builds a TodoService with a repository bound to the request's session.

Match the pairs0/5 matched

Where does each piece of code belong?

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

Three kinds of model, and why they differ

Beginners often ask why there is a models/todo.py and a schemas/todo.py that look almost the same. They describe different things, and they change for different reasons.

  • Pydantic schemas (schemas/) describe the API contract: what a client may send (TodoCreate, TodoUpdate) and what it gets back (TodoRead). They change when the API changes, and every change is visible to clients. TodoCreate has no id and no owner_id, because clients must not choose those. TodoRead has no password_hash equivalent, because clients must never see it.
  • ORM models (models/) describe the database tables: columns, types, indexes, foreign keys, relationships. They change with migrations. A column can exist for internal reasons (deleted_at, search_vector, stripe_customer_id) without ever appearing in the API.
  • Domain models are plain Python classes or dataclasses for business logic that is neither a table nor a payload: a Money value with a currency, a PriceQuote built from several tables, an OrderTotal with tax rules. Small apps do not need a separate layer of these. Reach for them when a service is juggling dicts and tuples to represent a concept the business talks about.

Keeping schemas and ORM models separate is the important part. If you return ORM objects straight from routes with no response model, adding a sensitive column to the table leaks it in the API the same day. If you accept ORM objects as request bodies, a client can set is_admin. Separate classes, plus model_config = ConfigDict(from_attributes=True) on the read schema so it can be built from an ORM object, make both mistakes impossible.

SQLModel, by FastAPI's author, lets one class be both a table and a Pydantic model, which removes duplication in small apps. Even there, the documented pattern is a shared base plus separate Create, Update and Public classes, and only the table=True class maps to the database. Note that table=True models do not validate on construction the way plain Pydantic models do, which is one more reason to validate input with the separate Create class.

Match the pairs0/4 matched

Which kind of model should hold each thing?

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

Avoiding circular imports

Sooner or later, someone writes from app.orders.service import ... inside users/service.py while orders/service.py already imports from users/service.py. Python starts running users, hits the import of orders, starts running orders, which asks for a name from the half-finished users module, and fails:

Pythoncircular.py
import importlibimport sysimport tempfilefrom pathlib import Path root = Path(tempfile.mkdtemp())sys.path.insert(0, str(root))pkg = root / "shop"pkg.mkdir()(pkg / "__init__.py").write_text("") # users/service imports orders/service, and orders/service imports users/service.(pkg / "users.py").write_text( "from shop.orders import count_orders\n" "def user_summary(user_id):\n" " return {'id': user_id, 'orders': count_orders(user_id)}\n")(pkg / "orders.py").write_text( "from shop.users import user_summary\n" "def count_orders(user_id):\n" " return 3\n") try: importlib.import_module("shop.users")except ImportError as err: print("ImportError:", str(err).split(" (")[0]) # The fix: move the shared piece down a layer, so imports only point one way.for name in ["shop.users", "shop.orders"]: sys.modules.pop(name, None)(pkg / "orders.py").write_text( "def count_orders(user_id):\n" " return 3\n")importlib.invalidate_caches()users = importlib.import_module("shop.users")print(users.user_summary(7))
Output
Press Run (⌘ Enter) to see what happens.

The error message even says "partially initialized module". Three fixes, in order of preference:

  • Make dependencies point one way. Within a feature: router, then service, then repository, then models. Never upwards. Across features, decide which is lower level (orders may know about users; users must not know about orders) and move shared pieces down into core/ or into the lower feature. A cycle is usually a design smell telling you a function sits in the wrong module.
  • Communicate upwards with events or callbacks. If users needs to react when an order is placed, orders publishes an OrderPlaced event and users subscribes, wired up in main.py. Neither module imports the other.
  • Type-only imports. When the only reason for the import is a type hint, guard it with if TYPE_CHECKING: and keep annotations lazy. The type checker sees the import; at runtime it never happens. In Python 3.14, annotations are evaluated lazily by default; on 3.12 and 3.13 add from __future__ import annotations or quote the type.
app/orders/service.py
from typing import TYPE_CHECKING
 
if TYPE_CHECKING:
    from app.users.models import User   # for the type checker only
 
 
def place_order(user: "User", items: list[int]) -> int:
    ...

Two tempting fixes are worse. Moving the import inside the function works but hides the cycle, so it grows. Merging the two modules into one large file removes the error and the structure with it. Tools like import-linter let you write the allowed directions down as a contract ("app.users must not import app.orders") and fail CI when someone breaks it, which is how larger teams keep the layering honest.

Quick check
users/service.py imports orders/service.py only to annotate a parameter as Order, and this creates an import cycle. What is the cleanest fix?
Need a nudge? A hint rules out a wrong answer.

The layers, runnable

Here is the same layering in plain Python. Notice how the service is tested with a different repository without any change to its code.

Pythonlayers.py
class NotFound(Exception): pass class InMemoryTodoRepo: # repository: data access only def __init__(self, rows): self.rows = {r["id"]: dict(r) for r in rows} def get_for_user(self, user_id, todo_id): row = self.rows.get(todo_id) return row if row and row["user_id"] == user_id else None def save(self, row): self.rows[row["id"]] = row return row class TodoService: # service: business rules only def __init__(self, repo): self.repo = repo def complete(self, user_id, todo_id): todo = self.repo.get_for_user(user_id, todo_id) if todo is None: raise NotFound(todo_id) todo["done"] = True return self.repo.save(todo) def complete_route(todo_id, user_id, service): # route: HTTP translation only try: return 200, service.complete(user_id, todo_id) except NotFound: return 404, {"detail": "Todo not found"} service = TodoService(InMemoryTodoRepo([{"id": 7, "user_id": 1, "title": "Ship", "done": False}]))print(complete_route(7, user_id=1, service=service))print(complete_route(7, user_id=2, service=service))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Product says: "A todo cannot be marked done if it has unfinished subtasks." Where should that check live?
Need a nudge? A hint rules out a wrong answer.

Splitting routes with APIRouter

APIRouter is a mini app for one group of routes. main.py assembles them:

app/main.py
from contextlib import asynccontextmanager
 
from fastapi import FastAPI
 
from app.api.routes import auth, todos, users
from app.core.config import get_settings
from app.db.session import engine
 
settings = get_settings()
 
 
@asynccontextmanager
async def lifespan(app: FastAPI):
    yield                     # the app serves requests while paused here
    engine.dispose()          # on shutdown: close database connections
 
 
app = FastAPI(title=settings.app_name, lifespan=lifespan)
app.include_router(auth.router, prefix="/api/v1")
app.include_router(todos.router, prefix="/api/v1")
app.include_router(users.router, prefix="/api/v1")

prefix and tags set on the router apply to all its routes (tags groups them in /docs). A router can also take dependencies=[Depends(require_admin)] to protect a whole group. The lifespan function runs setup before the first request and cleanup at shutdown.

A tour of the official full-stack template

FastAPI's author maintains full-stack-fastapi-template on GitHub: a FastAPI backend, a React frontend, PostgreSQL, Docker Compose, tests and CI, all wired together. Teams copy it as a starting point, and interviewers recognise it, so it is worth knowing how its backend is laid out. Below is the shape of the backend at the time of writing; files move between releases, so check the repository for the current version.

full-stack-fastapi-template (backend, simplified)
  • backend/
  • app/
  • main.pycreates the app, CORS, includes the API router
  • models.pySQLModel tables and API schemas in one file
  • crud.pycreate_user, authenticate, ... as functions
  • utils.pyemail helpers, token generation
  • api/
  • main.pyapi_router: includes every route module
  • deps.pySessionDep, CurrentUser, get_current_active_superuser
  • routes/
  • login.pytoken, password recovery
  • users.py
  • items.py
  • utils.pyhealth check, test email
  • core/
  • config.pySettings with pydantic-settings
  • db.pyengine, init_db for the first superuser
  • security.pypassword hashing, create_access_token
  • alembic/migrations
  • email-templates/
  • tests/api, crud and script tests, conftest.py
  • scripts/prestart, test and lint scripts
  • pyproject.toml
  • Dockerfile
  • docker-compose.ymldb, backend, frontend and helper services
  • frontend/React + TypeScript, client generated from OpenAPI

Things to notice, and to judge rather than copy:

  • Layer-first, kept flat. There is no separate service or repository layer. crud.py holds data access functions and routes call them directly. For a template with users and items, that is the right amount of structure; for a product with real business rules, you would add the service layer this lesson describes.
  • api/deps.py with Annotated aliases. SessionDep and CurrentUser are exactly the pattern from Dependency Injection: define the dependency once, and every route signature stays short.
  • One models.py with SQLModel. Table classes and the Create, Update and Public schemas sit together, sharing base classes. That works at this size and becomes a long file quickly; splitting it per feature is a common first change.
  • Settings validated at startup, including checks that refuse placeholder secrets outside local development.
  • The frontend client is generated from the backend's OpenAPI schema, so a backend change that breaks the frontend shows up as a type error.

Reading a well-known template critically, "what would I keep, what would I change at ten times the size", is a good exercise before a system design or take-home interview.

Config and secrets with pydantic-settings

Configuration changes between environments (your laptop, CI, staging, production); code does not. The twelve-factor convention is to read config from environment variables. pydantic-settings turns them into a typed, validated object, using the same Pydantic you already know.

app/core/config.py
from functools import lru_cache
 
from pydantic import PostgresDsn, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
 
 
class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_file=".env", extra="ignore")
 
    app_name: str = "Todo API"
    debug: bool = False
    database_url: PostgresDsn                 # required: startup fails without it
    secret_key: SecretStr                     # hidden when printed or logged
    access_token_minutes: int = 15
    allowed_origins: list[str] = []           # from JSON: '["https://app.example.com"]'
 
 
@lru_cache
def get_settings() -> Settings:
    return Settings()
.env.example
DATABASE_URL=postgresql+psycopg://app:app@localhost:5432/todosSECRET_KEY=generate-with-python-c-import-secrets-print-secrets-token-urlsafe-32DEBUG=true

Environment variable names match fields case-insensitively, values are converted and validated (DEBUG=true becomes True), and a missing required value stops the app at startup with a clear error, instead of crashing on the first request that needs it. @lru_cache builds the settings once. Because get_settings is a function, tests can override it with app.dependency_overrides like any dependency.

SecretStr prints as **********, so a stray print(settings) or an error report cannot leak the key; call .get_secret_value() where you really need it.

Predict the outputPython

A tiny imitation of SecretStr. What does this print?

class SecretStr:
  def __init__(self, value):
      self._value = value
  def __repr__(self):
      return "SecretStr('**********')"
  def get_secret_value(self):
      return self._value

key = SecretStr("hunter2")
print(key, len(key.get_secret_value()))
Need a nudge? Hints walk you through it.
Quick check
Which files belong in git?
Need a nudge? A hint rules out a wrong answer.

Practice

ChallengeMedium

Settings from the environment

Imitate pydantic-settings. Write load_settings(env) that reads a dict of environment variables into typed settings.

FieldTypeDefaultRules
database_urlstrrequired
secret_keystrrequiredat least 32 characters
debugboolFalsetrue/false/1/0/yes/no/on/off, any case
portint8000between 1 and 65535
allowed_originslist[str][]comma-separated; strip spaces; drop empty items
  • Variable names match fields case-insensitively (DATABASE_URL or database_url). Ignore unknown variables.
  • An empty value counts as not set.
  • Return {"settings": {...all five fields...}}, or {"errors": [...]} with every problem in the table's field order, using exactly these messages: "<field>: missing", "secret_key: too short", "debug: not a valid bool", "port: not a valid int", "port: out of range".
load_settings({"DATABASE_URL": "postgresql://db/todos", "SECRET_KEY": "x" * 32, "PORT": "9000"})
# {"settings": {"database_url": "postgresql://db/todos", "secret_key": "xxxx...", "debug": False,
#               "port": 9000, "allowed_origins": []}}
Python
def load_settings(env: dict) -> dict: # Lowercase the keys, then read each field in order, collecting errors. pass
Key terms
APIRouter
A group of routes with a shared prefix, tags and dependencies, included into the app with include_router.
service layer
Holds business rules. Called by routes and jobs; knows nothing about HTTP or SQL details.
repository
Holds all data access for a model, so queries live in one place and can be faked in tests.
pydantic-settings
Reads environment variables (and .env) into a typed, validated Settings object.
SecretStr
A string type that masks its value when printed, so secrets do not leak into logs.
lifespan
An async context manager passed to FastAPI(lifespan=...) for startup and shutdown work.
feature-first layout
One folder per business area (users, orders, billing), each holding its own router, schemas, models and service.
circular import
Two modules importing each other, so one is used before it has finished loading. Fixed by making dependencies point one way.
TYPE_CHECKING
A constant that is False at runtime and True for type checkers, used to import names only for type hints.