This document provides an overview of the fastapi-base project architecture, including the technology stack, project structure, and key design decisions.
The fastapi-base project follows a modern, microservices-oriented architecture with the following components:
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Load Balancer β β FastAPI β β PostgreSQL β
β (Optional) ββββββ Application ββββββ Database β
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β
βββββββββββββββββββ βββββββββββββββββββ
β Redis β β Celery β
β (Cache) β β Workers β
βββββββββββββββββββ βββββββββββββββββββ
User Request β Load Balancer β FastAPI App β Business Logic β Database
β
Cache Check (Redis) β Background Tasks (Celery)
- FastAPI - Modern, fast web framework for building APIs with Python
- Pydantic - Data validation and settings management using Python type annotations
- SQLModel - SQL databases in Python, designed for simplicity, compatibility, and robustness
- PostgreSQL - Advanced open-source relational database
- Alembic - Database migration tool for SQLAlchemy
- Redis - In-memory data structure store for caching and sessions
- Celery - Distributed task queue for background job processing
- Celery Beat - Scheduler for periodic tasks
- Docker - Containerization for consistent development and deployment
- uv - Fast Python package manager and resolver
- Gunicorn + Uvicorn - ASGI server for production deployment
- pytest - Testing framework with fixtures and plugins
- ruff - Fast Python linter and code formatter
- black - Code formatter for consistent style
- mypy - Static type checker
- pre-commit - Git hooks for code quality
fastapi-base/
βββ fastapi-base/ # Main application directory
β βββ src/ # Source code
β β βββ api/ # API layer
β β β βββ v1/ # API version 1
β β β β βββ endpoints/ # API endpoints
β β β β βββ deps.py # Dependencies
β β β βββ __init__.py
β β βββ core/ # Core configuration
β β β βββ config.py # Settings and configuration
β β β βββ security.py # Security utilities
β β β βββ __init__.py
β β βββ db/ # Database layer
β β β βββ base.py # Database base classes
β β β βββ init_db.py # Database initialization
β β β βββ session.py # Database session management
β β βββ models/ # Data models
β β β βββ user.py # User model
β β β βββ __init__.py
β β βββ schemas/ # Pydantic schemas
β β β βββ user.py # User schemas
β β β βββ __init__.py
β β βββ services/ # Business logic layer
β β β βββ user_service.py # User business logic
β β β βββ __init__.py
β β βββ utils/ # Utility functions
β β β βββ cache.py # Caching utilities
β β β βββ __init__.py
β β βββ migrations/ # Alembic migrations
β β β βββ versions/ # Migration files
β β β βββ env.py # Alembic configuration
β β β βββ script.py.mako # Migration template
β β βββ tasks/ # Celery tasks
β β β βββ __init__.py
β β β βββ example_tasks.py # Example background tasks
β β βββ main.py # Application entry point
β βββ tests/ # Test suite
β β βββ api/ # API tests
β β βββ models/ # Model tests
β β βββ services/ # Service tests
β β βββ conftest.py # Pytest configuration
β β βββ __init__.py
β βββ pyproject.toml # Project dependencies & config
β βββ Dockerfile # Development Docker image
β βββ alembic.ini # Alembic configuration
β βββ logconfig.yml # Logging configuration
βββ ops/ # Operations & deployment
β βββ production.Dockerfile # Production Docker image
βββ docs/ # Documentation
β βββ architecture.md # This file
β βββ developing.md # Development guide
β βββ README-pt.md # Portuguese README
β βββ README-fr.md # French README
β βββ README-es.md # Spanish README
βββ docker-compose.yml # Development environment
βββ Makefile # Development commands
βββ .env.example # Environment variables template
βββ CONTRIBUTING.md # Contribution guidelines
βββ README.md # Main documentation
- Request Reception: HTTP requests are received by the FastAPI application
- Middleware Processing: Security, CORS, and logging middleware process the request
- Route Resolution: FastAPI routes the request to the appropriate endpoint
- Dependency Injection: FastAPI resolves dependencies (database session, authentication, etc.)
- Business Logic: Service layer handles the business logic
- Data Access: Models interact with the PostgreSQL database through SQLModel
- Response Serialization: Pydantic schemas serialize the response data
- Response Return: JSON response is returned to the client
- Connection Management: Database connections are managed through SQLModel/SQLAlchemy
- Query Execution: Async queries are executed against PostgreSQL
- Transaction Handling: Database transactions ensure data consistency
- Migration Management: Alembic handles database schema changes
- Task Queuing: Tasks are queued in Redis through Celery
- Worker Processing: Celery workers process tasks asynchronously
- Result Storage: Task results are stored in Redis for retrieval
- Scheduling: Celery Beat handles periodic task scheduling
- Connection Encryption: SSL/TLS encryption for database connections
- Parameter Binding: Parameterized queries to prevent SQL injection
- Input Validation: Pydantic schemas validate all input data
- Secret Management: Sensitive data stored in environment variables
- Configuration Validation: Pydantic settings for configuration validation
- Environment Isolation: Separate configurations for development, testing, and production
- Structured Logging: JSON-formatted logs for better parsing
- Log Levels: Configurable log levels for different environments
- Request Tracing: Correlation IDs for request tracking
- Sentry Integration: Error tracking and performance monitoring
- Exception Handling: Comprehensive exception handling with proper HTTP status codes
- Health Checks: API endpoints for service health monitoring
- Database Connection Pooling: Efficient database connection management
- Redis Caching: In-memory caching for frequently accessed data
- Async Operations: Non-blocking I/O for better performance
- Docker Compose: Multi-container development setup
- Hot Reloading: Automatic code reloading for development
- Volume Mounting: Source code mounted for real-time changes
- Multi-stage Docker Build: Optimized production Docker images
- Gunicorn + Uvicorn: Production ASGI server configuration
- Environment Variables: Configuration through environment variables
- Health Checks: Container health monitoring
- Horizontal Scaling: Stateless design allows for easy horizontal scaling
- Database Connection Pooling: Efficient resource utilization
- Caching Strategy: Redis caching reduces database load
- Background Processing: Celery workers can be scaled independently
- Development: Debug mode enabled, verbose logging
- Testing: Isolated test database, mocked external services
- Production: Optimized for performance, error monitoring enabled
- Environment Variables: Feature toggles through environment configuration
- Runtime Configuration: Dynamic configuration changes without deployment
- Connection Pooling: Reuse database connections for efficiency
- Query Optimization: Efficient queries with proper indexing
- Migration Strategy: Zero-downtime database migrations
- Redis Integration: In-memory caching for frequent data
- Cache Invalidation: Proper cache invalidation strategies
- Session Management: Redis-based session storage
- Response Compression: Gzip compression for API responses
- Pagination: Efficient data pagination for large datasets
- Rate Limiting: API rate limiting to prevent abuse
- Pre-commit Hooks: Automated checks before commits
- Linting & Formatting: Code quality enforcement
- Type Checking: Static type analysis with mypy
- Testing: Comprehensive test suite execution
- Code Review: Peer review process for all changes
- GitHub Actions: Automated CI/CD pipeline
- Test Execution: Automated test running on pull requests
- Code Coverage: Coverage reporting and enforcement
- Security Scanning: Automated security vulnerability scanning
This architecture ensures a scalable, maintainable, and production-ready FastAPI application with modern development practices and comprehensive tooling.