Skip to content

Repository files navigation

Python Backend API Template

Professional REST API template for GitLab projects using FastAPI, SQLAlchemy, and PostgreSQL.

🚀 Features

  • FastAPI - Modern, fast web framework
  • SQLAlchemy - Async ORM for database operations
  • PostgreSQL - Robust relational database
  • Redis - Caching and session management
  • Celery - Background task processing
  • JWT Authentication - Secure token-based auth
  • Pydantic - Data validation and settings
  • Alembic - Database migrations
  • Typer CLI - Powerful command-line interface
  • Webhooks - Webhook handlers structure
  • Docker - Containerization support
  • CI/CD - GitLab pipeline included
  • Pre-commit - Automated code quality checks
  • Testing - Comprehensive test suite (70%+ coverage)
  • Type Hints - Full type coverage
  • OpenAPI - Auto-generated documentation

📁 Project Structure

.
├── app/                      # Application source code
│   ├── api/                  # API endpoints
│   │   └── v1/               # API version 1
│   │       ├── routes/       # API route handlers
│   │       └── webhooks/     # Webhook handlers
│   ├── config/               # Configuration (settings + JSON files)
│   ├── core/                 # Core functionality (DB, cache, security)
│   ├── models/               # SQLAlchemy models
│   ├── schemas/              # Pydantic schemas
│   ├── services/             # Business logic layer
│   ├── repositories/         # Data access layer
│   ├── tasks/                # Celery background tasks
│   ├── middleware/           # Custom middleware
│   ├── utils/                # Utility functions
│   ├── cli.py                # CLI commands
│   └── main.py               # Application entry point
├── tests/                    # Test suite
│   ├── unit/                 # Unit tests
│   └── integration/          # Integration tests
├── docs/                     # Documentation
├── alembic/                  # Database migrations
├── .gitlab/                  # GitLab templates
│   ├── issue_templates/      # Issue templates
│   └── merge_request_templates/  # MR templates
├── .gitlab-ci.yml            # CI/CD pipeline
├── Dockerfile                # Container definition
├── docker-compose.yml        # Multi-container setup
└── requirements.txt          # Python dependencies

🚦 Quick Start

Prerequisites

  • Python 3.11+
  • PostgreSQL 15+
  • Redis 7+
  • Git

Installation

  1. Clone repository
git clone <repository-url>
cd rest-python-backend-boilerplate
  1. Create virtual environment
python -m venv .venv
source .venv/bin/activate  # Windows: .venv\Scripts\activate
  1. Install dependencies & setup
make setup
# Or manually:
# pip install -r requirements.txt -r requirements-dev.txt
# pre-commit install
# git config commit.template .gitmessage
  1. Configure environment
cp .env.example .env
# Edit .env with your configuration
  1. Run migrations
alembic upgrade head
  1. Start server
python -m app.main
# Or use CLI
python -m app.cli run-server

Visit:

Using Docker

docker-compose up -d

CLI Commands

# Run server
python -m app.cli run-server --reload

# Database operations
python -m app.cli init-db
python -m app.cli run-migrations
python -m app.cli create-migration "Add new field"

# Create superuser
python -m app.cli create-superuser

# Run Celery worker
python -m app.cli run-worker

# Run Celery beat
python -m app.cli run-beat

# Code quality
python -m app.cli lint
python -m app.cli format-code
python -m app.cli test

🛠️ Development

Setup Git Commit Template

git config commit.template .gitmessage

Setup Pre-commit Hooks

# Install pre-commit hooks
pre-commit install

# Run manually on all files
pre-commit run --all-files

Run Tests

# All tests
pytest

# With coverage
pytest --cov=src --cov-report=html

# Specific tests
pytest tests/unit/test_security.py -v

Code Quality

# Format code
black app/ tests/
isort app/ tests/

# Lint
ruff check app/ tests/

# Type check
mypy app/

# Or use CLI
python -m app.cli format-code
python -m app.cli lint

Database Migrations

# Create migration
alembic revision --autogenerate -m "description"

# Apply migrations
alembic upgrade head

# Rollback
alembic downgrade -1

📚 Documentation

🔒 Security

  • JWT token authentication
  • Password hashing with bcrypt
  • CORS configuration
  • Environment variable management
  • SQL injection protection (ORM)

🧪 Testing

Unit Tests

pytest tests/unit/ -v

Integration Tests

pytest tests/integration/ -v

Coverage Report

pytest --cov=src --cov-report=html
open htmlcov/index.html

🚀 Deployment

Environment Variables

Required variables:

  • DATABASE_URL - PostgreSQL connection string
  • REDIS_URL - Redis connection string
  • SECRET_KEY - JWT secret key

Docker Deployment

docker build -t api:latest .
docker run -p 8000:8000 --env-file .env api:latest

CI/CD Pipeline

GitLab CI/CD pipeline includes:

  1. Lint - Code formatting, linting, type checking, security scans
  2. Test - Unit and integration tests on Python 3.10, 3.11, 3.12
  3. Build - Build and push Docker images
  4. Deploy - Deploy to staging/production (manual)

Features:

  • Configurable inputs (coverage threshold, Python versions, etc.)
  • Parallel test execution
  • PostgreSQL + Redis services
  • Coverage enforcement (70% minimum)
  • Multiple Python version testing

See CI/CD Documentation for details.

🤝 Contributing

  1. Setup development environment: make setup
  2. Create issue describing the change
  3. Create branch from develop
  4. Make changes following code style
  5. Pre-commit hooks run automatically
  6. Write/update tests (min 70% coverage)
  7. Submit merge request
  8. Wait for review and approval

See Contributing Guide for detailed workflow.

Pre-commit Hooks

  • ✅ Code formatting (Black, isort)
  • ✅ Linting (Ruff)
  • ✅ Type checking (MyPy)
  • ✅ Security checks (Bandit)
  • ✅ Test coverage (min 70%)

📝 GitLab Templates

Issue Templates

  • Bug Report
  • Feature Request
  • Task

Merge Request Template

  • Description
  • Related issues
  • Type of change
  • Testing checklist
  • Deployment notes

🏗️ Architecture

Layered architecture:

  1. API Layer - Request/response handling
  2. Service Layer - Business logic
  3. Repository Layer - Data access
  4. Model Layer - Data models

🔧 Configuration

Configuration via environment variables or .env file.

See .env.example for all options.

📊 Monitoring

  • Health check endpoint: /api/v1/health
  • Structured logging (JSON format)
  • Request/response logging

📄 License

MIT License

🙋 Support

Create an issue in GitLab for:

  • Bug reports
  • Feature requests
  • Questions
  • Documentation improvements

About

REST API Python Boilerplate

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages