🚀 Production-ready FastAPI template with JWT authentication, PostgreSQL integration, async support, clean architecture, and modern development tools.
概要
A production-ready FastAPI project template with modern best practices, async support, JWT authentication, and PostgreSQL integration. - - Modern, fast web framework for building APIs, with versioned routers (/v1, /v2) - - Async database integration with SQLAlchemy 2.0 and Alembic migrations - - Secure token-based authentication with token blacklisting - - Repository pattern, dependency injection, and enforced module boundaries (tach) - - CSRF, rate limiting, and security headers middleware - - Backend, Postgres, and Redis ready to run - - 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 .
README
FastAPI Template
A production-ready FastAPI project template with modern best practices, async support, JWT authentication, and PostgreSQL integration.
✨ Features
- 🚀 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.
🚀 Quick Start
Prerequisites
Installation
-
Clone the repository
git clone cd FastApi-Template -
Install dependencies
Create a virtual environment
python -m venv .venvActivate the virtual environment
# On Linux / macOS source .venv/bin/activate # On Windows (PowerShell) .venv\Scripts\Activate.ps1Install dependencies
# Install dependencies uv sync --all-groups # Install optional integrations as needed uv sync --all-groups --all-extras # Install pre-commit hooks pre-commit installNote: 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
🧬 Using This as a Template
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 copier copy gh:eslam5464/Fastapi-Template --trust
Alternative: if you’d rather have copier installed permanently (e.g. for copier update later), use uv tool install copier 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 substitutes your answers into the copied files, 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 entirely in copier.yml and scripts/generate/post_gen.py, which run after copying and edit the same real files you already build, test, and run directly. There are no separate .jinja template files to keep in sync.
🤖 AI Coding Assistant Support
This repo packages its whole architecture — layering rules, SQLAlchemy patterns, auth/ security conventions, testing gotchas, CI/tooling config, and the Copier generation mechanics above — as something an AI coding assistant can actually use, not just read about. It has two jobs, for whichever assistant you use:
- Scaffold a brand-new project with this architecture by driving the real Copier template (not re-typing boilerplate from memory, so it can’t drift from what’s actually here).
- Extend or review an existing instance of this architecture — this repo, or any project generated from it — adding new endpoints/services/models consistently with what’s already there, or auditing a diff/codebase against the documented rules and anti-patterns catalog before you merge it. Reviews always list what’s wrong and why, and what’s suggested instead, and leave applying any fix up to you.
Install it in another project — one command, any of 76+ agents
The canonical source lives at
.claude/skills/fastapi-template-architect/
in Agent Skills format (portable — not
Claude-specific). To pull it into an unrelated project for Claude Code, Codex CLI,
GitHub Copilot, Cursor, Windsurf, or any other agent supported by
skills (vercel-labs/skills), run this from
that project:
npx skills add eslam5464/Fastapi-Template --skill fastapi-template-architect
Add -g to install it once to your personal/global skills folder instead of just this
project, or -a claude-code / -a codex to target one agent specifically. This is a
real, general-purpose skill installer, not something built for this repo — it works
the same way for anyone else’s skills too.
GitHub Copilot support in that CLI is unverified as of this writing — Copilot’s own docs don’t describe a native skills-folder mechanism yet. If
-a github-copilotdoesn’t do anything for you, use the Copilot-specific files below instead.
Working in this repo, or in a project generated from it? Nothing to do
Each of these is auto-discovered with zero install step, for the same reason: every project generated from this template inherits them automatically, just like the rest of the architecture.
- Claude Code scans
.claude/skills/. - Codex CLI scans
.agents/skills/— a mirror of the Claude Code skill (sameSKILL.mdformat), regenerated from it byscripts/sync_skill_mirrors.pyand kept in sync by a pre-commit hook. - GitHub Copilot reads
.github/copilot-instructions.mdautomatically, plus two reusable Copilot Chat prompts oncechat.promptFiles: trueis set in VS Code:/fastapi-scaffoldand/fastapi-review. Reusing these in another repo today means copying those files there — Copilot has no cross-project installer of its own yet.
Fallback: manual copy/symlink (if you’d rather not run npx)
# macOS/Linux
cp -r .claude/skills/fastapi-template-architect ~/.claude/skills/
# Windows (PowerShell) - a junction instead of a copy keeps it in sync automatically
New-Item -ItemType Junction -Path "$env:USERPROFILE\.claude\skills\fastapi-template-architect" -Target "$PWD\.claude\skills\fastapi-template-architect"
See the skill’s own SKILL.md for the full detail on both modes.
📖 Documentation
Detailed documentation is available in the docs/ folder:
- LLM Index - Canonical documentation entrypoint for AI and quick doc navigation
- AI Coding Assistant Skill - Scaffold or extend/review projects with this architecture from Claude Code, Codex CLI, or GitHub Copilot
- 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
🏛️ Architecture
Screenshot of the interactive diagram — client → API Gateway → versioned API → Service Layer → Repository/ORM → PostgreSQL, with Redis-backed caching/rate-limiting/token-blacklisting and an optional Celery worker for background jobs, all inside the Docker Compose trusted network.
See Architecture Overview for the full write-up. The interactive version lives at docs/architecture/fastapi-template.architecture.html — download it and open it locally for guided views, theme toggling, and per-node source links (GitHub renders .html files as source, not a live page, so the link above won’t run it in-browser).
🏗️ Project Structure
├── 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)
🔐 Authentication
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
Example Usage
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}!"}
🛠️ Development
Code Quality
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
Testing
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 browser
Coverage Scope:
- ✅ Unit, service, and integration tests
- 📊 Terminal and HTML coverage reports
- 🎯 Tests cover API endpoints, authentication, database operations, services, middleware, and utilities
Security Analysis
Run security analysis using Bandit:
uv run bandit -r app -f json -o bandit_results.json
Running Tests
uv run pytest -v
Background Jobs & Task Queue
The project uses Celery for background job processing with Redis as the message broker.
Start Celery Worker
# Linux/macOS
./scripts/celery_worker.sh
# Windows
.\scripts\celery_worker.bat
# Or directly
celery -A app.services.task_queue worker --loglevel=info --pool=solo
Start Celery Beat (Scheduler)
# Linux/macOS
./scripts/celery_beat.sh
# Windows
.\scripts\celery_beat.bat
# Or directly
celery -A app.services.task_queue beat --loglevel=info
Available Tasks:
seed_fake_users- Generates fake users for testing (runs every 10 seconds whenENABLE_DATA_SEEDING=true)
Database Migrations
Use the scripts provided (Recommended):
# Run database migrations for linux/macOS
./scripts/alembic.sh
# Run database migrations for windows
.\scripts\alembic.bat
Or use Alembic commands directly:
# Create a new migration
alembic revision --autogenerate -m "Description"
# Apply migrations
alembic upgrade head
# Rollback migrations
alembic downgrade -1
🌍 Environment Configuration
The 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_here
📦 Dependencies
Core 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-services
See docs/features.md for what each extra provides and how to configure it.
🤝 Contributing
- 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
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- 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
推奨ツール
別のキーワードを試すか、フィルタを外してください。
インストール
npx skillfish add eslam5464/fastapi-template