| name | fastapi-backend-overview |
| description | Overview and guidelines for FastAPI 3-layer architecture with async SQLAlchemy, Pydantic v2, and best practices |
FastAPI Backend Stack - Overview & Guidelines
Architecture Overview
This stack follows a 3-layer architecture with strict separation of concerns:
Router (API Layer) → Service (Business Logic) → Repository (Data Access) → Database
Layer Responsibilities
| Layer | Responsibility | SQL Allowed | Imports |
|---|
| Router | HTTP handling, request validation, dependency injection | NO | Service, Schemas, Filters |
| Service | Business logic, orchestration, validation rules | NO | Repository, Schemas |
| Repository | Data access, SQL queries, database operations | YES | Models, SQLAlchemy |
Project Structure (Entity-Based)
project/
├── pyproject.toml
├── .env.example
├── .python-version # 3.12
├── ruff.toml
├── alembic.ini
├── alembic/
│ ├── env.py
│ ├── script.py.mako
│ └── versions/
├── src/
│ └── app/
│ ├── __init__.py
│ ├── main.py # App factory
│ ├── config.py # pydantic-settings
│ ├── database.py # Async SQLAlchemy
│ ├── dependencies.py # Shared dependencies (get_db)
│ ├── exceptions.py # Custom exceptions
│ ├── exception_handlers.py
│ ├── logging.py # Structured logging
│ ├── middleware/
│ │ ├── __init__.py
│ │ └── correlation_id.py
│ ├── core/ # Abstract base classes
│ │ ├── __init__.py
│ │ ├── models.py # Base model, mixins
│ │ ├── schemas.py # Base schemas
│ │ ├── repository.py # AbstractRepository
│ │ └── service.py # BaseService
│ ├── common/
│ │ ├── __init__.py
│ │ └── postgres_repository.py
│ ├── api/
│ │ ├── __init__.py
│ │ └── v1/
│ │ ├── __init__.py
│ │ └── router.py
│ └── {entity}/ # Per-entity folders
│ ├── __init__.py
│ ├── models.py
│ ├── schemas.py
│ ├── repository.py
│ ├── service.py
│ ├── router.py
│ ├── dependencies.py
│ └── filters.py
└── tests/
├── __init__.py
├── conftest.py
└── api/v1/