Skip to content

Latest commit

 

History

History
502 lines (368 loc) · 14 KB

File metadata and controls

502 lines (368 loc) · 14 KB

FastAPI Clean Architecture Blueprint - Quick Start

🎯 What You Have

A complete, production-ready template for building FastAPI applications using Clean Architecture principles. This blueprint ensures:

Testability - Business logic tested without frameworks
Maintainability - Clear structure, easy to understand
Scalability - Add features without refactoring existing code
Flexibility - Switch databases, frameworks easily
Professional Quality - Industry best practices


📁 Files Overview

Documentation (Start Here!)

File Purpose
README.md Project overview and quick start
AI_ASSISTANT_PROMPT.md Comprehensive prompt for AI coding assistants
docs/ARCHITECTURE.md Deep dive: Clean Architecture principles
docs/PROJECT_STRUCTURE.md Detailed folder organization guide
docs/DEVELOPMENT_GUIDE.md How to add features (with full Product example)
docs/TESTING_STRATEGY.md Unit & integration testing approach

Source Code

src/
├── domain/              # Core business logic (pure Python)
├── application/         # Use cases & business orchestration
├── infrastructure/      # Database, external services
├── presentation/        # FastAPI routers & schemas
├── config/              # Configuration management
└── main.py              # Application entry point

Tests

tests/
├── conftest.py          # Pytest fixtures & configuration
├── unit/                # Unit tests (isolated, fast)
└── integration/         # Integration tests (with dependencies)

Configuration

File Purpose
pyproject.toml Project metadata & dependencies
requirements.txt Python package list
.env.example Environment variables template
pytest.ini Pytest configuration
.gitignore Git ignore rules

🚀 Getting Started

1. Copy the Blueprint

cp -r /path/to/FastAPIBluePrint your-new-project
cd your-new-project

2. Set Up Environment

# Create virtual environment
python3.10 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Copy environment template
cp .env.example .env

3. Run the Application

# Development mode with auto-reload
uvicorn src.main:app --reload

# Visit http://localhost:8000/docs for interactive API docs

4. Run Tests

# Run all tests
pytest

# Run with coverage report
pytest --cov=src

# Run only unit tests
pytest tests/unit/

# Run specific test
pytest tests/unit/test_example.py -v

📚 Learning Path

For Beginners

  1. Read README.md - Project overview
  2. Skim docs/ARCHITECTURE.md - Understand the 4 layers
  3. Study docs/PROJECT_STRUCTURE.md - See where code goes
  4. Review skeleton code in src/ directory - See patterns in action
  5. Try docs/DEVELOPMENT_GUIDE.md - Add a feature yourself

For Experienced Developers

  1. Review AI_ASSISTANT_PROMPT.md - Use with Copilot/Claude
  2. Study docs/PROJECT_STRUCTURE.md - Directory purposes
  3. Examine test examples in tests/ - Testing patterns
  4. Adapt for your use case - Scale up/down as needed

For AI Assistant Integration

  1. Load AI_ASSISTANT_PROMPT.md into your AI assistant
  2. Ask: "Generate a [Feature Name] feature following this blueprint"
  3. AI generates: Entity, Use Case, Repository, Router, Tests
  4. You integrate: Copy code, adjust domain names
  5. Result: Professional, testable feature implementation

🏗️ Architecture Layers (Quick Overview)

┌─────────────────────────────────┐
│ Presentation Layer (HTTP API)   │  FastAPI routers, Pydantic schemas
├─────────────────────────────────┤
│ Application Layer (Use Cases)   │  Business orchestration, DTOs
├─────────────────────────────────┤
│ Domain Layer (Business Logic)   │  Entities, business rules (pure Python)
├─────────────────────────────────┤
│ Infrastructure Layer (Technical)│  Database, external services
└─────────────────────────────────┘

The Dependency Rule: Inner layers never depend on outer layers.


📊 Project Size Scaling

Small Projects (1-2 developers)

  • Use simplified structure (combine some files)
  • Single database implementation
  • See docs for structure

Medium Projects (3-5 developers)

  • Use full blueprint structure as provided
  • Multiple repository implementations possible
  • Team coordination on feature boundaries

Large Projects (6+ developers)

  • Add bounded contexts (domain-driven design)
  • Event-driven architecture
  • Microservices consideration
  • See docs for advanced patterns

🎓 Key Concepts

Clean Architecture Principles

  1. Independence of Frameworks: Business logic doesn't depend on FastAPI
  2. Testability: Core logic tested without database or HTTP
  3. Independence of UI: API can change without affecting business logic
  4. Independence of Database: Database choice is implementation detail
  5. Independence of External Services: Business logic survives external API changes

The Dependency Rule

Source code dependencies must point inward.

  • ✅ Outer layers can depend on inner layers
  • ❌ Inner layers MUST NOT depend on outer layers
  • ❌ No circular dependencies

Design Patterns Used

  • Repository Pattern: Abstract data access
  • Dependency Injection: Loose coupling via FastAPI's Depends
  • DTO Pattern: Transfer data between layers
  • Mapper Pattern: Convert between entities and DTOs
  • Factory Pattern: Create instances with dependencies

💡 Feature Development Workflow

Adding a New Feature (e.g., "Comments")

1. Domain Layer - Define the business concept

src/domain/entities/comment_entity.py
src/domain/repositories/comment_repository.py
src/domain/exceptions/comment_exceptions.py

2. Application Layer - Implement use cases

src/application/use_cases/comment_use_cases.py
src/application/dto/comment_dto.py
src/application/mappers/comment_mapper.py

3. Infrastructure Layer - Implement persistence

src/infrastructure/database/models.py (add CommentModel)
src/infrastructure/repositories/sqlalchemy_comment_repository.py

4. Presentation Layer - Create API

src/presentation/api/comment_router.py
src/presentation/schemas/comment_schemas.py

5. Tests - Verify correctness

tests/unit/application/test_comment_use_cases.py
tests/integration/api/test_comment_endpoints.py

See docs/DEVELOPMENT_GUIDE.md for complete Product example.


🧪 Testing Strategy

Unit Tests (80% of tests)

  • Test business logic in isolation
  • No database, no HTTP calls
  • Mock repositories
  • Fast execution (< 1 second each)

Location: tests/unit/

Integration Tests (15% of tests)

  • Test with real database (in-memory SQLite)
  • Test repository implementations
  • Test full HTTP endpoints
  • Medium speed (< 5 seconds each)

Location: tests/integration/

E2E Tests (5% of tests)

  • Full system tests
  • Manual or automated via HTTP client
  • Slowest but most comprehensive
  • Real environment

Location: Separate test suite or manual


🔧 Common Tasks

Add a New Endpoint

  1. Create entity in src/domain/entities/
  2. Create repository interface in src/domain/repositories/
  3. Create use case in src/application/use_cases/
  4. Implement repository in src/infrastructure/repositories/
  5. Create router in src/presentation/api/
  6. Define schemas in src/presentation/schemas/
  7. Add tests in tests/unit/ and tests/integration/

Implement Authentication

  • Put auth logic in src/domain/ (value objects, entities)
  • Orchestrate in src/application/ (use cases)
  • Store tokens via repository
  • Verify in src/presentation/ middleware

Change Database

  1. Keep domain and application layers unchanged
  2. Create new repository implementation:
    • MongoDBUserRepository, RedisUserRepository, etc.
    • Implement same interface
  3. Update infrastructure layer
  4. Update src/presentation/api/dependencies.py

Add External Service

  1. Create adapter in src/infrastructure/external_services/
  2. Define interface if complex
  3. Call from use cases
  4. Mock in tests

📋 Checklist: Before Shipping

  • Domain layer has ZERO external dependencies
  • All business logic in domain/application layers
  • Repository interfaces in domain, implementations in infrastructure
  • Use cases orchestrate, don't implement directly
  • No ORM models exposed outside infrastructure
  • All HTTP errors caught in routers
  • 80%+ test coverage for domain & application
  • Configuration via environment variables
  • Logging configured properly
  • .env file not committed to git
  • Documentation updated
  • Type hints used throughout

🆘 Troubleshooting

Import Errors

Problem: "Cannot import from src"

Solution:

# Add src to Python path
export PYTHONPATH="${PYTHONPATH}:/path/to/project"

# Or run from project root
python -m pytest tests/

Database Connection Errors

Problem: "Could not connect to database"

Solution:

  1. Check .env file exists and is configured
  2. For SQLite: ensure path is writable
  3. For PostgreSQL: ensure server is running
  4. Check DATABASE_URL in .env

Tests Not Running

Problem: "No tests collected"

Solution:

  1. Test files must be named test_*.py
  2. Test classes must be named Test*
  3. Test functions must be named test_*
  4. Ensure pytest.ini is in root directory

Async/Await Errors

Problem: "RuntimeError: Event loop is closed"

Solution: Use @pytest.mark.asyncio on async test functions


🌐 Use with AI Assistants

GitHub Copilot

  1. Open file in each layer
  2. Let Copilot see the pattern
  3. Start typing: "def create_..." → Copilot completes the pattern

ChatGPT / Claude / other LLMs

  1. Load AI_ASSISTANT_PROMPT.md
  2. Provide context: "I have a FastAPI project with this structure..."
  3. Request: "Generate [feature] following this architecture"
  4. AI generates complete, structured code

Example Prompt

I have a FastAPI Clean Architecture project. 
Here's the prompt: [paste AI_ASSISTANT_PROMPT.md]

Please generate a complete "Blog Posts" feature with:
- Entity validation for title and content
- CRUD use cases
- Repository for data persistence
- FastAPI router with all endpoints
- Pydantic schemas
- Unit and integration tests

Follow the existing patterns in the blueprint.

📈 Performance Optimization Tips

  1. Use async throughout: async def, await
  2. Connection pooling: Handled by SQLAlchemy automatically
  3. Lazy loading: Configure in ORM models
  4. Caching: Add at repository layer
  5. Pagination: Implement in repository.find_all()
  6. Indexing: Configure in database models
  7. Monitoring: Add logging in critical paths

🔐 Security Best Practices

  1. Validate all input: Use Pydantic schemas
  2. Authorize all endpoints: Add dependency for auth check
  3. No sensitive data in logs: Filter PII
  4. Hash passwords: Never store plain text
  5. Use HTTPS in production: FastAPI supports it
  6. Validate domain invariants: In entity constructors
  7. Use environment variables: For secrets (DATABASE_URL, API_KEYS, etc.)

🤝 Contributing to This Blueprint

To improve the blueprint:

  1. Test your changes thoroughly
  2. Update documentation
  3. Add tests for new features
  4. Follow existing code style
  5. Keep layers separated
  6. Update AI_ASSISTANT_PROMPT.md if architecture changes

📞 Quick Reference

Run Commands

uvicorn src.main:app --reload    # Start app
pytest                            # Run tests
pytest --cov=src                  # With coverage
black src/                         # Format code
ruff check src/                    # Lint code

File Locations

Domain logic        → src/domain/entities/
Use cases           → src/application/use_cases/
Database            → src/infrastructure/repositories/
API endpoints       → src/presentation/api/
Configuration       → src/config/settings.py
Tests               → tests/unit/ and tests/integration/

Key Patterns

Entity pattern      → src/domain/entities/base_entity.py
Repository pattern  → src/domain/repositories/base_repository.py
Use case pattern    → src/application/use_cases/base_use_case.py
Test pattern        → tests/unit/test_example.py

📚 Additional Resources


🎉 You're Ready!

You now have everything needed to:

✅ Create professional FastAPI projects
✅ Structure code following industry best practices
✅ Generate features quickly with AI assistance
✅ Write testable, maintainable code
✅ Scale from solo projects to team projects

Next Steps:

  1. Customize the blueprint for your project
  2. Update project metadata in pyproject.toml
  3. Modify .env.example for your needs
  4. Start building features!

Happy coding! 🚀


Blueprint Version: 1.0.0
Created: December 2025
Python: 3.10+
FastAPI: 0.104+