Skip to content

mahdighadiriii/Fastapi-DDD-Hexagonal-Todo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

63 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿš€ FastAPI DDD Hexagonal Architecture - Todo API

FastAPI Python PostgreSQL SQLAlchemy Docker Poetry

A production-ready Todo API implementing Domain-Driven Design (DDD) and Hexagonal Architecture principles

Features โ€ข Architecture โ€ข Quick Start โ€ข API Documentation โ€ข Testing


๐Ÿ“‹ Table of Contents

๐ŸŽฏ Overview

This project demonstrates a production-grade implementation of a Todo API using FastAPI with Domain-Driven Design (DDD) and Hexagonal Architecture (Ports & Adapters). It showcases best practices for building scalable, maintainable, and testable Python applications.

Why This Architecture?

  • ๐ŸŽฏ Domain-Centric: Business logic isolated from infrastructure concerns
  • ๐Ÿ”Œ Pluggable: Easy to swap implementations (database, message queue, etc.)
  • ๐Ÿงช Testable: High test coverage with isolated unit tests
  • ๐Ÿ“ˆ Scalable: Clean separation enables horizontal scaling
  • ๐Ÿ›ก๏ธ Maintainable: Clear boundaries reduce coupling and technical debt

โœจ Features

  • โœ… CQRS Pattern - Separate read and write models
  • โœ… Event-Driven Architecture - Domain events for loose coupling
  • โœ… Unit of Work Pattern - Transactional consistency
  • โœ… Repository Pattern - Data access abstraction
  • โœ… Value Objects - Type-safe domain primitives
  • โœ… Domain Events - Business event tracking
  • โœ… API Versioning - Future-proof API design
  • โœ… Exception Handling - Centralized error management
  • โœ… Docker Support - Containerized deployment
  • โœ… Type Safety - Full type hints with Python 3.12

๐Ÿ—๏ธ Architecture

This project follows the Hexagonal Architecture pattern, organizing code into three main layers:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                    Infrastructure Layer                 โ”‚
โ”‚  (FastAPI, SQLAlchemy, Event Handlers, External APIs)   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                      โ”‚ Adapters
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                    Application Layer                    โ”‚
โ”‚     (Use Cases, DTOs, Interfaces/Ports)                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                      โ”‚ Use Cases
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                      Domain Layer                       โ”‚
โ”‚  (Entities, Value Objects, Domain Events, Repositories) โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Layer Responsibilities

๐ŸŽฏ Domain Layer (Core Business Logic)

  • Entities and Aggregates
  • Value Objects
  • Domain Events
  • Repository Interfaces
  • Business Rules and Invariants

โš™๏ธ Application Layer (Use Cases)

  • Command Handlers (Write Operations)
  • Query Handlers (Read Operations)
  • DTOs (Data Transfer Objects)
  • Port Interfaces (UnitOfWork, EventBus)

๐Ÿ”Œ Infrastructure Layer (Technical Details)

  • FastAPI REST endpoints
  • SQLAlchemy ORM models
  • Database repositories
  • Event bus implementation
  • Middleware and exception handlers

๐Ÿ› ๏ธ Technology Stack

Technology Purpose Version
FastAPI Web framework Latest
Python Programming language 3.12+
PostgreSQL Database Latest
SQLAlchemy ORM Latest
Poetry Dependency management Latest
Docker Containerization Latest
Pydantic Data validation v2.0+

๐Ÿ“ Project Structure

src/
โ”œโ”€โ”€ domain/                    # Core business logic
โ”‚   โ”œโ”€โ”€ entities/              # Domain entities
โ”‚   โ”‚   โ””โ”€โ”€ todo.py           # Todo aggregate root
โ”‚   โ”œโ”€โ”€ value_objects/        # Immutable value types
โ”‚   โ”‚   โ”œโ”€โ”€ todo_id.py        # Unique identifier
โ”‚   โ”‚   โ”œโ”€โ”€ todo_status.py    # Status enum
โ”‚   โ”‚   โ””โ”€โ”€ priority.py       # Priority enum
โ”‚   โ”œโ”€โ”€ events/               # Domain events
โ”‚   โ”‚   โ”œโ”€โ”€ base.py           # Base event
โ”‚   โ”‚   โ””โ”€โ”€ todo_events.py    # Todo-specific events
โ”‚   โ”œโ”€โ”€ repositories/         # Repository interfaces
โ”‚   โ”‚   โ””โ”€โ”€ todo_repository.py
โ”‚   โ””โ”€โ”€ exceptions.py         # Domain exceptions
โ”‚
โ”œโ”€โ”€ application/              # Use cases and DTOs
โ”‚   โ”œโ”€โ”€ use_cases/
โ”‚   โ”‚   โ”œโ”€โ”€ commands/         # Write operations (CQRS)
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ create_todo.py
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ update_todo.py
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ complete_todo.py
โ”‚   โ”‚   โ””โ”€โ”€ queries/          # Read operations (CQRS)
โ”‚   โ”‚       โ”œโ”€โ”€ get_todo.py
โ”‚   โ”‚       โ””โ”€โ”€ list_todos.py
โ”‚   โ”œโ”€โ”€ dto/                  # Data transfer objects
โ”‚   โ”‚   โ””โ”€โ”€ todo_dto.py
โ”‚   โ””โ”€โ”€ interfaces/           # Port interfaces
โ”‚       โ”œโ”€โ”€ unit_of_work.py
โ”‚       โ””โ”€โ”€ event_bus.py
โ”‚
โ”œโ”€โ”€ infrastructure/           # External adapters
โ”‚   โ”œโ”€โ”€ api/                  # FastAPI layer
โ”‚   โ”‚   โ””โ”€โ”€ v1/
โ”‚   โ”‚       โ”œโ”€โ”€ endpoints/
โ”‚   โ”‚       โ”‚   โ””โ”€โ”€ todos.py
โ”‚   โ”‚       โ”œโ”€โ”€ schemas.py
โ”‚   โ”‚       โ””โ”€โ”€ dependencies.py
โ”‚   โ”œโ”€โ”€ persistence/          # Database layer
โ”‚   โ”‚   โ””โ”€โ”€ sqlalchemy/
โ”‚   โ”‚       โ”œโ”€โ”€ models.py
โ”‚   โ”‚       โ”œโ”€โ”€ repositories.py
โ”‚   โ”‚       โ”œโ”€โ”€ read_repositories.py
โ”‚   โ”‚       โ”œโ”€โ”€ unit_of_work.py
โ”‚   โ”‚       โ””โ”€โ”€ database.py
โ”‚   โ””โ”€โ”€ events/               # Event handling
โ”‚       โ”œโ”€โ”€ event_bus.py
โ”‚       โ””โ”€โ”€ handlers.py
โ”‚
โ”œโ”€โ”€ config/                   # Configuration
โ”‚   โ””โ”€โ”€ settings.py
โ”‚
โ””โ”€โ”€ main.py                   # Application entry point

๐Ÿš€ Quick Start

Prerequisites

  • Python 3.12+
  • Poetry
  • Docker & Docker Compose
  • PostgreSQL (or use Docker)

Installation

  1. Clone the repository

    git clone https://github.com/mahdighadiriii/Fastapi-DDD-Hexagonal-Todo.git
    cd Fastapi-DDD-Hexagonal-Todo
  2. Install dependencies

    poetry install
  3. Start PostgreSQL (using Docker)

    cd postgres
    docker-compose up -d
  4. Configure environment variables

    cp .env.example .env
    # Edit .env with your database credentials
  5. Run migrations

    poetry run alembic upgrade head
  6. Start the application

    poetry run uvicorn src.main:app --reload
  7. Access the API

Using Requirements.txt

If you prefer pip over Poetry:

pip install -r requirements.txt
uvicorn src.main:app --reload

โš™๏ธ Configuration

Configuration is managed through src/config/settings.py using Pydantic settings.

Environment Variables

# Database
DATABASE_URL=postgresql://user:password@localhost:5432/todo_db

# Application
APP_NAME=Todo API
VERSION=1.0.0
DEBUG=true

# API
API_V1_PREFIX=/api/v1

๐Ÿ“š API Documentation

Endpoints

Create Todo

POST /api/v1/todos
Content-Type: application/json

{
  "title": "Complete project documentation",
  "description": "Write comprehensive README",
  "priority": "HIGH"
}

Get Todo

GET /api/v1/todos/{todo_id}

List Todos

GET /api/v1/todos?status=PENDING&priority=HIGH&skip=0&limit=10

Update Todo

PUT /api/v1/todos/{todo_id}
Content-Type: application/json

{
  "title": "Updated title",
  "description": "Updated description",
  "priority": "MEDIUM"
}

Complete Todo

POST /api/v1/todos/{todo_id}/complete

Delete Todo

DELETE /api/v1/todos/{todo_id}

Response Examples

Success Response (201 Created)

{
  "id": "123e4567-e89b-12d3-a456-426614174000",
  "title": "Complete project documentation",
  "description": "Write comprehensive README",
  "status": "PENDING",
  "priority": "HIGH",
  "created_at": "2025-10-26T10:30:00Z",
  "updated_at": "2025-10-26T10:30:00Z",
  "completed_at": null
}

Error Response (404 Not Found)

{
  "detail": "Todo not found"
}

๐ŸŽจ Design Patterns

1. CQRS (Command Query Responsibility Segregation)

Separates read and write operations for optimal performance and clarity.

  • Commands: create_todo.py, update_todo.py, complete_todo.py
  • Queries: get_todo.py, list_todos.py

2. Repository Pattern

Abstracts data access logic from business logic.

# Domain interface
class TodoRepository(ABC):
    @abstractmethod
    async def add(self, todo: Todo) -> None:
        pass

3. Unit of Work Pattern

Manages transactions and ensures consistency.

async with uow:
    todo = await uow.todos.get(todo_id)
    todo.complete()
    await uow.commit()

4. Domain Events

Decouples business logic through events.

class TodoCompletedEvent(DomainEvent):
    todo_id: TodoId
    completed_at: datetime

5. Value Objects

Encapsulates domain concepts with validation.

@dataclass(frozen=True)
class TodoId:
    value: UUID

๐Ÿงช Testing

Run Tests

# Run all tests
poetry run pytest

# Run with coverage
poetry run pytest --cov=src --cov-report=html

# Run specific test file
poetry run pytest tests/domain/test_entities.py

Test Structure

tests/
โ”œโ”€โ”€ domain/           # Domain layer tests
โ”œโ”€โ”€ application/      # Use case tests
โ”œโ”€โ”€ infrastructure/   # Infrastructure tests
โ””โ”€โ”€ conftest.py       # Shared fixtures

๐Ÿณ Docker Deployment

Build and Run

# Build image
docker build -t fastapi-ddd-todo .

# Run container
docker run -p 8000:8000 fastapi-ddd-todo

Docker Compose (Full Stack)

docker-compose up -d

๐Ÿ“Š Performance Considerations

  • Connection Pooling: SQLAlchemy manages database connections efficiently
  • Async/Await: Non-blocking I/O for better concurrency
  • Read Models: Optimized queries for read operations (CQRS)
  • Caching: Can be easily integrated at the infrastructure layer
  • Indexing: Database indexes on frequently queried fields

๐Ÿ”’ Security Best Practices

  • Input validation using Pydantic
  • SQL injection prevention via SQLAlchemy ORM
  • Environment-based configuration
  • CORS middleware configuration
  • Exception handling without information leakage

๐Ÿค Contributing

Contributions are welcome! Please follow these steps:

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

Coding Standards

  • Follow PEP 8 style guide
  • Add type hints to all functions
  • Write docstrings for public APIs
  • Include unit tests for new features
  • Update documentation as needed

๐Ÿ“– Resources

๐Ÿ“ License

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

๐Ÿ‘จโ€๐Ÿ’ป Author

Mahdi Ghadiri


โญ If you find this project helpful, please consider giving it a star!

Made with mahdiโค๏ธ using FastAPI and Domain-Driven Design

About

The FastAPI DDD Hexagonal Todo API is an educational yet production-ready reference implementation that bridges the gap between simple tutorials and real-world enterprise applications. **The Problem It Solves:** Most FastAPI tutorials teach basic CRUD operations with tightly coupled code that becomes unmaintainable as applications grow.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

โšก