| 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/
Core Technologies
- Python: 3.12+
- Package Manager: uv (required)
- Framework: FastAPI
- ORM: SQLAlchemy 2.0+ (async)
- Database: PostgreSQL with asyncpg
- Validation: Pydantic v2
- Configuration: pydantic-settings
- Migrations: Alembic (async)
- Pagination: fastapi-pagination
- Filtering: fastapi-filter
- Linting: ruff
Key Design Decisions
1. UUID Primary Keys
All models use UUID primary keys for distributed system compatibility.
2. UTC Timestamps
All timestamps are timezone-aware UTC using DateTime(timezone=True).
3. Soft Delete
Models support soft delete via deleted_at timestamp. Queries automatically filter deleted records.
4. Entity-Based Organization
Each entity (e.g., items, users) has its own folder containing all related files.
5. Generic Repository Pattern
Type-safe repositories using Python generics: Repository[ModelType, CreateSchema, UpdateSchema]
6. PostgreSQL-Specific Features
Bulk operations use PostgreSQL's ON CONFLICT for upserts.
Data Flow
Request
โ
Middleware (Correlation ID)
โ
Router
โโโ Validates request (Pydantic)
โโโ Extracts filter params (fastapi-filter)
โโโ Calls Service
โ
Service
โโโ Applies business logic
โโโ Calls Repository
โ
Repository
โโโ Executes SQL (SQLAlchemy)
โโโ Returns model instances
โ
Database
Error Handling
All errors return a consistent JSON structure:
{
"detail": "Resource not found",
"error_code": "NOT_FOUND",
"correlation_id": "uuid",
"timestamp": "2025-01-05T12:00:00Z"
}
Available Skills
Load specific skills for detailed implementation:
| Skill | Purpose |
|---|
fastapi-project-setup | Initialize project with uv, dependencies, ruff |
fastapi-database-setup | Async SQLAlchemy engine and session |
fastapi-core-models | Base model and mixins |
fastapi-core-schemas | Base Pydantic schemas |
fastapi-core-repository | Abstract repository interface |
fastapi-postgres-repository | PostgreSQL repository implementation |
fastapi-core-service | Base service class |
fastapi-exceptions | Custom exceptions and handlers |
fastapi-logging | Structured logging with correlation IDs |
fastapi-app-factory | FastAPI app factory and main.py |
fastapi-alembic-setup | Async Alembic configuration |
fastapi-entity | Create a new entity with all files |
fastapi-testing | Test configuration and fixtures |
Best Practices
- SQL Only in Repositories: Never write SQLAlchemy queries outside repository layer
- Type Everything: Use type hints everywhere, enable strict mypy
- Async All The Way: Use async/await consistently
- Dependency Injection: Use FastAPI's
Depends() for all dependencies
- Validate Early: Use Pydantic schemas at API boundary
- Log with Context: Always include correlation_id in logs
- Handle Errors Gracefully: Use custom exceptions, never raise generic ones