The Ultimate CLI tool for scaffolding FastAPI projects with Clean Architecture principles.
- Introduction
- Features
- Architecture
- Installation
- Quick Start
- Commands
- Project Structure
- Examples
- Production Ready
- Contributing
- Changelog
- Acknowledgments
FastAPI Clean CLI is a powerful command-line interface designed to streamline the development of FastAPI applications. It enforces Clean Architecture (Uncle Bob's architecture) and SOLID principles, allowing you to focus on business logic rather than boilerplate code.
- ⚡ Save Hours: Generate production-ready projects in seconds
- 🏗️ Best Practices: Clean Architecture, SOLID principles, DDD patterns
- 🔧 Batteries Included: Docker, Tests, CI/CD, Monitoring out of the box
- 📚 Learn by Example: Educational reference implementation
- 🚀 Production Ready: Enterprise-grade structure from day one
- ✅ 4-Layer Clean Architecture: Domain → Application → Infrastructure → Presentation
- ✅ Domain-Driven Design: Entity-centric business logic
- ✅ Dependency Injection: Built-in IoC container
- ✅ Repository Pattern: Abstract data access
- ✅ Use Case Pattern: Single responsibility business operations
- ✅ Multiple Databases: PostgreSQL, MySQL, SQLite, MongoDB (coming soon)
- ✅ Authentication: JWT, OAuth2, API Key support
- ✅ Caching: Redis, Memcached integration
- ✅ Background Jobs: Celery with Redis/RabbitMQ
- ✅ Object Storage: MinIO/S3 client integration
- ✅ Monitoring: Prometheus & Grafana configs
- ✅ CRUD Generator: Full vertical slice in one command
- ✅ Async/Await: Native async support throughout
- ✅ Type Hints: Complete type safety
- ✅ Auto Tests: Unit and integration tests generated
- ✅ CI/CD Ready: GitHub Actions workflows included
- ✅ Docker Ready: Complete containerization setup
- ✅ API Documentation: Auto-generated Swagger/OpenAPI
FastAPI Clean CLI follows the Dependency Rule: source code dependencies can only point inwards.
┌──────────────────────────────────────────────────┐
│ Presentation Layer (API, CLI, Schemas) │ ← Frameworks & Drivers
├──────────────────────────────────────────────────┤
│ Infrastructure Layer (DB, Cache, Queue, Auth) │ ← Interface Adapters
├──────────────────────────────────────────────────┤
│ Application Layer (Use Cases, DTOs, Ports) │ ← Application Business Rules
├──────────────────────────────────────────────────┤
│ Domain Layer (Entities, Value Objects) │ ← Enterprise Business Rules
└──────────────────────────────────────────────────┘
- 🎯 Independence of Frameworks: Business logic doesn't depend on FastAPI
- 🧪 Testability: Each layer can be tested independently
- 🔄 Independence of Database: Switch databases without changing business logic
- 🎨 Independence of UI: API can be swapped with GraphQL, CLI, etc.
pip install fastapi-clean-clifastapi-clean --version
fastapi-clean --helpgit clone https://github.com/Amirrdoustdar/fastclean.git
cd fastclean
python -m venv venv
source venv/bin/activate
pip install -e ".[dev]"# Simple project
fastapi-clean init --name=my_api
# With PostgreSQL and Docker
fastapi-clean init --name=my_api --db=postgresql --docker
# Enterprise setup
fastapi-clean init \
--name=my_api \
--db=postgresql \
--cache=redis \
--auth=jwt \
--dockercd my_api
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txt# Development
uvicorn src.main:app --reload
# Or with Docker
docker-compose upOpen your browser at:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- Health Check: http://localhost:8000/health
Initialize a new FastAPI project with customizable options.
fastapi-clean init --name=blog_apifastapi-clean init \
--name=enterprise_app \
--path=~/projects \
--db=postgresql \
--cache=redis \
--queue=celery \
--auth=jwt \
--storage=minio \
--monitoring=prometheus \
--ci=github-actions \
--docker| Option | Description | Choices | Default |
|---|---|---|---|
--name |
Project name | Any valid identifier | Required |
--path |
Project directory | Any valid path | . |
--db |
Database | postgresql, mysql, sqlite, mongodb |
postgresql |
--cache |
Caching system | redis, memcached, none |
none |
--queue |
Task queue | celery, arq, none |
none |
--auth |
Authentication | jwt, oauth2, api_key, none |
none |
--storage |
File storage | minio, s3, local |
local |
--monitoring |
Monitoring | prometheus, elk, none |
none |
--docker |
Include Docker | Flag | False |
--ci |
CI/CD | github-actions, gitlab-ci, none |
none |
--no-tests |
Skip tests | Flag | False |
Generate a complete vertical slice for any entity with one command.
fastapi-clean crud EntityName --fields="field1:type1,field2:type2"fastapi-clean crud Product --fields="name:str,price:float,stock:int,is_active:bool,description:str"✓ src/domain/entities/product.py # Domain Entity
✓ src/domain/repositories/product_repository.py # Repository Interface
✓ src/infrastructure/database/models/product_model.py # SQLAlchemy Model
✓ src/infrastructure/database/repositories/product_repository.py # Repository Impl
✓ src/application/usecases/product/create_product.py # Create Use Case
✓ src/application/usecases/product/get_product.py # Get Use Case
✓ src/application/usecases/product/update_product.py # Update Use Case
✓ src/application/usecases/product/delete_product.py # Delete Use Case
✓ src/application/usecases/product/list_products.py # List Use Case
✓ src/interfaces/api/v1/routes/product.py # API Routes
✓ src/interfaces/schemas/product.py # Pydantic Schemas
✓ tests/unit/test_product_usecase.py # Unit Tests
✓ tests/integration/test_product_api.py # Integration Tests
str- Stringint- Integerfloat- Float/Decimalbool- Booleandatetime- DateTimedate- DateOptional[type]- Optional field
Add features to an existing project.
fastapi-clean feature FEATURE_NAME --type=TYPE# Add JWT Authentication
fastapi-clean feature auth --type=jwt
# Add Redis Caching
fastapi-clean feature cache --type=redis
# Add Celery Background Jobs
fastapi-clean feature queue --type=celery
# Add Prometheus Monitoring
fastapi-clean feature monitoring --type=prometheusGenerated projects follow a strict Clean Architecture layout:
my_project/
│
├── src/
│ ├── domain/ # 🎯 Enterprise Business Rules
│ │ ├── entities/ # Business entities
│ │ ├── repositories/ # Repository interfaces (Ports)
│ │ └── value_objects/ # Value objects
│ │
│ ├── application/ # 🔧 Application Business Rules
│ │ ├── usecases/ # Use case implementations
│ │ │ ├── user/
│ │ │ │ ├── create_user.py
│ │ │ │ ├── get_user.py
│ │ │ │ └── list_users.py
│ │ └── interfaces/ # Input/Output ports
│ │
│ ├── infrastructure/ # 🏗️ Frameworks & Drivers
│ │ ├── config/ # Configuration
│ │ │ └── settings.py
│ │ ├── database/ # Database implementation
│ │ │ ├── database.py
│ │ │ ├── models/ # SQLAlchemy models
│ │ │ └── repositories/ # Repository implementations
│ │ ├── security/ # JWT, OAuth2 handlers
│ │ ├── worker/ # Celery app
│ │ └── external_services/ # MinIO, S3, etc.
│ │
│ ├── interfaces/ # 🌐 Interface Adapters
│ │ ├── api/
│ │ │ ├── dependencies.py # FastAPI dependencies
│ │ │ └── v1/
│ │ │ └── routes/ # API endpoints
│ │ │ ├── user.py
│ │ │ └── health.py
│ │ └── schemas/ # Pydantic DTOs
│ │ └── user.py
│ │
│ └── main.py # FastAPI application
│
├── tests/
│ ├── conftest.py # Pytest configuration
│ ├── unit/ # Unit tests
│ │ └── test_create_user_usecase.py
│ └── integration/ # Integration tests
│ └── test_user_api.py
│
├── docker-compose.yml # Multi-service orchestration
├── Dockerfile # Container definition
├── .env.example # Environment variables template
├── .gitignore
├── requirements.txt # Python dependencies
├── pytest.ini # Pytest configuration
└── README.md
# Initialize project
fastapi-clean init \
--name=shop_api \
--db=postgresql \
--cache=redis \
--auth=jwt \
--docker
cd shop_api
# Generate entities
fastapi-clean crud Product --fields="name:str,price:float,stock:int,category:str"
fastapi-clean crud Order --fields="user_id:int,total:float,status:str,created_at:datetime"
fastapi-clean crud Customer --fields="email:str,name:str,phone:str"
# Run
docker-compose up# Initialize
fastapi-clean init --name=blog_api --db=postgresql --auth=jwt
cd blog_api
# Generate
fastapi-clean crud Post --fields="title:str,content:str,author_id:int,published:bool"
fastapi-clean crud Comment --fields="post_id:int,user_id:int,content:str"
fastapi-clean crud Category --fields="name:str,slug:str"
# Run
uvicorn src.main:app --reload# Initialize with monitoring
fastapi-clean init \
--name=user_service \
--db=postgresql \
--cache=redis \
--monitoring=prometheus \
--docker
cd user_service
docker-compose up
# Metrics available at: http://localhost:9090When you use the --docker flag, FastAPI Clean CLI generates a complete docker-compose.yml that orchestrates:
| Service | Description | Port |
|---|---|---|
| API | FastAPI with Uvicorn | 8000 |
| Database | PostgreSQL/MySQL | 5432/3306 |
| Redis | Caching & Message Broker | 6379 |
| Celery Worker | Background Jobs | - |
| MinIO | S3-compatible Storage | 9000 |
| Prometheus | Metrics Collection | 9090 |
| Grafana | Metrics Visualization | 3000 |
docker-compose up --buildAll sensitive data is managed via .env:
# Database
DATABASE_URL=postgresql://user:password@db:5432/mydb
# Redis
REDIS_URL=redis://redis:6379/0
# JWT
SECRET_KEY=your-secret-key-change-in-production
ALGORITHM=HS256
# MinIO
MINIO_ROOT_USER=admin
MINIO_ROOT_PASSWORD=passwordGenerated projects include comprehensive test suites.
# All tests
pytest
# Unit tests only
pytest tests/unit/
# Integration tests only
pytest tests/integration/
# With coverage
pytest --cov=src --cov-report=html# tests/unit/test_create_user_usecase.py
import pytest
from src.application.usecases.user.create_user import CreateUserUseCase
@pytest.mark.asyncio
async def test_create_user_success(mock_user_repository):
usecase = CreateUserUseCase(mock_user_repository)
user = await usecase.execute("test@example.com", "testuser")
assert user.email == "test@example.com"| Metric | Value |
|---|---|
| Project Generation | < 5 seconds |
| CRUD Generation | < 2 seconds |
| Files Generated (init) | 40+ files |
| Lines of Code (init) | 1,500+ LOC |
| Test Coverage | 80%+ (goal) |
Contributions are what make the open-source community amazing! Any contributions you make are greatly appreciated.
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature') - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
git clone https://github.com/Amirrdoustdar/fastclean.git
cd fastclean
python -m venv venv
source venv/bin/activate
pip install -e ".[dev]"
pre-commit install
pytestSee CHANGELOG.md for detailed release notes.
- ✅ Initial stable release
- ✅ Complete Clean Architecture implementation
- ✅ CRUD generator
- ✅ Multiple database support
- ✅ Docker integration
- ✅ JWT authentication
- ✅ Redis caching
⚠️ MongoDB support is experimental (coming in v1.1.0)⚠️ GraphQL templates not yet available (planned for v1.2.0)
Report bugs at: GitHub Issues
- MongoDB full support
- GraphQL generator
- Interactive CLI mode
- WebSocket templates
- More database option
- Kubernetes manifests generator
- gRPC support
- Event sourcing templates
- CQRS pattern implementation
- Multi-tenancy support
- Advanced monitoring (OpenTelemetry)
- Service mesh integration
- Serverless deployment templates
This project is licensed under the MIT License - see the LICENSE file for details.
Special thanks to:
- Robert C. Martin (Uncle Bob) - For Clean Architecture principles
- FastAPI - Amazing Python framework
- HiDjango - Inspiration for CLI design
- Open Source Community - For continuous support and contributions
- Author: Amir Doustdar
- Email: amirrdoustdar1@gmail.com
- GitHub: @Amirrdoustdar
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- PyPI: https://pypi.org/project/fastapi-clean-cli/
- GitHub: https://github.com/Amirrdoustdar/fastclean
- Documentation: [Coming Soon]
- Blog Post: [Coming Soon]
If this project helped you, please consider giving it a star! ⭐
Become a sponsor and get your logo here! Sponsor this project
Made with ❤️ and Clean Architecture principles
FastAPI Clean CLI - From zero to production in minutes