A clean and modern task management API built with FastAPI, following clean architecture principles and best practices.
- CRUD Operations: Create, read, update, delete task lists and tasks
- Task State Management: Change task status (pending, in-progress, completed)
- Advanced Filtering: Filter tasks by state, priority with completion percentage
- Clean Architecture: Domain/Application/Infrastructure layers
- JWT Authentication: Login and protected endpoints
- Task Assignment: Assign users to tasks
- Email Notifications: Simulated email invitations
- API Framework: FastAPI + Uvicorn (ASGI server)
- Database: SQLAlchemy + PostgreSQL
- Testing: pytest (75% coverage target)
- Code Quality: black + isort + flake8
- Containerization: Docker + docker-compose
- Dependencies: Poetry
- Dependency Management: Poetry for reliable package management
- Code Formatting:
- Black for consistent code style
- isort for organized imports
- Linting: flake8 with plugins for code quality checks
- Testing:
- pytest for test running
- pytest-cov for coverage reporting
- Git Hooks: pre-commit for automated quality checks
- Docker: For consistent development and deployment environments
- Makefile: Simple command interface for common development tasks
- API Testing: Postman collection with example requests for all main endpoints
- Project setup with Poetry
- Code quality tools configuration
- Documentation structure
- Project planning
- Initial API design
- FastAPI project setup
- Domain models (Task, TaskList, User)
- Custom exceptions and validations
- Repository interfaces
classDiagram
class Task {
+UUID id
+String title
+String description
+TaskStatus status
+TaskPriority priority
+UUID task_list_id
+UUID assigned_user_id
+DateTime created_at
+DateTime updated_at
+DateTime due_date
+DateTime completed_at
+mark_as_in_progress()
+mark_as_completed()
+mark_as_pending()
+change_priority(priority)
+assign_to_user(user_id)
+update_details(title, description, due_date)
+is_completed()
+is_overdue()
}
class TaskList {
+UUID id
+String name
+String description
+UUID owner_id
+DateTime created_at
+DateTime updated_at
+Boolean is_active
+update_details(name, description)
+deactivate()
+activate()
}
class User {
+UUID id
+String email
+String username
+String full_name
+Boolean is_active
+DateTime created_at
+DateTime updated_at
+DateTime last_login
+update_profile(username, full_name, email)
+deactivate()
+activate()
+record_login()
}
class TaskStatus {
<<enumeration>>
PENDING
IN_PROGRESS
COMPLETED
}
class TaskPriority {
<<enumeration>>
LOW
MEDIUM
HIGH
CRITICAL
}
Task --> TaskStatus
Task --> TaskPriority
Task "*" --> "1" TaskList: belongs to
Task "*" --> "0..1" User: assigned to
TaskList "*" --> "1" User: owned by
DomainException
βββ ValidationError
βββ NotFoundError
β βββ TaskNotFoundError
β βββ TaskListNotFoundError
β βββ UserNotFoundError
βββ AlreadyExistsError
β βββ TaskListAlreadyExistsError
β βββ UserAlreadyExistsError
βββ BusinessRuleViolationError
βββ UnauthorizedOperationError
- Immutable Entities: All domain entities are immutable, using Pydantic v2's frozen models
- Rich Domain Model: Business logic encapsulated in entity methods rather than anemic models
- Method-Based State Changes: All state changes happen through explicit methods like
mark_as_completed() - Type Safety: Strong typing throughout with validation via Pydantic
- Clear Repository Interfaces: Abstract base classes define contracts for data access
The infrastructure layer implements the repository pattern using SQLAlchemy ORM:
Database Models:
UserModel: User entity with email/username uniqueness constraintsTaskListModel: Task list entity with foreign key to user (owner)TaskModel: Task entity with foreign keys to task list and optional assignee
Key Features:
- PostgreSQL database with proper relationships and constraints
- Repository pattern implementation for clean separation of concerns
- Async SQLAlchemy for high-performance database operations
- Automatic timestamp management (created_at, updated_at)
- Proper foreign key relationships and cascading deletes
- Database setup (SQLAlchemy + PostgreSQL)
- Repository implementations
- SQLAlchemy models with relationships and constraints
- Repository pattern implementation
- FastAPI routes and schemas
- Error handling middleware
- Task and TaskList domain services
- Database migrations for nullable owner_id
- Enhanced test infrastructure with mocked endpoints
- Unit and integration tests
- Coverage report (71% achieved, targeting 75%+)
- Comprehensive test infrastructure with database isolation
- Pre-commit hooks with automated testing
- JWT Authentication implementation
- User registration and login endpoints
- Password hashing with bcrypt
- Protected route middleware
- Role-based access control (RBAC)
Libraries and Dependencies:
# Core authentication libraries
poetry add python-jose[cryptography] # JWT token handling
poetry add passlib[bcrypt] # Password hashing
poetry add python-multipart # Form data supportImplementation Phases:
-
Password Security (Week 1)
- Implement password hashing with bcrypt
- Add password validation rules
- Update User model with hashed_password field
- Create password utilities (hash, verify)
-
JWT Token System (Week 2)
- JWT token generation and validation
- Access token and refresh token logic
- Token expiration and renewal
- Secure token storage recommendations
-
Authentication Endpoints (Week 3)
- POST /auth/register - User registration
- POST /auth/login - User authentication
- POST /auth/refresh - Token refresh
- POST /auth/logout - Token invalidation
-
Protected Routes (Week 4)
- Authentication dependency injection
- Route protection middleware
- Current user context
- Permission-based access control
-
Role-Based Access Control (Week 5)
- User roles and permissions
- Resource ownership validation
- Admin vs regular user capabilities
- Task assignment permissions
- Email notification system
- Task assignment workflows
- Real-time updates with WebSockets
- File attachments for tasks
- Task comments and activity logs
Email Notifications:
- Integration with SendGrid or AWS SES
- Task deadline reminders
- Assignment notifications
- Daily/weekly digest emails
Real-time Features:
- WebSocket integration for live updates
- Task status change notifications
- Collaborative editing indicators
- Live user presence
Enhanced Task Management:
- File upload and attachment system
- Task comments and discussion threads
- Activity logs and audit trails
- Task templates and recurring tasks
- Production Docker configuration
- CI/CD pipeline setup
- Environment configuration management
- Monitoring and logging
- Performance optimization
The project uses a comprehensive testing strategy with proper database isolation:
- Isolated Sessions: Each test runs in its own transaction with automatic rollback
- No Data Persistence: Test data doesn't leak between tests
- Async Support: Full async/await support with pytest-asyncio
- Pre-commit Integration: Tests run automatically on git commits with database lifecycle management
- Transaction Isolation: Uses
isolated_db_sessionfixture for complete test isolation - Automatic Cleanup: Database state is automatically rolled back after each test
- Docker Integration: Test database runs in Docker with automatic startup/teardown
- Performance Testing: Includes load tests for 100+ users and 200+ tasks
tests/
βββ conftest.py # Shared fixtures
βββ unit/domain/ # Domain unit tests
β βββ test_task.py # Task entity tests
β βββ test_task_list.py # TaskList entity tests
β βββ test_user.py # User entity tests
β βββ test_edge_cases.py # Edge case tests
βββ integration/ # Integration tests
β βββ test_database_integration.py # Database tests
β βββ repositories/ # Repository tests
βββ performance/ # Performance tests
βββ test_performance.py # Concurrency and performance tests
# Run all tests with automatic database setup
make test
# Run only unit tests (no database required)
make test-unit
# Run only integration tests (with database)
make test-integration
# Run tests with coverage report
make test-cov
# Watch mode for continuous testing
make test-watch
# Manual test execution with pytest
ENVIRONMENT=test poetry run pytest- Edge Cases: Boundary and extreme case validations
- Performance: Load tests (100+ users, 200+ tasks)
- Concurrency: Concurrent operation tests
- Integration: Entity relationship tests
- Coverage: 75%+ target
# Run migrations
make migrate
# Create new migration
make migration
# View migration history
make migration-history
# View current migration
make migration-current# Complete setup with Docker
make test-db
# Only create test database
python scripts/setup_test_db.py# Development
make install # Install dependencies and setup pre-commit hooks
make dev # Start development server
make format # Format code with black and isort
make lint # Run linting with flake8
make check # Run all quality checks (CI-friendly)
make clean # Clean temporary files
make update # Update dependencies
# Testing
make test # Run all tests with database setup
make test-unit # Run unit tests only
make test-integration # Run integration tests with database
make test-cov # Run tests with coverage report
make test-watch # Watch mode for continuous testing
# Database
make migrate # Run database migrations
make migration # Create new migration
make migration-history # Show migration history
make migration-current # Show current migration
make test-db-up # Start test database
make test-db-down # Stop test database
# Docker
make docker-dev # Start development database
make docker-test # Start test database
make docker-test-down # Stop test containers
make docker-prod # Start production environment
make docker-down # Stop all containers
make docker-down-all # Stop all containers (dev, test, prod)The project includes automated pre-commit hooks that:
- Start test database automatically
- Run database migrations
- Execute all tests
- Clean up test containers
- Ensure code quality before commits
Completed Phases:
- β Phase 1-4: Core infrastructure, domain models, API endpoints
- β Phase 5: Comprehensive testing with 71% coverage
- π§ Phase 6: Authentication (next priority)
Ready for Production Features:
- Complete CRUD operations for tasks and task lists
- Advanced filtering and pagination
- Robust error handling and validation
- Comprehensive test suite with database isolation
- Clean architecture with domain-driven design
# Install dependencies and pre-commit hooks
make install
# API: http://localhost:8000
# Docs: http://localhost:8000/docs- Immediate Priority: Implement JWT authentication system
- Short Term: Add email notifications and real-time features
- Long Term: Production deployment and monitoring
See the Authentication Implementation Plan for detailed next steps.
# Run development server
make dev
# Update dependencies
make update# Format code (DOESN'T fix imports/unused)
make format
# Check code quality issues (doesn't modify)
make lint
# Verify everything is correct (CI-friendly)
make check# 1. Write code
# 2. Format and check code
make format
make check
# 3. Run tests
make testThe project includes a comprehensive testing structure with clear separation between unit and integration tests.
# Run all tests (unit + integration)
make test
# Run only unit tests (fast, no database required)
make test-unit
# Run only integration tests (with database)
make test-integration
# Run with coverage report
make test-cov
# Watch mode for development
make test-watchTest Structure:
-
Unit Tests (
tests/unit/): Fast tests that don't require a database- Domain model tests (User, Task, TaskList)
- Business logic validation
- No external dependencies
-
Integration Tests (
tests/integration/): Tests that require database connectivity- Repository implementations
- Database operations
- Full application workflows
Key Features:
- Automatic Setup: Integration tests handle all database setup and teardown
- Test Isolation: Each integration test run uses a fresh database instance
- Fast Unit Tests: Unit tests run without database overhead
- Clear Separation: Distinct test categories for different purposes
- No Manual Setup: No need to run separate database setup commands
The project includes a comprehensive Postman collection (API.postman_collection.json) with example requests for all main API endpoints.
Features:
- Pre-configured requests for all CRUD operations
- Example payloads for creating and updating resources
- Authentication examples (when implemented)
- Environment variables for easy endpoint management
Usage:
- Import
API.postman_collection.jsoninto Postman - Set up environment variables (base URL:
http://localhost:8000) - Start the development server with
make dev - Test endpoints directly from Postman interface
Available Endpoints:
- User management (CRUD operations)
- Task list management
- Task operations with filtering
- Authentication flows (when implemented)
# Start only PostgreSQL in Docker (API runs locally for debugging)
make docker-devWith this setup:
- PostgreSQL runs in Docker (accessible at localhost:5432)
- API runs locally through your IDE for easy debugging
- Use the following connection string:
postgresql://postgres:postgres@localhost:5432/pytasks
# Start both PostgreSQL and API in Docker
make docker-prodWith this setup:
- Both PostgreSQL and API run in Docker
- API is accessible at http://localhost:8000
- API uses internal Docker networking to connect to PostgreSQL
# Stop all Docker containers and remove volumes
make docker-down| Command | Description |
|---|---|
make install |
Install dependencies and setup hooks |
make dev |
Run development server |
make test |
Run all tests (full lifecycle) |
make test-cov |
Run tests with coverage report |
make test-unit |
Run unit tests only |
make format |
Format code with black and isort |
make check |
Verify code quality (CI-friendly) |
make docker-dev |
Start PostgreSQL in Docker |
make docker-down |
Stop all Docker containers |
Here is a detailed project structure.
pytasks-api-rest/
βββ app/
β βββ __init__.py
β βββ main.py # FastAPI application entry point
β βββ config.py # Configuration settings
β βββ domain/ # Business entities and rules
β β βββ __init__.py
β β βββ models/ # Domain entities
β β β βββ __init__.py
β β β βββ task.py # Task entity
β β β βββ task_list.py # TaskList entity
β β β βββ user.py # User entity
β β βββ exceptions/ # Domain-specific exceptions
β β β βββ __init__.py
β β β βββ base.py
β β β βββ task.py
β β β βββ task_list.py
β β β βββ user.py
β β βββ repositories/ # Repository interfaces
β β β βββ __init__.py
β β β βββ task_repository.py
β β β βββ task_list_repository.py
β β β βββ user_repository.py
β β βββ services/ # Domain services
β β βββ __init__.py
β β βββ task_domain_service.py
β β βββ task_list_domain_service.py
β β βββ user_domain_service.py
β βββ application/ # Use cases and services
β β βββ services/ # Application validation services
β β β βββ __init__.py
β β β βββ task_validation_service.py
β β β βββ task_list_validation_service.py
β β β βββ user_validation_service.py
β β βββ use_cases/ # Application use cases
β β βββ __init__.py
β β βββ create_task.py
β β βββ create_task_list.py
β β βββ create_user.py
β β βββ get_task.py
β β βββ get_tasks.py
β β βββ update_task.py
β β βββ ... (other use cases)
β βββ infrastructure/ # Implementation details
β β βββ __init__.py
β β βββ database/ # Database related code
β β β βββ __init__.py
β β β βββ connection.py # Database connection setup
β β β βββ models/ # SQLAlchemy ORM models
β β β βββ __init__.py
β β β βββ task.py
β β β βββ task_list.py
β β β βββ user.py
β β βββ repositories/ # Repository implementations
β β β βββ __init__.py
β β β βββ task_repository_impl.py
β β β βββ task_list_repository_impl.py
β β β βββ user_repository_impl.py
β β βββ email/ # Email service implementation
β β βββ __init__.py
β β βββ notification_service.py
β βββ api/ # HTTP layer
β βββ __init__.py
β βββ dependencies.py # FastAPI dependencies
β βββ error_handlers.py # Exception handlers
β βββ routes/ # API endpoints
β β βββ __init__.py
β β βββ health.py # Health check routes
β β βββ tasks.py # Task routes
β β βββ task_lists.py # TaskList routes
β β βββ users.py # User routes
β βββ schemas/ # Pydantic schemas
β βββ __init__.py
β βββ common_schemas.py
β βββ task_schemas.py
β βββ task_list_schemas.py
β βββ user_schemas.py
βββ tests/ # Test suite
β βββ conftest.py # Global pytest fixtures
β βββ api/ # API endpoint tests (integration)
β β βββ conftest.py # API-specific fixtures
β β βββ test_task_lists_endpoints.py
β β βββ test_tasks_endpoints.py
β β βββ test_users_endpoints.py
β βββ unit/ # Unit tests
β β βββ conftest.py # Unit test fixtures
β β βββ domain/ # Domain layer tests
β β βββ application/ # Application layer tests
β β βββ api/ # API layer unit tests
β βββ integration/ # Integration tests
β β βββ repositories/ # Repository integration tests
β βββ factories/ # Test data factories
β βββ performance/ # Performance tests
βββ migrations/ # Database migrations
β βββ env.py # Alembic environment
β βββ script.py.mako # Migration template
β βββ versions/ # Migration files
βββ scripts/ # Utility scripts
β βββ run_tests.py
β βββ setup_test_db.py
β βββ test_runner.py
βββ .env.example # Environment variables template
βββ .flake8 # Flake8 configuration
βββ .gitignore # Git ignore file
βββ .pre-commit-config.yaml # Pre-commit hooks configuration
βββ alembic.ini # Alembic configuration
βββ docker-compose.yml # Main Docker compose
βββ docker-compose.dev.yml # Development environment
βββ docker-compose.test.yml # Test environment
βββ docker-compose.prod.yml # Production environment
βββ Dockerfile # Docker image definition
βββ Makefile # Development commands
βββ pyproject.toml # Project dependencies and config
βββ poetry.toml # Poetry configuration
βββ poetry.lock # Locked dependencies
βββ pytest-mocked.ini # Pytest configuration for mocked tests
βββ API.postman_collection.json # Postman API collection
βββ DECISION_LOG.md # Technical decisions documentation
βββ README.md # Project documentation