Skip to content

keanallen/fastapi-clean-architecture

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

FastAPI Clean Architecture Starter

A clean architecture starter template for FastAPI applications with PostgreSQL database, authentication, and proper project structure.

πŸ—οΈ Architecture Overview

This project follows Clean Architecture principles with clear separation of concerns:

app/
β”œβ”€β”€ main.py                 # FastAPI application entry point
β”œβ”€β”€ api/                    # API layer (routes, controllers)
β”‚   β”œβ”€β”€ deps.py            # Dependency injection
β”‚   └── v1/                # API version 1
β”‚       β”œβ”€β”€ auth_route.py  # Authentication endpoints
β”‚       β”œβ”€β”€ division_route.py # Division management endpoints
β”‚       └── user_route.py  # User management endpoints
β”œβ”€β”€ core/                   # Core application configuration
β”‚   β”œβ”€β”€ config.py          # Application settings
β”‚   └── security.py        # Security utilities
β”œβ”€β”€ db/                     # Database layer
β”‚   β”œβ”€β”€ base.py            # Database base classes
β”‚   └── session.py         # Database session management
β”œβ”€β”€ models/                 # Data models (SQLAlchemy)
β”‚   └── user.py            # User model
β”œβ”€β”€ repositories/           # Data access layer
β”‚   β”œβ”€β”€ division_repository.py
β”‚   └── user_repository.py
β”œβ”€β”€ schemas/                # Pydantic schemas (DTOs)
β”‚   β”œβ”€β”€ division_schema.py
β”‚   └── user_schema.py
β”œβ”€β”€ services/               # Business logic layer
β”‚   β”œβ”€β”€ division_service.py
β”‚   └── user_service.py
└── utils/                  # Utility functions
    β”œβ”€β”€ encryption.py
    └── http_error_response.py

✨ Features

  • Clean Architecture: Proper separation of concerns with layers
  • FastAPI: Modern, fast web framework for building APIs
  • PostgreSQL: Robust relational database
  • SQLAlchemy 2.0: Modern Python SQL toolkit and ORM
  • Alembic: Database migration tool
  • JWT Authentication: Secure authentication system
  • Pydantic: Data validation using Python type annotations
  • Docker: Containerized development environment
  • pgAdmin: Database administration tool

πŸš€ Quick Start

Prerequisites

  • Python 3.9+
  • Docker and Docker Compose
  • Git

1. Clone the Repository

git clone <repository-url>
cd fastapi-clean-starter

2. Environment Setup

Create a .env file in the root directory:

# Database
DATABASE_URL=postgresql://username:password@localhost:5432/db_name

# JWT Configuration
JWT_SECRET_KEY=your-super-secret-jwt-key-here
JWT_ALGORITHM=HS256
JWT_EXPIRATION_MINUTES=60

# Application
PROJECT_NAME=DTRAS API

3. Start the Database

docker-compose up -d db pgadmin

4. Install Dependencies

pip install -r requirements.txt

5. Initialize Alembic (First Time Only)

If this is a fresh project setup and Alembic hasn't been initialized:

# Initialize Alembic (creates alembic/ directory and alembic.ini)
alembic init alembic

# Edit alembic.ini to set your database URL or use environment variable
# sqlalchemy.url = ???

6. Run Database Migrations

alembic upgrade head

7. Start the Application

uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

The API will be available at http://localhost:8000

πŸ“š API Documentation

Once the application is running, you can access:

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc
  • OpenAPI JSON: http://localhost:8000/openapi.json

πŸ—„οΈ Database Management

Alembic Setup and Configuration

This project uses Alembic for database migrations. The configuration is already set up in alembic.ini and alembic/env.py.

Initial Setup (for new projects)

  1. Initialize Alembic (already done in this starter):
alembic init alembic
  1. Configure Database URL in alembic.ini:
# Option 1: Direct URL in alembic.ini
sqlalchemy.url = postgresql://username:password@localhost:5432/dbname

# Option 2: Use environment variable (recommended)
# sqlalchemy.url = 
  1. Configure env.py to use your models (already configured):
# In alembic/env.py
from app.db.base import Base  # Import your Base
target_metadata = Base.metadata

Database Migrations

Creating Migrations

Auto-generate migration from model changes:

# Generate migration automatically by comparing models to database
alembic revision --autogenerate -m "Add user table"

# For more complex changes, create empty migration
alembic revision -m "Custom migration description"

Best Practices for Migrations:

  • Always review auto-generated migrations before applying
  • Use descriptive migration messages
  • Test migrations on a copy of production data
  • Keep migrations small and focused

Applying Migrations

# Apply all pending migrations
alembic upgrade head

# Apply migrations up to a specific revision
alembic upgrade ae1027a6acf

# Apply only the next migration
alembic upgrade +1

Migration History and Information

# Show current migration status
alembic current

# Show migration history
alembic history

# Show detailed history with descriptions
alembic history --verbose

# Show pending migrations
alembic show head

Rolling Back Migrations

# Rollback one migration
alembic downgrade -1

# Rollback to a specific revision
alembic downgrade ae1027a6acf

# Rollback all migrations (use with caution!)
alembic downgrade base

Working with Branches (Advanced)

# Create a branch
alembic revision --branch-label feature_branch -m "Feature branch migration"

# Merge branches
alembic merge -m "Merge feature branch" head1 head2

# Show branches
alembic branches

pgAdmin Access

  • URL: http://localhost:8080
  • Email: admin@admin.com
  • Password: admin

Common Alembic Issues and Solutions

Issue: "Can't locate revision identified by..."

Solution: Check if you're in the correct directory and the alembic version table exists:

# Stamp the database with current revision if version table is missing
alembic stamp head

Issue: Auto-generation not detecting changes

Solutions:

  1. Ensure models are properly imported in alembic/env.py
  2. Check that target_metadata is set correctly
  3. Verify database connection is working

Issue: Migration conflicts

Solution: Create a merge migration:

alembic merge -m "Merge conflicting revisions" revision1 revision2

πŸ› οΈ Development

Project Structure Explanation

  • app/main.py: Application entry point with FastAPI instance and route registration
  • app/api/: API layer containing route handlers and dependencies
  • app/core/: Core application configuration and security utilities
  • app/db/: Database configuration and session management
  • app/models/: SQLAlchemy ORM models
  • app/repositories/: Data access layer abstracting database operations
  • app/schemas/: Pydantic models for request/response validation
  • app/services/: Business logic layer containing application use cases
  • app/utils/: Utility functions and helpers

Adding New Features

  1. Model: Define database model in app/models/
  2. Schema: Create Pydantic schemas in app/schemas/
  3. Repository: Implement data access in app/repositories/
  4. Service: Add business logic in app/services/
  5. Route: Create API endpoints in app/api/v1/
  6. Migration: Generate and apply migration with Alembic

Example: Adding a New Entity

Let's say you want to add a Product entity:

  1. Create the model (app/models/product.py):
from sqlalchemy import Column, Integer, String, Numeric
from app.db.base import Base

class Product(Base):
    __tablename__ = "products"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, nullable=False)
    price = Column(Numeric(10, 2), nullable=False)
  1. Import in base.py (app/db/base.py):
from app.models.product import Product  # Add this import
  1. Generate migration:
alembic revision --autogenerate -m "Add products table"
alembic upgrade head
  1. Create schemas, repository, service, and routes following the existing patterns.

Code Style

Follow these conventions:

  • Use type hints for all function parameters and return types
  • Follow PEP 8 style guidelines
  • Use descriptive variable and function names
  • Add docstrings to all public functions and classes

πŸ”’ Authentication

The application includes JWT-based authentication with the following endpoints:

  • POST /api/v1/auth/login - User login
  • POST /api/v1/auth/register - User registration
  • GET /api/v1/auth/me - Get current user info

πŸ“Š Health Check

The application includes a health check endpoint:

  • GET /health - Returns application status

🐳 Docker

Full Development Environment

# Start all services (database, pgAdmin, and application)
docker-compose up -d

# Stop all services
docker-compose down

# View logs
docker-compose logs -f

Database Only

# Start only database and pgAdmin
docker-compose up -d db pgadmin

πŸ§ͺ Testing

# Run tests (when implemented)
pytest

# Run tests with coverage
pytest --cov=app

πŸ“¦ Dependencies

Main dependencies include:

  • fastapi: Web framework
  • uvicorn: ASGI server
  • sqlalchemy: ORM
  • alembic: Database migrations
  • pydantic: Data validation
  • python-jose: JWT handling
  • passlib: Password hashing
  • asyncpg: PostgreSQL driver

See requirements.txt for complete list.

πŸš€ Deployment

Production Considerations

  1. Use environment variables for all configuration
  2. Enable HTTPS in production
  3. Use a production ASGI server like Gunicorn with Uvicorn workers
  4. Set up proper logging and monitoring
  5. Use a reverse proxy like Nginx
  6. Implement rate limiting
  7. Set up database connection pooling

Example Production Command

gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

If you encounter any issues or have questions, please:

  1. Check the existing issues in the repository
  2. Create a new issue with detailed description
  3. Include error logs and steps to reproduce

πŸ”„ Changelog

See CHANGELOG.md for a detailed history of changes.

About

A FastAPI base template trying to follow Clean Architecture principles.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages