A production-ready FastAPI project template with modern best practices, async support, JWT authentication, and PostgreSQL integration.
- π FastAPI - Modern, fast web framework for building APIs, with versioned routers (
/v1,/v2) - π PostgreSQL - Async database integration with SQLAlchemy 2.0 and Alembic migrations
- π JWT Authentication - Secure token-based authentication with token blacklisting
- ποΈ Clean Architecture - Repository pattern, dependency injection, and enforced module boundaries (tach)
- π Security - CSRF, rate limiting, and security headers middleware
- π³ Docker Compose - Backend, Postgres, and Redis ready to run
- π§ͺ CI & Testing - Pytest with coverage gating, plus lint/type/security checks in GitHub Actions
Plus optional integrations for caching, background jobs, cloud storage, Firebase, Apple Pay, and email delivery. For the full list of integrations and services, see docs/features.md.
-
Clone the repository
git clone <your-repo-url> cd FastApi-Template
-
Install dependencies
Create a virtual environment
python -m venv .venv
Activate the virtual environment
# On Linux / macOS source .venv/bin/activate # On Windows (PowerShell) .venv\Scripts\Activate.ps1
Install dependencies
# Install dependencies uv sync --all-groups # Install optional integrations as needed uv sync --all-groups --all-extras # Install pre-commit hooks pre-commit install
Note: If you are facing SSL issues on Windows, use:
uv sync --all-groups --native-tls uv sync --native-tls --all-extras
-
Set up environment variables
cp .env.example .env # Edit .env with your configuration -
Configure database
# Create database createdb fastapi_template # Run migrations alembic upgrade head
-
Start the development server
python main.py
The API will be available at http://localhost:8799 with interactive documentation at:
http://localhost:8799/v1/docshttp://localhost:8799/v2/docs
This repository doubles as a Copier template β generate a brand-new FastAPI project from it, with your own name, author info, and settings, without cloning and hand-editing:
# Run copier directly with uvx - no install/PATH setup needed
uvx --with jinja2-time copier copy gh:eslam5464/Fastapi-Template <new-project-dir> --trustNote: --with jinja2-time is required because this template uses a Jinja extension (for the LICENSE copyright year) that isn't one of copier's own dependencies β without it you'll see Copier could not load some Jinja extensions: No module named 'jinja2_time'. uvx/uv tool run installs it alongside copier for this one run only.
Alternative: if you'd rather have copier installed permanently (e.g. for copier update later), use uv tool install copier --with jinja2-time instead. On Windows, that installs into a user tools directory that's often not yet on PATH in your current terminal session β if you see 'copier' is not recognized as an internal or external command right after installing, either open a new terminal window, or run uv tool update-shell and then restart the terminal. The uvx command above sidesteps the PATH issue entirely since it doesn't need copier installed anywhere persistent.
You'll be prompted for a project name, description, author name/email, GitHub username, Python version, and whether to include Apple Pay support. Everything identity-specific β the pyproject.toml name, Docker container names, the Postgres schema, README.md, LICENSE, CODEOWNERS β is filled in automatically; see docs/features.md for what ships by default versus what's opt-in.
--trust is required because generation runs a small post-processing script (scripts/generate/post_gen.py) that removes unused Apple Pay files when you opt out, regenerates uv.lock, and runs git init for you.
This repo itself stays fully runnable the whole time β the template mechanics live alongside the real code as .jinja-suffixed files (pyproject.toml.jinja, docker-compose.yml.jinja, etc.) plus copier.yml, none of which change how you build, test, or run this repo directly.
Detailed documentation is available in the docs/ folder:
- LLM Index - Canonical documentation entrypoint for AI and quick doc navigation
- Features - Full list of integrations and services, with setup notes
- Architecture Overview - Current system design and versioned routing model
- Backend Architecture Guide - Layered architecture deep dive
- API Reference - Versioned endpoint and auth reference
- Getting Started - Setup and first run
- Development Guide - Local workflow and quality commands
- Contributing - Contribution and PR standards
- Versioning - SemVer rules and how to bump the release version
- Deployment Guide - Production deployment checklist
- Strategy Vision - Product and technical direction
- Roadmap - Milestones and priorities
- Changelog - Release history
βββ app/
β βββ api/ # API routes and endpoints
β β βββ v1/ # API version 1
β β β βββ endpoints/ # Individual endpoint modules
β β β βββ deps/ # Dependencies (auth, database)
β β βββ v2/ # API version 2
β βββ core/ # Core functionality
β β βββ auth.py # Authentication utilities
β β βββ config.py # Configuration management
β β βββ db.py # Database connection
β β βββ exceptions.py # Custom exceptions
β βββ models/ # SQLAlchemy models
β βββ schemas/ # Pydantic schemas
β βββ repos/ # Repository pattern implementations
β βββ services/ # Business logic and external services
β βββ middleware/ # Custom middleware
β βββ alembic/ # Database migrations
βββ docs/ # Detailed documentation
βββ scripts/ # Utility scripts
βββ logs/ # Application logs (Generated at runtime)
The template includes a complete JWT-based authentication system:
- User registration and login
- Access and refresh tokens
- Password hashing with Argon2 (via pwdlib)
- Token blacklisting for secure logout
- Protected routes with dependency injection
from app.api.v1.deps.auth import get_current_user
@router.get("/protected")
async def protected_route(current_user: User = Depends(get_current_user)):
return {"message": f"Hello {current_user.username}!"}The project includes several tools for maintaining code quality:
- Black - Code formatting
- Pre-commit hooks - Automated checks before commits
- Loguru - Structured logging
- Environment validation - Pydantic settings
The project maintains comprehensive test coverage with ~90% code coverage across all modules:
# Run all tests with verbose output and detailed reporting
uv run pytest -v
# Run tests with coverage report
uv run pytest tests/ --cov=app --cov-report=term --cov-report=html
# View detailed HTML coverage report
# Open htmlcov/index.html in your browserCoverage Scope:
- β Unit, service, and integration tests
- π Terminal and HTML coverage reports
- π― Tests cover API endpoints, authentication, database operations, services, middleware, and utilities
Run security analysis using Bandit:
uv run bandit -r app -f json -o bandit_results.jsonuv run pytest -vThe project uses Celery for background job processing with Redis as the message broker.
# Linux/macOS
./scripts/celery_worker.sh
# Windows
.\scripts\celery_worker.bat
# Or directly
celery -A app.services.task_queue worker --loglevel=info --pool=solo# Linux/macOS
./scripts/celery_beat.sh
# Windows
.\scripts\celery_beat.bat
# Or directly
celery -A app.services.task_queue beat --loglevel=infoAvailable Tasks:
seed_fake_users- Generates fake users for testing (runs every 10 seconds whenENABLE_DATA_SEEDING=true)
Use the scripts provided (Recommended):
# Run database migrations for linux/macOS
./scripts/alembic.sh
# Run database migrations for windows
.\scripts\alembic.batOr use Alembic commands directly:
# Create a new migration
alembic revision --autogenerate -m "Description"
# Apply migrations
alembic upgrade head
# Rollback migrations
alembic downgrade -1The application supports multiple environments:
- local - Development with debug features
- dev - Development server
- stg - Pre-production testing (Staging)
- prd - Production deployment
Configure via environment variables or .env file:
# Database
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your-postgres-password
POSTGRES_DB=postgres
POSTGRES_DB_SCHEMA=fastapi_template
# Security
SECRET_KEY=your-secret-key
ACCESS_TOKEN_EXPIRE_SECONDS=2582000
REFRESH_TOKEN_EXPIRE_SECONDS=2592000
# Server
BACKEND_HOST=localhost
BACKEND_PORT=8799
CURRENT_ENVIRONMENT=local
# Redis (for caching and rate limiting)
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASS=your-redis-password
# Rate Limiting
RATE_LIMIT_ENABLED=true
RATE_LIMIT_DEFAULT=100
RATE_LIMIT_WINDOW=60
# Celery & Background Tasks
ENABLE_DATA_SEEDING=false
SEEDING_USER_COUNT=100
# Email Providers
resend_api_key=your_resend_api_key_here
brevo_api_key=your_brevo_api_key_hereCore dependencies (FastAPI, SQLAlchemy, Alembic, Pydantic, Uvicorn) are always installed. Optional integrations (Redis, Celery, Firebase, GCS, BackBlaze, Apple Pay, email providers) are opt-in extras β install only what you need:
uv sync --extra email
uv sync --extra cloud-service
uv sync --extra cache
uv sync --extra task-queue
uv sync --extra apple-servicesSee docs/features.md for what each extra provides and how to configure it.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- FastAPI - The amazing web framework
- SQLAlchemy - The Python SQL toolkit
- Pydantic - Data validation library
- Fastapi Template by tiangolo - A FastAPI project template
- Fastapi best practices - Inspiration for best practices
- Fastapi Tips - Useful tips and tricks from FastAPI Expert
- Fastapi structure - Project structure inspiration