An open API service indexing awesome lists of open source software.

https://github.com/bozok/fastapi-backend-template

๐Ÿš€ Production-ready FastAPI backend template with async support, PostgreSQL, Redis, comprehensive testing, Docker setup, and modern development practices
https://github.com/bozok/fastapi-backend-template

api async async-await authentication backend boilerplate docker docker-compose fastapi jwt postgresql pre-commit production-ready pytest python redis rest-api ruff sqlmodel template

Last synced: about 2 months ago
JSON representation

๐Ÿš€ Production-ready FastAPI backend template with async support, PostgreSQL, Redis, comprehensive testing, Docker setup, and modern development practices

Awesome Lists containing this project

README

          

# ๐Ÿš€ FastAPI Clean Project

A production-ready, clean startup boilerplate for FastAPI projects with comprehensive async support, robust testing, and modern development practices.

## โœจ Features

### ๐Ÿ—๏ธ **Architecture & Design**

- **Clean Architecture** with separation of concerns
- **Async-first** design for all database operations and endpoints
- **SQLModel** with PostgreSQL for type-safe database operations
- **Alembic** for database migrations and schema management
- **Modular structure** with clear separation of API, business logic, and data layers

### ๐Ÿ” **Authentication & Security**

- **JWT-based authentication** with configurable expiration
- **Password hashing** with bcrypt
- **Rate limiting** with Redis backend
- **CORS configuration** for frontend integration
- **Comprehensive audit logging** for security events
- **IP filtering** capabilities

### ๐Ÿงช **Testing & Quality**

- **Comprehensive test suite** with async support
- **Transaction-based test isolation** for fast, reliable tests
- **Test categories**: Unit, Integration, Auth, CRUD
- **Coverage reporting** with pytest-cov
- **Async test fixtures** for database and HTTP client testing
- **Security testing** for authentication and authorization
- **Pre-commit hooks** with ruff linting, formatting, and automated testing

### ๐Ÿ“Š **Observability & Monitoring**

- **Structured logging** with Loguru
- **Audit trails** for user actions and security events
- **Performance monitoring** with configurable slow request thresholds
- **Health check endpoints** with service status
- **Request/response logging** with sensitive data masking

### ๐Ÿณ **DevOps & Deployment**

- **Docker Compose** setup for local development
- **Multi-stage Dockerfile** with security best practices
- **uv package manager** for fast dependency management
- **Makefile** with comprehensive development commands
- **Production-ready** configuration with environment-based settings

### ๐Ÿ”ง **Developer Experience**

- **Hot reload** in development mode
- **pgAdmin** for database management
- **Redis** for caching and rate limiting
- **Environment-based configuration** with .env support
- **Comprehensive error handling** with proper HTTP status codes

## ๐Ÿƒโ€โ™‚๏ธ Quick Start

### Prerequisites

- Docker & Docker Compose
- Make (optional, for simplified commands)

### 1. Clone and Setup

```bash
git clone
cd fastapi-clean-project

# Create environment file
make env
# Edit .env file with your configuration
```

### 2. Start Development Environment

```bash
# Start all services (FastAPI + PostgreSQL + Redis + pgAdmin)
make dev

# Or for fresh setup with migrations
make dev-fresh
```

### 3. Access Services

- **API**: http://localhost:8000
- **API Documentation**: http://localhost:8000/docs (if `ENABLE_DOCS=true`)
- **ReDoc**: http://localhost:8000/redoc (if `ENABLE_DOCS=true`)
- **OpenAPI Schema**: http://localhost:8000/openapi.json (if `ENABLE_DOCS=true`)
- **pgAdmin**: http://localhost:5050 (if `ENABLE_PGADMIN=true`, admin@example.com / admin)
- **Health Check**: http://localhost:8000/health

## ๐Ÿ“ Project Structure

```
โ”œโ”€โ”€ app/
โ”‚ โ”œโ”€โ”€ api/ # API routes and endpoints
โ”‚ โ”‚ โ”œโ”€โ”€ deps.py # API dependencies (auth, pagination)
โ”‚ โ”‚ โ””โ”€โ”€ v1/
โ”‚ โ”‚ โ”œโ”€โ”€ api.py # Router aggregation
โ”‚ โ”‚ โ””โ”€โ”€ endpoints/ # Individual endpoint modules
โ”‚ โ”‚ โ”œโ”€โ”€ auth.py # Authentication endpoints
โ”‚ โ”‚ โ””โ”€โ”€ user.py # User management endpoints
โ”‚ โ”œโ”€โ”€ core/ # Core application configuration
โ”‚ โ”‚ โ”œโ”€โ”€ config.py # Application settings
โ”‚ โ”‚ โ”œโ”€โ”€ database.py # Database connection and session
โ”‚ โ”‚ โ”œโ”€โ”€ logging.py # Logging configuration
โ”‚ โ”‚ โ”œโ”€โ”€ rate_limit.py # Rate limiting setup
โ”‚ โ”‚ โ””โ”€โ”€ security.py # Security utilities (JWT, passwords)
โ”‚ โ”œโ”€โ”€ crud/ # Data access layer
โ”‚ โ”‚ โ”œโ”€โ”€ base.py # Base CRUD operations
โ”‚ โ”‚ โ””โ”€โ”€ user.py # User-specific database operations
โ”‚ โ”œโ”€โ”€ middleware/ # Custom middleware
โ”‚ โ”‚ โ””โ”€โ”€ logging.py # Request/response logging middleware
โ”‚ โ”œโ”€โ”€ models/ # SQLModel database models
โ”‚ โ”‚ โ”œโ”€โ”€ base.py # Base model with common fields
โ”‚ โ”‚ โ””โ”€โ”€ user.py # User model
โ”‚ โ”œโ”€โ”€ schemas/ # Pydantic schemas for API
โ”‚ โ”‚ โ”œโ”€โ”€ response.py # Standard response schemas
โ”‚ โ”‚ โ”œโ”€โ”€ token.py # Authentication token schemas
โ”‚ โ”‚ โ””โ”€โ”€ user.py # User request/response schemas
โ”‚ โ”œโ”€โ”€ services/ # Business logic layer
โ”‚ โ”‚ โ””โ”€โ”€ user.py # User business logic
โ”‚ โ”œโ”€โ”€ utils/ # Utility functions
โ”‚ โ”‚ โ””โ”€โ”€ correlation.py # Request correlation IDs
โ”‚ โ””โ”€โ”€ main.py # FastAPI application factory
โ”œโ”€โ”€ alembic/ # Database migrations
โ”‚ โ”œโ”€โ”€ versions/ # Migration files
โ”‚ โ””โ”€โ”€ env.py # Alembic configuration
โ”œโ”€โ”€ tests/ # Comprehensive test suite
โ”‚ โ”œโ”€โ”€ conftest.py # Test configuration and fixtures
โ”‚ โ”œโ”€โ”€ test_api/ # API endpoint tests
โ”‚ โ”œโ”€โ”€ test_crud/ # Database operation tests
โ”‚ โ”œโ”€โ”€ test_services/ # Business logic tests
โ”‚ โ””โ”€โ”€ test_logging/ # Audit and logging tests
โ”œโ”€โ”€ docs/ # Documentation
โ”‚ โ”œโ”€โ”€ DOCKER.md # Docker usage guide
โ”‚ โ”œโ”€โ”€ LOGGING.md # Logging documentation
โ”‚ โ””โ”€โ”€ TESTING.md # Testing strategy and guidelines
โ”œโ”€โ”€ scripts/ # Deployment and utility scripts
โ”‚ โ”œโ”€โ”€ start.sh # Application startup script
โ”‚ โ””โ”€โ”€ init-db.sql # Database initialization
โ”œโ”€โ”€ docker-compose.local.yaml # Local development environment
โ”œโ”€โ”€ Dockerfile # Production-ready container
โ”œโ”€โ”€ Makefile # Development automation
โ””โ”€โ”€ pyproject.toml # Python dependencies and configuration
```

## ๐Ÿ› ๏ธ Development Commands

### Core Operations

```bash
make help # Show all available commands
make dev # Setup development environment
make up # Start all services
make down # Stop all services
make restart # Restart all services
make health # Check service health
```

### Database Operations

```bash
make db # Connect to PostgreSQL
make migrate # Apply database migrations
make migration # Create new migration (msg="description")
make db-reset # Reset database tables
```

### Testing

```bash
make test # Run all tests
make test-unit # Run unit tests only
make test-auth # Run authentication tests
make test-coverage # Run with coverage report
make test-watch # Run tests in watch mode
```

### Code Quality

```bash
make lint # Run linting checks
make format # Format code with ruff
```

### Pre-commit Hooks

```bash
# Install pre-commit (one-time setup)
pip install pre-commit
pre-commit install

# Pre-commit will now automatically run on every commit:
# - Ruff linting with auto-fix
# - Ruff code formatting
# - Full test suite in Docker container

# Manual pre-commit run (optional)
pre-commit run --all-files
```

### Utility Commands

```bash
make logs # Show all service logs
make logs-app # Show FastAPI logs only
make shell # Open shell in app container
make python # Open Python shell in container
```

## ๐Ÿ”ง Configuration

### Environment Variables

Key configuration options in `.env` file:

```bash
# Application
PROJECT_NAME="FastAPI Clean Project"
ENVIRONMENT=development # development, staging, production
DEBUG=true

# Database
DATABASE_URL="postgresql+asyncpg://user:pass@localhost:5432/db"
DATABASE_URL_TEST="postgresql+asyncpg://user:pass@localhost:5432/db_test"

# Security
SECRET_KEY="your-secret-key"
ACCESS_TOKEN_EXPIRE_MINUTES=30

# Features
ENABLE_DOCS=true # Enable/disable API documentation (disable in production)
ENABLE_RATE_LIMITING=true
ENABLE_PGADMIN=true # Enable/disable pgAdmin (disable in production)
ENABLE_AUDIT_LOGS=true
ENABLE_PERFORMANCE_LOGS=true

# External Services
REDIS_URL="redis://localhost:6379"
FRONTEND_URL="http://localhost:3000"
```

### Database Configuration

The project uses **Alembic** for database schema management:

```bash
# Create new migration
make migration msg="Add new field to User model"

# Apply migrations
make migrate

# View migration history
make migration-history
```

## ๐Ÿงช Testing Strategy

### Test Categories

- **Unit Tests** (`@pytest.mark.unit`): Fast, isolated function tests
- **Integration Tests** (`@pytest.mark.integration`): API endpoint tests
- **Auth Tests** (`@pytest.mark.auth`): Authentication and authorization
- **CRUD Tests** (`@pytest.mark.crud`): Database operation tests

### Test Features

- **Async test fixtures** with proper event loop management
- **Transaction-based isolation** for fast, reliable tests
- **Comprehensive auth testing** (JWT, permissions, rate limiting)
- **Database operation testing** with real PostgreSQL
- **Security testing** for authentication bypass attempts

### Coverage Areas

- โœ… User authentication and authorization
- โœ… CRUD operations with validation
- โœ… API endpoint responses and errors
- โœ… Rate limiting and security features
- โœ… Audit logging and monitoring
- โœ… Database migrations and schema changes

## ๐Ÿ“Š API Documentation

### Authentication Endpoints

- `POST /api/v1/auth/login` - User login with JWT token

### User Management Endpoints

- `POST /api/v1/users/` - Create new user (admin only)
- `GET /api/v1/users/me` - Get current user profile
- `PUT /api/v1/users/me` - Update current user profile
- `GET /api/v1/users/` - List users with pagination (admin only)

### System Endpoints

- `GET /health` - Health check with service status

### Rate Limiting

- **Configurable rate limiting** - Enable/disable via `ENABLE_RATE_LIMITING` environment variable
- **Login endpoint**: 5 attempts per minute (when enabled)
- **User endpoints**: Tiered rate limits (PUBLIC_READ, BURST_PROTECTION)
- **Redis backend** for distributed rate limiting
- **IP-based and API key-based** rate limiting support
- **Graceful degradation** - When disabled, all endpoints work without rate limiting

## ๐Ÿ” Security Features

### Authentication

- **JWT tokens** with configurable expiration
- **Secure password hashing** with bcrypt
- **Token validation** middleware
- **Role-based access control** (regular users vs superusers)

### Security Measures

- **Rate limiting** on sensitive endpoints
- **CORS configuration** for frontend integration
- **Input validation** with Pydantic schemas
- **SQL injection protection** with SQLModel/SQLAlchemy
- **Audit logging** for security events

### Best Practices

- **Non-root Docker containers** for security
- **Environment-based secrets** management
- **Comprehensive error handling** without information leakage
- **Request/response logging** with sensitive data masking

## ๐Ÿ“ˆ Monitoring & Logging

### Structured Logging

- **Request/response logging** with correlation IDs
- **Performance monitoring** with configurable thresholds
- **Security event logging** for audit trails
- **User action logging** for compliance

### Log Categories

- **Authentication attempts** (success/failure)
- **User actions** (create, update, delete)
- **Security events** (unauthorized access, rate limiting)
- **Performance metrics** (slow requests, database queries)
- **System events** (startup, shutdown, health checks)

### Configuration

```python
# Logging levels: DEBUG, INFO, WARNING, ERROR
LOG_LEVEL=INFO
ENABLE_JSON_LOGS=false # Set to true in production
ENABLE_AUDIT_LOGS=true
SLOW_REQUEST_THRESHOLD=1.0 # seconds
```

## ๐Ÿณ Docker & Deployment

### Local Development

```bash
# Start development environment
docker-compose -f docker-compose.local.yaml up -d

# Check service status
docker-compose ps

# View logs
docker-compose logs -f app
```

### Production Considerations

- **Multi-stage Dockerfile** for optimized images
- **Non-root user** for container security
- **Health checks** for container orchestration
- **Environment-based configuration** for different environments
- **Volume mounts** for persistent data

### Services

- **FastAPI App**: Main application server
- **PostgreSQL**: Primary database with persistence
- **Redis**: Caching and rate limiting
- **pgAdmin**: Database management interface

## ๐Ÿš€ Production Deployment

### Environment Setup

1. Update `.env` file with production values
2. Set `ENVIRONMENT=production`
3. Configure secure `SECRET_KEY`
4. Set `ENABLE_JSON_LOGS=true`
5. Configure proper CORS origins

### Database Setup

```bash
# Apply migrations in production
make migrate

# Create superuser (if needed)
docker-compose exec app uv run python -c "
from app.services.user import create_superuser
import asyncio
asyncio.run(create_superuser('admin@example.com', 'secure-password'))
"
```

### Security Checklist

- [ ] Strong `SECRET_KEY` configured
- [ ] Database credentials secured
- [ ] CORS origins properly configured
- [ ] Rate limiting enabled (`ENABLE_RATE_LIMITING=true`)
- [ ] API documentation disabled (`ENABLE_DOCS=false`)
- [ ] pgAdmin disabled (`ENABLE_PGADMIN=false`)
- [ ] JSON logging enabled
- [ ] Debug mode disabled
- [ ] Health checks configured

### ๐Ÿ“š API Documentation Management

The project supports dynamic enabling/disabling of API documentation:

**Development Mode** (`ENABLE_DOCS=true`):

- Swagger UI available at `/docs`
- ReDoc available at `/redoc`
- OpenAPI schema at `/openapi.json`
- Full interactive API exploration

**Production Mode** (`ENABLE_DOCS=false`):

- All documentation endpoints return 404
- Reduced attack surface
- No OpenAPI schema exposure
- Better security posture

```bash
# Disable docs for production
export ENABLE_DOCS=false

# Enable docs for development
export ENABLE_DOCS=true
```

### ๐Ÿ”ง pgAdmin Database Management

The project includes optional pgAdmin for database management with security controls:

**Development Mode** (`ENABLE_PGADMIN=true`):

- pgAdmin accessible at http://localhost:5050
- Default credentials: admin@example.com / admin
- Full database management interface
- Useful for development and debugging

**Production Mode** (`ENABLE_PGADMIN=false`):

- pgAdmin container not started
- Reduced security attack surface
- No database management web interface
- Direct database access only

```bash
# Disable pgAdmin for production
export ENABLE_PGADMIN=false

# Enable pgAdmin for development
export ENABLE_PGADMIN=true

# pgAdmin-specific commands
make pgadmin-start # Start pgAdmin only
make pgadmin-stop # Stop pgAdmin only
make pgadmin-status # Check pgAdmin status
```

**Security Note**: Always disable pgAdmin in production environments as it provides direct database access through a web interface.

## ๐Ÿค Contributing

### Development Setup

1. Fork the repository
2. Clone and setup: `git clone && cd clean-project`
3. **Install pre-commit hooks**: `pip install pre-commit && pre-commit install`
4. Create feature branch: `git checkout -b feature/amazing-feature`
5. Start development environment: `make dev`
6. Make changes following the code standards below
7. Commit changes (pre-commit hooks will run automatically)
8. Push to branch: `git push origin feature/amazing-feature`
9. Create Pull Request

### Code Quality & Standards

**๐Ÿ” Automated Quality Checks (Pre-commit Hooks):**

- โœ… **Ruff Linting** with auto-fix (`ruff check --fix`)
- โœ… **Code Formatting** with ruff (`ruff format`)
- โœ… **Full Test Suite** runs in Docker (`make test`)
- โœ… **Type Checking** via ruff's comprehensive rules
- โœ… **Import Sorting** and organization

**๐Ÿ“‹ Code Standards:**

- **Type hints** for all functions and methods
- **Docstrings** for public APIs
- **Test coverage** for new features
- **Error handling** with proper HTTP status codes
- **Async/await** for all I/O operations
- **Security best practices** (no hardcoded secrets, input validation)

**๐Ÿ”„ Development Workflow:**

```bash
# Your commits will automatically:
# 1. Fix linting issues
# 2. Format code consistently
# 3. Run full test suite
# 4. Prevent commit if tests fail

git add .
git commit -m "Add feature" # Pre-commit runs automatically

# Manual quality checks (optional):
make lint # Check code quality
make format # Format code
make test # Run tests
pre-commit run --all-files # Run all hooks manually
```

**๐Ÿ› ๏ธ Pre-commit Configuration:**

```yaml
# .pre-commit-config.yaml
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
hooks:
- id: ruff-check # Linting with auto-fix
- id: ruff-format # Code formatting
- repo: local
hooks:
- id: pytest-docker # Tests in Docker
```

## ๐Ÿ“š Documentation

- [Docker Guide](docs/DOCKER.md) - Detailed Docker usage and deployment
- [Testing Guide](docs/TESTING.md) - Comprehensive testing strategy
- [Logging Guide](docs/LOGGING.md) - Logging and monitoring setup

## ๐Ÿ›ฃ๏ธ Roadmap

- [ ] **Background Tasks** with Celery/RQ integration
- [ ] **Email Service** for notifications and password reset
- [ ] **File Upload** with cloud storage support
- [ ] **API Versioning** strategy and implementation
- [ ] **Metrics Collection** with Prometheus/Grafana
- [ ] **CI/CD Pipeline** with GitHub Actions
- [ ] **OpenAPI Schema** enhancements

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™ Acknowledgments

- **FastAPI** for the excellent async web framework
- **SQLModel** for type-safe database operations
- **Pydantic** for data validation and serialization
- **Alembic** for database migration management
- **Docker** for containerization and development environment

---

**Built with โค๏ธ for modern Python web development**

For questions, issues, or contributions, please open an issue or submit a pull request.