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
| 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 |
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/
├── conftest.py # Pytest fixtures & configuration
├── unit/ # Unit tests (isolated, fast)
└── integration/ # Integration tests (with dependencies)
| 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 |
cp -r /path/to/FastAPIBluePrint your-new-project
cd your-new-project# 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# Development mode with auto-reload
uvicorn src.main:app --reload
# Visit http://localhost:8000/docs for interactive API docs# 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- Read README.md - Project overview
- Skim docs/ARCHITECTURE.md - Understand the 4 layers
- Study docs/PROJECT_STRUCTURE.md - See where code goes
- Review skeleton code in
src/directory - See patterns in action - Try docs/DEVELOPMENT_GUIDE.md - Add a feature yourself
- Review AI_ASSISTANT_PROMPT.md - Use with Copilot/Claude
- Study docs/PROJECT_STRUCTURE.md - Directory purposes
- Examine test examples in
tests/- Testing patterns - Adapt for your use case - Scale up/down as needed
- Load AI_ASSISTANT_PROMPT.md into your AI assistant
- Ask: "Generate a [Feature Name] feature following this blueprint"
- AI generates: Entity, Use Case, Repository, Router, Tests
- You integrate: Copy code, adjust domain names
- Result: Professional, testable feature implementation
┌─────────────────────────────────┐
│ 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.
- Use simplified structure (combine some files)
- Single database implementation
- See docs for structure
- Use full blueprint structure as provided
- Multiple repository implementations possible
- Team coordination on feature boundaries
- Add bounded contexts (domain-driven design)
- Event-driven architecture
- Microservices consideration
- See docs for advanced patterns
- Independence of Frameworks: Business logic doesn't depend on FastAPI
- Testability: Core logic tested without database or HTTP
- Independence of UI: API can change without affecting business logic
- Independence of Database: Database choice is implementation detail
- Independence of External Services: Business logic survives external API changes
Source code dependencies must point inward.
- ✅ Outer layers can depend on inner layers
- ❌ Inner layers MUST NOT depend on outer layers
- ❌ No circular dependencies
- 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
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.
- Test business logic in isolation
- No database, no HTTP calls
- Mock repositories
- Fast execution (< 1 second each)
Location: tests/unit/
- Test with real database (in-memory SQLite)
- Test repository implementations
- Test full HTTP endpoints
- Medium speed (< 5 seconds each)
Location: tests/integration/
- Full system tests
- Manual or automated via HTTP client
- Slowest but most comprehensive
- Real environment
Location: Separate test suite or manual
- Create entity in
src/domain/entities/ - Create repository interface in
src/domain/repositories/ - Create use case in
src/application/use_cases/ - Implement repository in
src/infrastructure/repositories/ - Create router in
src/presentation/api/ - Define schemas in
src/presentation/schemas/ - Add tests in
tests/unit/andtests/integration/
- Put auth logic in
src/domain/(value objects, entities) - Orchestrate in
src/application/(use cases) - Store tokens via repository
- Verify in
src/presentation/middleware
- Keep domain and application layers unchanged
- Create new repository implementation:
MongoDBUserRepository,RedisUserRepository, etc.- Implement same interface
- Update infrastructure layer
- Update
src/presentation/api/dependencies.py
- Create adapter in
src/infrastructure/external_services/ - Define interface if complex
- Call from use cases
- Mock in tests
- 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
-
.envfile not committed to git - Documentation updated
- Type hints used throughout
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/Problem: "Could not connect to database"
Solution:
- Check
.envfile exists and is configured - For SQLite: ensure path is writable
- For PostgreSQL: ensure server is running
- Check
DATABASE_URLin.env
Problem: "No tests collected"
Solution:
- Test files must be named
test_*.py - Test classes must be named
Test* - Test functions must be named
test_* - Ensure pytest.ini is in root directory
Problem: "RuntimeError: Event loop is closed"
Solution: Use @pytest.mark.asyncio on async test functions
- Open file in each layer
- Let Copilot see the pattern
- Start typing: "def create_..." → Copilot completes the pattern
- Load AI_ASSISTANT_PROMPT.md
- Provide context: "I have a FastAPI project with this structure..."
- Request: "Generate [feature] following this architecture"
- AI generates complete, structured code
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.
- Use async throughout:
async def,await - Connection pooling: Handled by SQLAlchemy automatically
- Lazy loading: Configure in ORM models
- Caching: Add at repository layer
- Pagination: Implement in repository.find_all()
- Indexing: Configure in database models
- Monitoring: Add logging in critical paths
- Validate all input: Use Pydantic schemas
- Authorize all endpoints: Add dependency for auth check
- No sensitive data in logs: Filter PII
- Hash passwords: Never store plain text
- Use HTTPS in production: FastAPI supports it
- Validate domain invariants: In entity constructors
- Use environment variables: For secrets (DATABASE_URL, API_KEYS, etc.)
To improve the blueprint:
- Test your changes thoroughly
- Update documentation
- Add tests for new features
- Follow existing code style
- Keep layers separated
- Update AI_ASSISTANT_PROMPT.md if architecture changes
uvicorn src.main:app --reload # Start app
pytest # Run tests
pytest --cov=src # With coverage
black src/ # Format code
ruff check src/ # Lint codeDomain 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/
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
- FastAPI Docs: https://fastapi.tiangolo.com/
- SQLAlchemy Docs: https://docs.sqlalchemy.org/
- Pydantic Docs: https://docs.pydantic.dev/
- Clean Architecture: "Clean Architecture" by Robert C. Martin
- DDD: "Domain-Driven Design" by Eric Evans
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:
- Customize the blueprint for your project
- Update project metadata in
pyproject.toml - Modify
.env.examplefor your needs - Start building features!
Happy coding! 🚀
Blueprint Version: 1.0.0
Created: December 2025
Python: 3.10+
FastAPI: 0.104+