daireto/base-clean-arch-fastapi
Base project for FastAPI-based APIs implementing clean architecture patterns for maintainable and testable code.
Base Clean Architecture FastAPI-based API
This is a base project for FastAPI-based APIs implementing clean architecture
patterns for maintainable and testable code.
Feel free to use it as a starting point for your own projects.
๐๏ธ Architecture
This project follows the Clean Architecture pattern, with the following
layers:
- Domain Layer: Core business logic and entities.
- Application Layer: Use cases and application services.
- Infrastructure Layer: External dependencies and integrations.
The project is structured around modules (vertical slices), with each
module having its own directory containing all the necessary layers.
It also implements other patterns and practices, such as:
- Builder Pattern for entity creation.
- Dependency Injection (via Lagom).
- Data Transfer Objects (DTOs) for request and response payloads.
- Value Objects for data validation.
- Result Pattern for handling operation outcomes.
- Repository Pattern for data access.
- Collections for enhanced filtering and sorting.
- Instrumentation for logging and monitoring use cases.
- OData V4 Query for filtering and sorting data.
- Correlation ID for request tracing.
๐ Technology Stack
These are some of the main technologies used in this project:
- FastAPI - Web framework for building APIs.
- SQLAdmin - Admin interface for database management.
- SQLActive - ActiveRecord pattern for database operations.
- SQLite - Database (via aiosqlite for async operations).
- Lagom - Dependency injection container.
- Pydantic - Data validation and settings management.
- Orjson - Fast JSON serialization.
- Uvloop - High-performance event loop.
- Structlog - Structured logging.
- Validators - Data validation.
- OData V4 Query - OData query parsing.
- ASGI Correlation ID - Requests correlation with unique IDs.
- Ruff - Linter and code formatter.
- Pytest - Testing framework.
๐ Project Structure
.
โโโ src/ # Source code
โ โโโ api/ # API-related code
โ โ โโโ middlewares/ # Application middlewares
โ โ โ โโโ access_log_middleware.py # Access logging middleware
โ โ โโโ config.py # Application configuration
โ โ โโโ health.py # Health check logic
โ โโโ modules/ # Feature modules (domain-driven)
โ โ โโโ resources/ # Resources feature module
โ โ โโโ application/ # Application layer (use cases)
โ โ โ โโโ use_cases/ # Use case implementations
โ โ โ โโโ create_resource.py
โ โ โ โโโ delete_resource.py
โ โ โ โโโ get_resource.py
โ โ โ โโโ list_resources.py
โ โ โ โโโ update_resource.py
โ โ โโโ domain/ # Domain layer
โ โ โ โโโ entities.py # Domain entities
โ โ โ โโโ error_codes.py # Domain-specific error codes
โ โ โ โโโ exceptions.py # Domain-specific exceptions
โ โ โ โโโ value_objects.py # Value objects
โ โ โ โโโ collections.py # Domain collections
โ โ โ โโโ interfaces/ # Repository interfaces
โ โ โ โโโ repositories.py
โ โ โโโ infrastructure/ # Infrastructure layer
โ โ โ โโโ instrumentation/ # Use case instrumentation/decorators
โ โ โ โ โโโ use_cases/
โ โ โ โ โโโ create_resource.py
โ โ โ โ โโโ delete_resource.py
โ โ โ โ โโโ get_resource.py
โ โ โ โ โโโ list_resources.py
โ โ โ โ โโโ update_resource.py
โ โ โ โโโ persistence/ # Persistence implementations
โ โ โ โโโ admin.py # SQLAdmin view for resources
โ โ โ โโโ models/ # Database models
โ โ โ โ โโโ mock.py # Mock models for testing
โ โ โ โ โโโ sqlite.py # SQLite database models
โ โ โ โโโ repositories/ # Repository implementations
โ โ โ โโโ mock.py # Mock repository for testing
โ โ โ โโโ sqlite.py # SQLite repository implementation
โ โ โโโ presentation/ # Presentation layer (API)
โ โ โ โโโ api.py # Resource API endpoints
โ โ โ โโโ dtos.py # Data transfer objects
โ โ โโโ di.py # Dependency injection configuration
โ โโโ shared/ # Shared utilities and common code
โ โ โโโ application/ # Shared application layer
โ โ โ โโโ interfaces/ # Shared interfaces
โ โ โ โโโ base.py # Base interfaces
โ โ โ โโโ instrumentation.py # Instrumentation interfaces
โ โ โโโ domain/ # Shared domain layer
โ โ โ โโโ bases/ # Base classes
โ โ โ โ โโโ entity.py # Entity base class
โ โ โ โ โโโ value_object.py # Value object base class
โ โ โ โโโ error_codes.py # Shared error codes
โ โ โ โโโ exceptions.py # Shared exception classes
โ โ โโโ helpers/ # Shared helper functions
โ โ โ โโโ odata_helper.py # OData query helper
โ โ โโโ infrastructure/ # Shared infrastructure
โ โ โ โโโ db.py # Database connection utilities
โ โ โโโ presentation/ # Shared presentation layer
โ โ โ โโโ api.py # Shared API routes (e.g., health check)
โ โ โ โโโ dtos.py # Base DTO classes
โ โ โ โโโ responses.py # Response utilities
โ โ โโโ utils/ # Shared utility functions
โ โ โโโ uuid_tools.py # UUID utility functions
โ โโโ logger.py # Logging configuration
โ โโโ main.py # FastAPI application entry point
โโโ tests/ # Tests directory
โ โโโ conftest.py # Pytest global fixtures
โ โโโ resources/ # Resource module tests
โ โ โโโ application/ # Application layer tests
โ โ โ โโโ test_create_resource.py
โ โ โ โโโ test_delete_resource.py
โ โ โ โโโ test_get_resource.py
โ โ โ โโโ test_list_resources.py
โ โ โ โโโ test_update_resource.py
โ โ โโโ domain/ # Domain layer tests
โ โ โ โโโ conftest.py
โ โ โ โโโ test_collections.py
โ โ โโโ infrastructure/ # Infrastructure layer tests
โ โ โ โโโ persistence/ # Persistence layer tests
โ โ โ โโโ repositories/ # Repository tests
โ โ โ โโโ test_sqlite_resource_repository.py
โ โ โโโ presentation/ # Presentation layer tests
โ โ โโโ test_create_resource.py
โ โ โโโ test_delete_resource.py
โ โ โโโ test_get_resource.py
โ โ โโโ test_list_resources.py
โ โ โโโ test_update_resource.py
โ โโโ shared/ # Shared tests
โ โโโ presentation/ # Shared presentation tests
โ โโโ api/ # API tests
โ โโโ test_health.py # Health endpoint tests
โโโ .env.example # Environment variables template
โโโ api.http # Some HTTP requests for testing
โโโ COMMITS.md # Git commit guidelines
โโโ LICENSE.md # Project license
โโโ pyproject.toml # Project configuration and dependencies
โโโ README.md # Project documentation
โโโ ruff.toml # Ruff linter configuration
โโโ uv.lock # UV dependency lock file
๐ ๏ธ Development Setup
Prerequisites
- Python 3.10+
- uv
Installation
- Clone the repository
- Create and activate a virtual environment:
uv venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate
- Install dependencies:
uv sync
Running the Application
Run the application with:
uv run main.pyThe API will be available at http://$DOMAIN_NAME:$PORT/.
Replace $DOMAIN_NAME and $PORT with the domain name or IP address of the
server and the port number you configured in the .env file respectively
(see the configuration section below).
๐ง Configuration
Copy the .env.example file to .env and update the settings as needed.
cp .env.example .envExample .env file:
ENV=dev
PORT=8000
DEBUG=True
DATABASE_URL=sqlite+aiosqlite:///./test.db
MAX_RECORDS_PER_PAGE=100
LOGS_PATH=./.logs/app.logDatabase
- Development: SQLite database.
- Connection: Configured via
DATABASE_URLsetting. - Migrations: Automatic table creation on startup.
๐ API Documentation
- Swagger UI:
http://$DOMAIN_NAME:$PORT/docs - ReDoc:
http://$DOMAIN_NAME:$PORT/redoc
Replace $PORT with the port number you configured in the .env file.
โ๏ธ Admin Interface
- Admin:
http://$DOMAIN_NAME:$PORT/admin
๐งช Testing & Linting
Run tests with pytest:
uv run -m pytestRun linting with ruff:
uv run -m ruff check .๐ Available Endpoints
Health Check
GET /health- Application health status.GET /ping- Same as/health.
Resources
- Resource endpoints are available under the
/resourcesprefix.
๐๏ธ Clean Architecture Benefits
This project structure provides:
- Testability: Easy to unit test business logic.
- Maintainability: Clear separation of concerns.
- Flexibility: Easy to swap implementations (e.g., database providers).
- Independence: Domain logic independent of frameworks.
๐ค Contributing
- Check the commits guidelines.
- Follow the existing architecture patterns.
- Add tests for new functionality using
pytest. - Use type hints throughout.
- Run linting with
ruffbefore committing.
๐ License
This project is licensed under the MIT License.