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

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


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

Last synced: 20 days ago
JSON representation

Awesome Lists containing this project

README

          

# FastAPI Backend Template

A production-ready FastAPI backend template with modern Python stack, featuring clean architecture, comprehensive observability, and development best practices.

## ๐Ÿš€ Features

### Core Stack
- **FastAPI** - Modern, fast web framework for building APIs
- **SQLAlchemy 2.0** - Powerful ORM with async support
- **Alembic** - Database migration management
- **PostgreSQL** - Robust relational database
- **Redis** - High-performance caching and session storage
- **Celery** - Distributed task processing
- **UV** - Ultra-fast Python package manager

### Architecture & Design
- **Clean Architecture** - Domain-driven design with clear separation of concerns
- **Repository Pattern** - Data access abstraction layer
- **Dependency Injection** - Testable and maintainable code structure
- **Pydantic V2** - Data validation and serialization with type safety

### Observability & Monitoring
- **OpenTelemetry** - Distributed tracing and observability
- **Structured Logging** - JSON-formatted logs with correlation IDs
- **Health Checks** - Application and dependency health monitoring
- **Metrics Collection** - Performance and business metrics

### Development Experience
- **Pre-commit Hooks** - Automated code quality checks
- **Ruff** - Lightning-fast linting and formatting
- **MyPy** - Static type checking
- **Comprehensive Makefile** - Development workflow automation
- **Docker Support** - Containerized development and deployment

### Security & Authentication
- **JWT Authentication** - Secure token-based authentication
- **Password Hashing** - Bcrypt for secure password storage
- **Input Validation** - Pydantic-based request validation
- **CORS Middleware** - Cross-origin resource sharing configuration

## ๐Ÿ“ Project Structure

```
fastapi-backend-template/
โ”œโ”€โ”€ alembic/
โ”‚ โ”œโ”€โ”€ versions/ # Migration scripts
โ”‚ โ”œโ”€โ”€ env.py # Alembic environment
โ”‚ โ””โ”€โ”€ script.py.mako # Migration template
โ”œโ”€โ”€ app/
โ”‚ โ”œโ”€โ”€ api/v1/ # API route definitions
โ”‚ โ”‚ โ”œโ”€โ”€ auth.py # Authentication endpoints
โ”‚ โ”‚ โ”œโ”€โ”€ health.py # Health check endpoints
โ”‚ โ”‚ โ”œโ”€โ”€ task.py # Task management endpoints
โ”‚ โ”‚ โ””โ”€โ”€ users.py # User management endpoints
โ”‚ โ”œโ”€โ”€ cmd/
โ”‚ โ”‚ โ””โ”€โ”€ main.py # Application entrypoint
โ”‚ โ”œโ”€โ”€ core/ # Core application components
โ”‚ โ”‚ โ”œโ”€โ”€ celery_config.py # Celery configuration
โ”‚ โ”‚ โ”œโ”€โ”€ database.py # Database setup
โ”‚ โ”‚ โ”œโ”€โ”€ settings.py # Application settings
โ”‚ โ”‚ โ””โ”€โ”€ telemetry.py # OpenTelemetry setup
โ”‚ โ”œโ”€โ”€ dependencies/ # Dependency injection
โ”‚ โ”œโ”€โ”€ middlewares/ # Custom middlewares
โ”‚ โ”œโ”€โ”€ models/ # SQLAlchemy models
โ”‚ โ”œโ”€โ”€ repositories/ # Data access layer
โ”‚ โ”œโ”€โ”€ schemas/ # Pydantic models
โ”‚ โ”œโ”€โ”€ services/ # Business logic layer
โ”‚ โ””โ”€โ”€ tasks/ # Celery tasks
โ”œโ”€โ”€ scripts/ # Utility scripts and automation
โ”œโ”€โ”€ tests/ # Test suite
โ”‚ โ”œโ”€โ”€ conftest.py # Test configuration and fixtures
โ”‚ โ”œโ”€โ”€ unit/ # Unit tests
โ”‚ โ”œโ”€โ”€ integration/ # Integration tests
โ”‚ โ””โ”€โ”€ api/ # API endpoint tests
โ”œโ”€โ”€ alembic.ini # Alembic configuration
โ”œโ”€โ”€ Makefile # Development commands
โ”œโ”€โ”€ pyproject.toml # Project dependencies
โ””โ”€โ”€ uv.lock # Dependency lock file
```

## ๐Ÿ›  Quick Start

### Prerequisites
- Python 3.11+
- PostgreSQL
- Redis
- UV package manager

### Installation

1. **Clone the repository**
```bash
git clone
cd fastapi-backend-template
```

2. **Install dependencies**
```bash
make dev-install
```

3. **Set up environment variables**
```bash
cp .env.example .env
# Edit .env with your configuration
```

4. **Start services with Docker**
```bash
docker-compose up -d postgres redis
```

5. **Run database migrations**
```bash
make db-upgrade
```

6. **Start the application**
```bash
make dev
```

The API will be available at `http://localhost:8000` with interactive documentation at `http://localhost:8000/docs`.

## ๐Ÿ“‹ Development Commands

### Application
```bash
make dev # Start development server
make run # Start production server
make shell # Python REPL with app context
```

### Code Quality
```bash
make lint # Run linting checks
make format # Format code
make type-check # Run type checking
make check # Run all quality checks
```

### Database
```bash
make db-upgrade # Apply migrations
make db-downgrade # Rollback migration
make db-revision MESSAGE="description" # Create new migration
make db-reset # Reset database
```

### Celery Tasks
```bash
make celery-worker-dummy # Start Celery worker
make celery-beat # Start Celery scheduler
make celery-flower # Start Flower monitoring UI
make celery-monitor # Show task/worker stats
```

### Testing
```bash
make test # Run tests
make test-cov # Run tests with coverage
```

## ๐Ÿ”ง Configuration

### Environment Variables

Key configuration options in `.env`:

```bash
# Application
ENVIRONMENT=development
APP_NAME=FastAPI Backend Template
SECRET_KEY=your-secret-key

# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/dbname

# Redis
REDIS_URL=redis://localhost:6379

# OpenTelemetry
OTEL_SERVICE_NAME=fastapi-backend-template
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
OTEL_EXPORTER_OTLP_HEADERS=authorization=Bearer your-token

# Logging
LOG_LEVEL=INFO
```

### OpenTelemetry Setup

The application includes comprehensive observability with OpenTelemetry:

- **Distributed Tracing** - Track requests across services
- **Metrics Collection** - Application and business metrics
- **Log Correlation** - Structured logging with trace context
- **Export to OTLP** - Compatible with Jaeger, Zipkin, and observability platforms

Configure your observability backend by setting `OTEL_EXPORTER_OTLP_ENDPOINT` and authentication headers.

## ๐Ÿ— Architecture Overview

### Clean Architecture Layers

1. **API Layer** (`app/api/`) - HTTP endpoints and request/response handling
2. **Service Layer** (`app/services/`) - Business logic and orchestration
3. **Repository Layer** (`app/repositories/`) - Data access abstraction
4. **Model Layer** (`app/models/`) - Domain entities and database models

### Key Components

- **Dependencies** - FastAPI dependency injection for auth, database, etc.
- **Middlewares** - Request/response processing and CORS handling
- **Schemas** - Pydantic models for request/response validation
- **Tasks** - Asynchronous background job processing with Celery

## ๐Ÿงช Testing

The project follows testing best practices:

- **Unit Tests** - Test individual components in isolation
- **Integration Tests** - Test component interactions
- **API Tests** - End-to-end API testing
- **Fixtures** - Reusable test data and setup

Run the test suite:

```bash
make test # Basic test run
make test-cov # With coverage report
```

## ๐Ÿš€ Deployment

### Docker

Build and run with Docker:

```bash
make docker-build
make docker-run
```

### Production Considerations

- Set `ENVIRONMENT=production` in your environment
- Use a reverse proxy (nginx) for SSL termination
- Set up log aggregation and monitoring
- Configure OpenTelemetry exports to your observability platform

## ๐Ÿค Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Run quality checks: `make check`
5. Submit a pull request

### Code Quality

This project enforces high code quality standards:

- **Ruff** for linting and formatting
- **MyPy** for static type checking
- **Pre-commit hooks** for automated checks
- **100% type coverage** target

## ๐Ÿ“„ License

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

## ๐Ÿ“ Notes

- **Authentication & JWT**: The current JWT authentication implementation is for demonstration purposes. Replace with your production authentication system as needed.
- **Dummy Celery Tasks**: Sample tasks in `app/tasks/dummy.py` are provided as examples. Remove and implement your actual background tasks.
- **User Management**: Basic user model and endpoints are included as a starting point. Extend with your application-specific user requirements.

## ๐Ÿ™ Acknowledgments

- [FastAPI](https://fastapi.tiangolo.com/) for the excellent web framework
- [SQLAlchemy](https://sqlalchemy.org/) for the powerful ORM
- [OpenTelemetry](https://opentelemetry.io/) for observability standards
- [UV](https://github.com/astral-sh/uv) for fast package management