← Back to FastAPI, page 3

fastapi-0046 · Hard senior

How would you structure a large FastAPI codebase, and how do you keep routers, services and persistence separate and testable?

Organise by feature (domain packages such as students, fees, auth), and inside each feature separate the HTTP layer (router, request and response schemas), the service layer (business rules, no FastAPI imports) and the persistence layer (SQLAlchemy models and queries). Dependencies wire the layers together, so tests can replace storage with fakes. Keep transactions at the service boundary, domain exceptions mapped by handlers, and configuration in one settings object.

Full answer

A flat main.py with 80 endpoints and SQL inside route functions becomes impossible to test and change. The usual remedy is layering plus feature folders.

Layout

app/ main.py # app factory, lifespan, include routers core/ # settings, security, logging, db session students/ router.py # HTTP only: parse input, call service, return schema schemas.py # Pydantic request/response models service.py # business rules, plain Python repository.py # SQLAlchemy queries models.py # ORM models exceptions.py fees/ ... tests/

Responsibilities

  • Router: validation via schemas, status codes, dependencies for auth. No business rules, no SQL.
  • Service: rules such as "a student cannot enrol in two overlapping courses". Takes plain arguments and a repository, raises domain exceptions, knows nothing about HTTP.
  • Repository: all queries for one aggregate. Returns ORM objects or domain objects.
  • Dependencies assemble them: get_student_service(db=Depends(get_db)).

Why this helps

  • Unit tests call the service with a fake repository (no database, no HTTP).
  • Integration tests hit routers with TestClient and a test database.
  • Services are reusable from CLI scripts, background workers and other routers.
  • A change in storage affects one layer.

Judgement calls

  • Do not build layers for trivial CRUD; a small app can have routers calling the session directly. Add the service layer when rules appear.
  • Avoid circular imports between features: depend on interfaces or pass IDs; shared concepts go in core.
  • The unit of work: one request, one session, one commit at the service boundary.
  • Use an app factory (create_app(settings)) so tests build isolated apps.
  • Keep Pydantic schemas separate from ORM models; they change for different reasons.
python
from typing import Annotated, Protocol

from fastapi import APIRouter, Depends, FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel


# students/exceptions.py
class AlreadyEnrolled(Exception):
    pass


# students/service.py  (no FastAPI imports)
class EnrolmentRepo(Protocol):
    def courses_of(self, roll_no: str) -> set[str]: ...
    def add(self, roll_no: str, course: str) -> None: ...


class EnrolmentService:
    def __init__(self, repo: EnrolmentRepo):
        self.repo = repo

    def enrol(self, roll_no: str, course: str) -> list[str]:
        if course in self.repo.courses_of(roll_no):
            raise AlreadyEnrolled(f"{roll_no} is already in {course}")
        self.repo.add(roll_no, course)
        return sorted(self.repo.courses_of(roll_no))


# students/repository.py
class InMemoryRepo:
    def __init__(self):
        self.data: dict[str, set[str]] = {}

    def courses_of(self, roll_no):
        return set(self.data.get(roll_no, ()))

    def add(self, roll_no, course):
        self.data.setdefault(roll_no, set()).add(course)


_repo = InMemoryRepo()


def get_service() -> EnrolmentService:                 # dependency wires the layers together
    return EnrolmentService(_repo)


# students/schemas.py and router.py
class EnrolIn(BaseModel):
    course: str


router = APIRouter(prefix="/students", tags=["students"])


@router.post("/{roll_no}/enrol")
def enrol(roll_no: str, body: EnrolIn, service: Annotated[EnrolmentService, Depends(get_service)]):
    return {"roll_no": roll_no, "courses": service.enrol(roll_no, body.course)}


# main.py
def create_app() -> FastAPI:
    app = FastAPI()
    app.include_router(router)

    @app.exception_handler(AlreadyEnrolled)
    async def already(request: Request, exc: AlreadyEnrolled):
        return JSONResponse(status_code=409, content={"detail": str(exc)})

    return app


app = create_app()
c = TestClient(app)
print(c.post("/students/BCA-17/enrol", json={"course": "DBMS"}).json())
print(c.post("/students/BCA-17/enrol", json={"course": "DBMS"}).status_code)

fake = InMemoryRepo()                                  # unit test: no HTTP, no database
print(EnrolmentService(fake).enrol("X-1", "Maths"))

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'roll_no': 'BCA-17', 'courses': ['DBMS']} 409 ['Maths']

Key points

  • Feature packages with router, schemas, service, repository
  • Routers handle HTTP only; services hold rules and know no HTTP
  • Dependencies wire layers; tests swap fakes
  • Commit at the service boundary
  • Do not over-layer trivial CRUD

Common mistakes

  • Writing SQL and business rules inside route functions
  • Importing FastAPI types into the service layer, tying rules to HTTP
  • Building repository, service and interface layers for trivial CRUD
  • Sharing ORM models directly as API schemas
  • Circular imports between feature packages

Follow-ups

  • Where do transactions begin and end in this design?
  • How would you test the service without a database?
  • How do you share code between features without circular imports?

Tips

  • Draw the folder layout
  • State each layer's responsibility and what it must not know
  • Mention when not to layer