{"id":31618089,"url":"https://github.com/bozok/fastapi-backend-template","last_synced_at":"2026-04-10T11:32:15.005Z","repository":{"id":315435548,"uuid":"1059484679","full_name":"bozok/fastapi-backend-template","owner":"bozok","description":"🚀 Production-ready FastAPI backend template with async support, PostgreSQL, Redis, comprehensive testing, Docker setup, and modern development practices","archived":false,"fork":false,"pushed_at":"2025-09-18T14:12:53.000Z","size":115,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-10-06T13:47:28.223Z","etag":null,"topics":["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"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bozok.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-09-18T14:02:51.000Z","updated_at":"2025-09-18T14:45:12.000Z","dependencies_parsed_at":"2025-09-18T21:45:28.400Z","dependency_job_id":null,"html_url":"https://github.com/bozok/fastapi-backend-template","commit_stats":null,"previous_names":["bozok/fastapi-backend-template"],"tags_count":0,"template":true,"template_full_name":null,"purl":"pkg:github/bozok/fastapi-backend-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bozok%2Ffastapi-backend-template","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bozok%2Ffastapi-backend-template/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bozok%2Ffastapi-backend-template/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bozok%2Ffastapi-backend-template/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bozok","download_url":"https://codeload.github.com/bozok/fastapi-backend-template/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bozok%2Ffastapi-backend-template/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31641114,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-10T07:40:12.752Z","status":"ssl_error","status_checked_at":"2026-04-10T07:40:11.664Z","response_time":98,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["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"],"created_at":"2025-10-06T13:45:29.173Z","updated_at":"2026-04-10T11:32:14.987Z","avatar_url":"https://github.com/bozok.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🚀 FastAPI Clean Project\n\nA production-ready, clean startup boilerplate for FastAPI projects with comprehensive async support, robust testing, and modern development practices.\n\n## ✨ Features\n\n### 🏗️ **Architecture \u0026 Design**\n\n- **Clean Architecture** with separation of concerns\n- **Async-first** design for all database operations and endpoints\n- **SQLModel** with PostgreSQL for type-safe database operations\n- **Alembic** for database migrations and schema management\n- **Modular structure** with clear separation of API, business logic, and data layers\n\n### 🔐 **Authentication \u0026 Security**\n\n- **JWT-based authentication** with configurable expiration\n- **Password hashing** with bcrypt\n- **Rate limiting** with Redis backend\n- **CORS configuration** for frontend integration\n- **Comprehensive audit logging** for security events\n- **IP filtering** capabilities\n\n### 🧪 **Testing \u0026 Quality**\n\n- **Comprehensive test suite** with async support\n- **Transaction-based test isolation** for fast, reliable tests\n- **Test categories**: Unit, Integration, Auth, CRUD\n- **Coverage reporting** with pytest-cov\n- **Async test fixtures** for database and HTTP client testing\n- **Security testing** for authentication and authorization\n- **Pre-commit hooks** with ruff linting, formatting, and automated testing\n\n### 📊 **Observability \u0026 Monitoring**\n\n- **Structured logging** with Loguru\n- **Audit trails** for user actions and security events\n- **Performance monitoring** with configurable slow request thresholds\n- **Health check endpoints** with service status\n- **Request/response logging** with sensitive data masking\n\n### 🐳 **DevOps \u0026 Deployment**\n\n- **Docker Compose** setup for local development\n- **Multi-stage Dockerfile** with security best practices\n- **uv package manager** for fast dependency management\n- **Makefile** with comprehensive development commands\n- **Production-ready** configuration with environment-based settings\n\n### 🔧 **Developer Experience**\n\n- **Hot reload** in development mode\n- **pgAdmin** for database management\n- **Redis** for caching and rate limiting\n- **Environment-based configuration** with .env support\n- **Comprehensive error handling** with proper HTTP status codes\n\n## 🏃‍♂️ Quick Start\n\n### Prerequisites\n\n- Docker \u0026 Docker Compose\n- Make (optional, for simplified commands)\n\n### 1. Clone and Setup\n\n```bash\ngit clone \u003cyour-repo-url\u003e\ncd fastapi-clean-project\n\n# Create environment file\nmake env\n# Edit .env file with your configuration\n```\n\n### 2. Start Development Environment\n\n```bash\n# Start all services (FastAPI + PostgreSQL + Redis + pgAdmin)\nmake dev\n\n# Or for fresh setup with migrations\nmake dev-fresh\n```\n\n### 3. Access Services\n\n- **API**: http://localhost:8000\n- **API Documentation**: http://localhost:8000/docs (if `ENABLE_DOCS=true`)\n- **ReDoc**: http://localhost:8000/redoc (if `ENABLE_DOCS=true`)\n- **OpenAPI Schema**: http://localhost:8000/openapi.json (if `ENABLE_DOCS=true`)\n- **pgAdmin**: http://localhost:5050 (if `ENABLE_PGADMIN=true`, admin@example.com / admin)\n- **Health Check**: http://localhost:8000/health\n\n## 📁 Project Structure\n\n```\n├── app/\n│   ├── api/                    # API routes and endpoints\n│   │   ├── deps.py            # API dependencies (auth, pagination)\n│   │   └── v1/\n│   │       ├── api.py         # Router aggregation\n│   │       └── endpoints/     # Individual endpoint modules\n│   │           ├── auth.py    # Authentication endpoints\n│   │           └── user.py    # User management endpoints\n│   ├── core/                  # Core application configuration\n│   │   ├── config.py         # Application settings\n│   │   ├── database.py       # Database connection and session\n│   │   ├── logging.py        # Logging configuration\n│   │   ├── rate_limit.py     # Rate limiting setup\n│   │   └── security.py       # Security utilities (JWT, passwords)\n│   ├── crud/                  # Data access layer\n│   │   ├── base.py           # Base CRUD operations\n│   │   └── user.py           # User-specific database operations\n│   ├── middleware/            # Custom middleware\n│   │   └── logging.py        # Request/response logging middleware\n│   ├── models/                # SQLModel database models\n│   │   ├── base.py           # Base model with common fields\n│   │   └── user.py           # User model\n│   ├── schemas/               # Pydantic schemas for API\n│   │   ├── response.py       # Standard response schemas\n│   │   ├── token.py          # Authentication token schemas\n│   │   └── user.py           # User request/response schemas\n│   ├── services/              # Business logic layer\n│   │   └── user.py           # User business logic\n│   ├── utils/                 # Utility functions\n│   │   └── correlation.py    # Request correlation IDs\n│   └── main.py               # FastAPI application factory\n├── alembic/                   # Database migrations\n│   ├── versions/             # Migration files\n│   └── env.py               # Alembic configuration\n├── tests/                     # Comprehensive test suite\n│   ├── conftest.py           # Test configuration and fixtures\n│   ├── test_api/             # API endpoint tests\n│   ├── test_crud/            # Database operation tests\n│   ├── test_services/        # Business logic tests\n│   └── test_logging/         # Audit and logging tests\n├── docs/                      # Documentation\n│   ├── DOCKER.md             # Docker usage guide\n│   ├── LOGGING.md            # Logging documentation\n│   └── TESTING.md            # Testing strategy and guidelines\n├── scripts/                   # Deployment and utility scripts\n│   ├── start.sh              # Application startup script\n│   └── init-db.sql           # Database initialization\n├── docker-compose.local.yaml # Local development environment\n├── Dockerfile                # Production-ready container\n├── Makefile                  # Development automation\n└── pyproject.toml            # Python dependencies and configuration\n```\n\n## 🛠️ Development Commands\n\n### Core Operations\n\n```bash\nmake help           # Show all available commands\nmake dev            # Setup development environment\nmake up             # Start all services\nmake down           # Stop all services\nmake restart        # Restart all services\nmake health         # Check service health\n```\n\n### Database Operations\n\n```bash\nmake db             # Connect to PostgreSQL\nmake migrate        # Apply database migrations\nmake migration      # Create new migration (msg=\"description\")\nmake db-reset       # Reset database tables\n```\n\n### Testing\n\n```bash\nmake test           # Run all tests\nmake test-unit      # Run unit tests only\nmake test-auth      # Run authentication tests\nmake test-coverage  # Run with coverage report\nmake test-watch     # Run tests in watch mode\n```\n\n### Code Quality\n\n```bash\nmake lint           # Run linting checks\nmake format         # Format code with ruff\n```\n\n### Pre-commit Hooks\n\n```bash\n# Install pre-commit (one-time setup)\npip install pre-commit\npre-commit install\n\n# Pre-commit will now automatically run on every commit:\n# - Ruff linting with auto-fix\n# - Ruff code formatting\n# - Full test suite in Docker container\n\n# Manual pre-commit run (optional)\npre-commit run --all-files\n```\n\n### Utility Commands\n\n```bash\nmake logs           # Show all service logs\nmake logs-app       # Show FastAPI logs only\nmake shell          # Open shell in app container\nmake python         # Open Python shell in container\n```\n\n## 🔧 Configuration\n\n### Environment Variables\n\nKey configuration options in `.env` file:\n\n```bash\n# Application\nPROJECT_NAME=\"FastAPI Clean Project\"\nENVIRONMENT=development  # development, staging, production\nDEBUG=true\n\n# Database\nDATABASE_URL=\"postgresql+asyncpg://user:pass@localhost:5432/db\"\nDATABASE_URL_TEST=\"postgresql+asyncpg://user:pass@localhost:5432/db_test\"\n\n# Security\nSECRET_KEY=\"your-secret-key\"\nACCESS_TOKEN_EXPIRE_MINUTES=30\n\n# Features\nENABLE_DOCS=true  # Enable/disable API documentation (disable in production)\nENABLE_RATE_LIMITING=true\nENABLE_PGADMIN=true  # Enable/disable pgAdmin (disable in production)\nENABLE_AUDIT_LOGS=true\nENABLE_PERFORMANCE_LOGS=true\n\n# External Services\nREDIS_URL=\"redis://localhost:6379\"\nFRONTEND_URL=\"http://localhost:3000\"\n```\n\n### Database Configuration\n\nThe project uses **Alembic** for database schema management:\n\n```bash\n# Create new migration\nmake migration msg=\"Add new field to User model\"\n\n# Apply migrations\nmake migrate\n\n# View migration history\nmake migration-history\n```\n\n## 🧪 Testing Strategy\n\n### Test Categories\n\n- **Unit Tests** (`@pytest.mark.unit`): Fast, isolated function tests\n- **Integration Tests** (`@pytest.mark.integration`): API endpoint tests\n- **Auth Tests** (`@pytest.mark.auth`): Authentication and authorization\n- **CRUD Tests** (`@pytest.mark.crud`): Database operation tests\n\n### Test Features\n\n- **Async test fixtures** with proper event loop management\n- **Transaction-based isolation** for fast, reliable tests\n- **Comprehensive auth testing** (JWT, permissions, rate limiting)\n- **Database operation testing** with real PostgreSQL\n- **Security testing** for authentication bypass attempts\n\n### Coverage Areas\n\n- ✅ User authentication and authorization\n- ✅ CRUD operations with validation\n- ✅ API endpoint responses and errors\n- ✅ Rate limiting and security features\n- ✅ Audit logging and monitoring\n- ✅ Database migrations and schema changes\n\n## 📊 API Documentation\n\n### Authentication Endpoints\n\n- `POST /api/v1/auth/login` - User login with JWT token\n\n### User Management Endpoints\n\n- `POST /api/v1/users/` - Create new user (admin only)\n- `GET /api/v1/users/me` - Get current user profile\n- `PUT /api/v1/users/me` - Update current user profile\n- `GET /api/v1/users/` - List users with pagination (admin only)\n\n### System Endpoints\n\n- `GET /health` - Health check with service status\n\n### Rate Limiting\n\n- **Configurable rate limiting** - Enable/disable via `ENABLE_RATE_LIMITING` environment variable\n- **Login endpoint**: 5 attempts per minute (when enabled)\n- **User endpoints**: Tiered rate limits (PUBLIC_READ, BURST_PROTECTION)\n- **Redis backend** for distributed rate limiting\n- **IP-based and API key-based** rate limiting support\n- **Graceful degradation** - When disabled, all endpoints work without rate limiting\n\n## 🔐 Security Features\n\n### Authentication\n\n- **JWT tokens** with configurable expiration\n- **Secure password hashing** with bcrypt\n- **Token validation** middleware\n- **Role-based access control** (regular users vs superusers)\n\n### Security Measures\n\n- **Rate limiting** on sensitive endpoints\n- **CORS configuration** for frontend integration\n- **Input validation** with Pydantic schemas\n- **SQL injection protection** with SQLModel/SQLAlchemy\n- **Audit logging** for security events\n\n### Best Practices\n\n- **Non-root Docker containers** for security\n- **Environment-based secrets** management\n- **Comprehensive error handling** without information leakage\n- **Request/response logging** with sensitive data masking\n\n## 📈 Monitoring \u0026 Logging\n\n### Structured Logging\n\n- **Request/response logging** with correlation IDs\n- **Performance monitoring** with configurable thresholds\n- **Security event logging** for audit trails\n- **User action logging** for compliance\n\n### Log Categories\n\n- **Authentication attempts** (success/failure)\n- **User actions** (create, update, delete)\n- **Security events** (unauthorized access, rate limiting)\n- **Performance metrics** (slow requests, database queries)\n- **System events** (startup, shutdown, health checks)\n\n### Configuration\n\n```python\n# Logging levels: DEBUG, INFO, WARNING, ERROR\nLOG_LEVEL=INFO\nENABLE_JSON_LOGS=false  # Set to true in production\nENABLE_AUDIT_LOGS=true\nSLOW_REQUEST_THRESHOLD=1.0  # seconds\n```\n\n## 🐳 Docker \u0026 Deployment\n\n### Local Development\n\n```bash\n# Start development environment\ndocker-compose -f docker-compose.local.yaml up -d\n\n# Check service status\ndocker-compose ps\n\n# View logs\ndocker-compose logs -f app\n```\n\n### Production Considerations\n\n- **Multi-stage Dockerfile** for optimized images\n- **Non-root user** for container security\n- **Health checks** for container orchestration\n- **Environment-based configuration** for different environments\n- **Volume mounts** for persistent data\n\n### Services\n\n- **FastAPI App**: Main application server\n- **PostgreSQL**: Primary database with persistence\n- **Redis**: Caching and rate limiting\n- **pgAdmin**: Database management interface\n\n## 🚀 Production Deployment\n\n### Environment Setup\n\n1. Update `.env` file with production values\n2. Set `ENVIRONMENT=production`\n3. Configure secure `SECRET_KEY`\n4. Set `ENABLE_JSON_LOGS=true`\n5. Configure proper CORS origins\n\n### Database Setup\n\n```bash\n# Apply migrations in production\nmake migrate\n\n# Create superuser (if needed)\ndocker-compose exec app uv run python -c \"\nfrom app.services.user import create_superuser\nimport asyncio\nasyncio.run(create_superuser('admin@example.com', 'secure-password'))\n\"\n```\n\n### Security Checklist\n\n- [ ] Strong `SECRET_KEY` configured\n- [ ] Database credentials secured\n- [ ] CORS origins properly configured\n- [ ] Rate limiting enabled (`ENABLE_RATE_LIMITING=true`)\n- [ ] API documentation disabled (`ENABLE_DOCS=false`)\n- [ ] pgAdmin disabled (`ENABLE_PGADMIN=false`)\n- [ ] JSON logging enabled\n- [ ] Debug mode disabled\n- [ ] Health checks configured\n\n### 📚 API Documentation Management\n\nThe project supports dynamic enabling/disabling of API documentation:\n\n**Development Mode** (`ENABLE_DOCS=true`):\n\n- Swagger UI available at `/docs`\n- ReDoc available at `/redoc`\n- OpenAPI schema at `/openapi.json`\n- Full interactive API exploration\n\n**Production Mode** (`ENABLE_DOCS=false`):\n\n- All documentation endpoints return 404\n- Reduced attack surface\n- No OpenAPI schema exposure\n- Better security posture\n\n```bash\n# Disable docs for production\nexport ENABLE_DOCS=false\n\n# Enable docs for development\nexport ENABLE_DOCS=true\n```\n\n### 🔧 pgAdmin Database Management\n\nThe project includes optional pgAdmin for database management with security controls:\n\n**Development Mode** (`ENABLE_PGADMIN=true`):\n\n- pgAdmin accessible at http://localhost:5050\n- Default credentials: admin@example.com / admin\n- Full database management interface\n- Useful for development and debugging\n\n**Production Mode** (`ENABLE_PGADMIN=false`):\n\n- pgAdmin container not started\n- Reduced security attack surface\n- No database management web interface\n- Direct database access only\n\n```bash\n# Disable pgAdmin for production\nexport ENABLE_PGADMIN=false\n\n# Enable pgAdmin for development\nexport ENABLE_PGADMIN=true\n\n# pgAdmin-specific commands\nmake pgadmin-start    # Start pgAdmin only\nmake pgadmin-stop     # Stop pgAdmin only\nmake pgadmin-status   # Check pgAdmin status\n```\n\n**Security Note**: Always disable pgAdmin in production environments as it provides direct database access through a web interface.\n\n## 🤝 Contributing\n\n### Development Setup\n\n1. Fork the repository\n2. Clone and setup: `git clone \u003crepo\u003e \u0026\u0026 cd clean-project`\n3. **Install pre-commit hooks**: `pip install pre-commit \u0026\u0026 pre-commit install`\n4. Create feature branch: `git checkout -b feature/amazing-feature`\n5. Start development environment: `make dev`\n6. Make changes following the code standards below\n7. Commit changes (pre-commit hooks will run automatically)\n8. Push to branch: `git push origin feature/amazing-feature`\n9. Create Pull Request\n\n### Code Quality \u0026 Standards\n\n**🔍 Automated Quality Checks (Pre-commit Hooks):**\n\n- ✅ **Ruff Linting** with auto-fix (`ruff check --fix`)\n- ✅ **Code Formatting** with ruff (`ruff format`)\n- ✅ **Full Test Suite** runs in Docker (`make test`)\n- ✅ **Type Checking** via ruff's comprehensive rules\n- ✅ **Import Sorting** and organization\n\n**📋 Code Standards:**\n\n- **Type hints** for all functions and methods\n- **Docstrings** for public APIs\n- **Test coverage** for new features\n- **Error handling** with proper HTTP status codes\n- **Async/await** for all I/O operations\n- **Security best practices** (no hardcoded secrets, input validation)\n\n**🔄 Development Workflow:**\n\n```bash\n# Your commits will automatically:\n# 1. Fix linting issues\n# 2. Format code consistently\n# 3. Run full test suite\n# 4. Prevent commit if tests fail\n\ngit add .\ngit commit -m \"Add feature\"  # Pre-commit runs automatically\n\n# Manual quality checks (optional):\nmake lint    # Check code quality\nmake format  # Format code\nmake test    # Run tests\npre-commit run --all-files  # Run all hooks manually\n```\n\n**🛠️ Pre-commit Configuration:**\n\n```yaml\n# .pre-commit-config.yaml\nrepos:\n  - repo: https://github.com/astral-sh/ruff-pre-commit\n    hooks:\n      - id: ruff-check # Linting with auto-fix\n      - id: ruff-format # Code formatting\n  - repo: local\n    hooks:\n      - id: pytest-docker # Tests in Docker\n```\n\n## 📚 Documentation\n\n- [Docker Guide](docs/DOCKER.md) - Detailed Docker usage and deployment\n- [Testing Guide](docs/TESTING.md) - Comprehensive testing strategy\n- [Logging Guide](docs/LOGGING.md) - Logging and monitoring setup\n\n## 🛣️ Roadmap\n\n- [ ] **Background Tasks** with Celery/RQ integration\n- [ ] **Email Service** for notifications and password reset\n- [ ] **File Upload** with cloud storage support\n- [ ] **API Versioning** strategy and implementation\n- [ ] **Metrics Collection** with Prometheus/Grafana\n- [ ] **CI/CD Pipeline** with GitHub Actions\n- [ ] **OpenAPI Schema** enhancements\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 🙏 Acknowledgments\n\n- **FastAPI** for the excellent async web framework\n- **SQLModel** for type-safe database operations\n- **Pydantic** for data validation and serialization\n- **Alembic** for database migration management\n- **Docker** for containerization and development environment\n\n---\n\n**Built with ❤️ for modern Python web development**\n\nFor questions, issues, or contributions, please open an issue or submit a pull request.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbozok%2Ffastapi-backend-template","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbozok%2Ffastapi-backend-template","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbozok%2Ffastapi-backend-template/lists"}