A production-grade FastAPI code base that doubles as a learning resource: typed SQLAlchemy 2.0 models, tested migrations, structured logging with request correlation, Prometheus metrics, atomic Redis rate limiting, real-time WebSockets/SSE, and a CI pipeline that keeps lint, types and tests green.
- Features
- Tech Stack
- Project Structure
- Quick Start
- API Documentation
- API Endpoints
- Real-time Features
- Testing
- Development
- Architecture
- Deployment
- Performance
- Security
- Monitoring
- Learning Resources
- Contributing
- Troubleshooting
- Changelog
- License
- β
REST API, versioned -
/api/v1core,/api/v2advanced auth (MFA, magic links, sessions) and analytics - β
Typed models - SQLAlchemy 2.0
Mapped[]declarations, shared mixins, named constraints - β Tested migrations - Alembic chain is applied and diffed against the models in CI
- β
One error envelope -
{"error", "message", "details", "request_id"}for every failure - β UTC everywhere - timezone-aware timestamps via a custom column type; no naive datetimes
- β Real-time - WebSocket rooms/channels and Server-Sent Events (unbuffered, pure-ASGI stack)
- β Files & forms - streaming uploads with validation, multipart forms, surveys
- β Analytics - enrollment cohorts, market trends, instructor dashboard, A/B experiments with a z-test
- π©Ί Probes -
/health/liveand/health/ready(DB + Redis with timeouts, 503 when degraded) - π Metrics - Prometheus
/metricslabelled by route template; compose profile with Grafana - π§Ύ Structured logs - structlog, JSON in production,
X-Request-IDpropagated end to end - π¦ Rate limiting - sliding windows on Redis sorted sets, atomic, fails open on outage
- π Hardened defaults - secrets as
SecretStr, production refuses placeholder config, security headers, bcrypt - π³ Docker - multi-stage image (uv), non-root, tini, migrations on start, health-gated compose
- π§ͺ 300+ tests (82% coverage) on in-memory SQLite + fakeredis; no external services needed
- π§Ή ruff + mypy - zero lint findings, zero type errors, both blocking in CI
- βοΈ GitHub Actions - lint, typecheck, test matrix (3.11/3.12), Docker build, OpenAPI artefact
- π€ Dependabot, pre-commit hooks, Makefile
| Category | Technology | Purpose |
|---|---|---|
| Framework | FastAPI / Starlette | ASGI web framework |
| Language | Python 3.11+ | `X |
| Validation | Pydantic v2 | Schemas and settings |
| Database | PostgreSQL 16 | Primary store (SQLite for tests) |
| ORM / Migrations | SQLAlchemy 2.0 / Alembic | Typed async ORM, versioned schema |
| Cache & limits | Redis 7 | Caching, rate limiting, token blacklist |
| Auth | python-jose, bcrypt, pyotp | JWT, password hashing, TOTP MFA |
| Observability | structlog, prometheus-client | Logs and metrics |
| Testing | pytest, httpx, fakeredis | Async tests without external services |
| Quality | ruff, mypy, pre-commit | Lint, format, types |
| Packaging | uv | Fast, reproducible installs |
| Runtime | Uvicorn, Docker, nginx | Serving and deployment |
FastAPIVerseHub/
βββ app/
β βββ main.py # app factory, lifespan, middleware stack, error envelope
β βββ api/
β β βββ health.py # /health, /health/live, /health/ready
β β βββ v1/ # auth, users, courses, uploads, forms, websocket, sse
β β βββ v2/ # advanced auth (MFA, magic link, sessions), advanced courses
β βββ core/
β β βββ config.py # validated Settings (SecretStr, production guards)
β β βββ dependencies.py # DB session, Redis, current-user dependencies
β β βββ logging.py # structlog + request correlation
β β βββ metrics.py # Prometheus middleware + /metrics
β β βββ security.py # bcrypt hasher, JWT manager
β β βββ time.py # utcnow(), aware-datetime helpers
β βββ middleware/ # pure-ASGI: request context, rate limit, security headers, CORS
β βββ models/ # SQLAlchemy 2.0 typed models, mixins, UTCDateTime
β βββ schemas/ # Pydantic request/response models
β βββ services/ # business logic (auth, users, courses, files, forms, analyticsβ¦)
β βββ common/ # cache manager, sliding-window limiter, file/email utils
β βββ exceptions/ # application exception hierarchy
β βββ templates/ # Jinja2 email templates
β βββ tests/ # pytest suite (SQLite + fakeredis, migration drift tests)
βββ alembic/ # migration environment and versions/
βββ docker/ # entrypoint, Prometheus + Grafana provisioning
βββ docs/ # guides and ADRs
βββ nginx/ # reverse proxy config (TLS, WS, SSE, /metrics allow-list)
βββ scripts/ # fake data, benchmarks, OpenAPI export, test runner
βββ .github/workflows/ci.yml # lint Β· typecheck Β· tests Β· docker Β· openapi
βββ docker-compose.yml # app + postgres + redis (+ monitoring / admin / nginx profiles)
βββ Dockerfile # multi-stage, uv, non-root, tini
βββ Makefile # make install | lint | typecheck | test | run | migrate
βββ pyproject.toml # deps, ruff, mypy, pytest, coverage config
- π Python 3.11+ and uv (
pip install uvworks too) - π³ Docker (optional, for the full stack)
git clone https://github.com/SatvikPraveen/FastAPIVerseHub.git
cd FastAPIVerseHub
docker compose up -d --build # api + postgres + redis; migrations run on start
curl -s localhost:8000/health/ready | jq # {"status": "ready", ...}
open http://localhost:8000/docs
# optional profiles
docker compose --profile monitoring up -d # Prometheus :9090, Grafana :3001
docker compose --profile admin up -d # pgAdmin :5050, Redis Commander :8081git clone https://github.com/SatvikPraveen/FastAPIVerseHub.git
cd FastAPIVerseHub
make install # uv venv + deps + pre-commit hooks
cp .env.example .env # point DATABASE_* / REDIS_* at your services
make migrate # alembic upgrade head
make run # uvicorn with reload on :8000make lint typecheck test # ruff Β· mypy Β· pytest (no services required)Once running, access the comprehensive API documentation:
| Documentation Type | URL | Description |
|---|---|---|
| π¨ Swagger UI | http://localhost:8000/docs | Interactive API documentation |
| π ReDoc | http://localhost:8000/redoc | Alternative documentation view |
| π OpenAPI Spec | http://localhost:8000/openapi.json | Raw OpenAPI specification |
Docs are served in every environment except production. Export the spec with
python scripts/generate_openapi_spec.py (JSON, YAML, Markdown and a Postman
collection under docs/openapi/; CI publishes the same as an artefact).
python scripts/generate_fake_data.py # users (password: password123), courses, enrollmentsEvery error response has the same shape, so clients can switch on error:
{"error": "VALIDATION_ERROR", "message": "Request validation failed",
"details": {"errors": [{"field": "email", "message": "value is not a valid email address"}]},
"request_id": "3f1c9b2e0d0d4b6f9a1c2d3e4f5a6b7c"}| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST |
/api/v1/auth/register |
Register, returns token pair | β |
POST |
/api/v1/auth/login |
Login | β |
POST |
/api/v1/auth/refresh |
Rotate access token | β |
POST |
/api/v1/auth/logout |
Revoke token (jti blacklist) | β |
POST |
/api/v1/auth/forgot-password |
Request reset token | β |
POST |
/api/v1/auth/reset-password |
Reset with token | β |
POST |
/api/v2/auth/mfa/setup /verify /disable |
TOTP MFA lifecycle | β |
POST |
/api/v2/auth/passwordless/request /verify |
Magic-link login | β |
GET |
/api/v2/auth/sessions |
List / revoke sessions | β |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
GET/PUT/DELETE |
/api/v1/users/me |
Own profile | β |
GET |
/api/v1/users/ |
List users (admin) | π |
GET |
/api/v1/courses/ |
List/search courses | β |
POST |
/api/v1/courses/ |
Create course | β |
GET/PUT/DELETE |
/api/v1/courses/{course_id} |
Course detail / update / delete | β/β |
POST/DELETE |
/api/v1/courses/{course_id}/enroll |
Enroll / unenroll | β |
GET |
/api/v2/courses/recommendations |
Recommendations | β |
GET |
/api/v2/courses/analytics/{id} |
Course analytics (owner) | β |
GET |
/api/v2/courses/cohorts/{id} |
Monthly enrollment cohorts | β |
POST |
/api/v2/courses/experiments/ab-test |
Create A/B experiment | β |
GET |
/api/v2/courses/trends/market |
Demand / pricing signals | β |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST |
/api/v1/uploads/file /multiple |
Upload (streamed, hashed) | β |
GET |
/api/v1/uploads/download/{file_id} |
Download (public files: no auth) | β/β |
GET |
/api/v1/uploads/stream/{file_id} |
Chunked stream | β |
GET |
/api/v1/uploads/categories /stats |
Per-user aggregates | β |
POST |
/api/v1/forms/contact /feedback /survey /multipart /dynamic |
Submissions | varies |
POST |
/api/v1/forms/validate |
Dry-run validation | β |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
GET |
/health/live |
Liveness | β |
GET |
/health/ready |
Readiness (DB + Redis), 503 when degraded | β |
GET |
/metrics |
Prometheus exposition | β (restrict at the proxy) |
Rate-limited responses carry X-RateLimit-Limit, X-RateLimit-Remaining,
X-RateLimit-Reset and, on 429, Retry-After. Every response carries
X-Request-ID and X-Process-Time.
const ws = new WebSocket("ws://localhost:8000/api/v1/ws/connect/my-client?token=" + jwt);
ws.onmessage = (e) => console.log(JSON.parse(e.data));
ws.onopen = () => {
ws.send(JSON.stringify({ type: "subscribe", channel: "general" }));
ws.send(JSON.stringify({ type: "broadcast", channel: "general", content: "Hello!" }));
};Message types: ping, subscribe, unsubscribe, broadcast, private_message,
join_room, leave_room, room_message. Stats at GET /api/v1/ws/stats.
const es = new EventSource("http://localhost:8000/api/v1/sse/events?channels=general,updates");
es.addEventListener("connected", (e) => console.log("connected", JSON.parse(e.data)));
es.addEventListener("message", (e) => console.log(JSON.parse(e.data)));Publish with POST /api/v1/sse/publish/{channel} or POST /api/v1/sse/broadcast.
The stream ends as soon as the client disconnects; the middleware stack is pure
ASGI so events are not buffered.
make test # full suite with coverage (fails under 80%)
make test-fast # parallel, no coverage
pytest app/tests/test_rate_limit.py -k concurrent -v- Runs entirely in-process: async SQLite in memory and fakeredis with real Redis command semantics. No Docker, no services.
test_migrations.pyapplies the Alembic chain to a scratch database and asserts zero drift against the models, then downgrades to empty.- Every test has a 60 s timeout, so a stalled stream fails fast.
- Load test a running instance:
python scripts/benchmark_apis.py --total 200 --concurrent 20.
make help # list targets
make lint # ruff check
make format # ruff --fix + ruff format
make typecheck # mypy app (zero errors is the bar)
make migrate # alembic upgrade head
alembic revision --autogenerate -m "add thing" # then run make test: drift is assertedpre-commit install (done by make install) runs ruff, ruff-format and mypy
on every commit. CI runs the same checks plus the test matrix and a Docker build.
docker compose up -d --build
docker compose logs -f app
docker compose exec app alembic history
docker compose exec db psql -U fastapi_user -d fastapi_verse_hub
docker compose --profile monitoring up -d # Prometheus + GrafanaThe image runs migrations on start (SKIP_MIGRATIONS=1 to disable), serves with
WEB_CONCURRENCY uvicorn workers behind tini, and reports readiness via the
container healthcheck.
- ποΈ Clean Architecture - Clear separation of concerns
- π― Domain-Driven Design - Business logic in services layer
- β‘ SOLID Principles - Maintainable and extensible code
- π§ͺ Test-Driven Development - Comprehensive test coverage
- π API-First Design - OpenAPI specification driven
- π§ Configuration Management - Pydantic Settings with environment variables
- π Security Utilities - JWT handling and password hashing
- ποΈ Database Connection - Async SQLAlchemy setup
- π Dependency Injection - FastAPI dependencies
- π Structured Logging - JSON logging with correlation IDs
- π£οΈ RESTful Endpoints - Standard HTTP methods and status codes
- β Request/Response Validation - Automatic Pydantic validation
- β Error Handling - Consistent error responses
- π API Versioning - Support for multiple API versions
- π Domain Rules - Business logic implementation
- ποΈ Database Operations - Data access patterns
- π External Integrations - Third-party service calls
- β‘ Background Tasks - Async task management
- π ORM Models - SQLAlchemy database models
- π Relationships - Database table relationships
- β Constraints - Data integrity rules
- π₯ Request Models - Input validation schemas
- π€ Response Models - Output serialization schemas
- π Documentation - Automatic API docs generation
# Build the runtime image (multi-stage, non-root, tini, migrations on start)
docker build -t fastapiversehub:latest .
# Run behind the bundled nginx (TLS, WebSocket/SSE proxying, /metrics allow-list)
docker compose --profile production up -d
# Required production environment (startup refuses unsafe values):
# ENVIRONMENT=production JWT_SECRET_KEY=<openssl rand -hex 32>
# DATABASE_URL=postgresql://... REDIS_URL=redis://... CORS_ORIGINS=https://app.example.com
docker compose ps && docker compose logs -f app# π¦ Install production dependencies
pip install -e ".[production]"
# π Run with Gunicorn
gunicorn app.main:app \
--workers 4 \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:8000 \
--access-logfile - \
--error-logfile -The project includes deployment configurations for:
| Platform | Service | Configuration |
|---|---|---|
| π AWS | ECS/Fargate | Container-based deployment |
| π΅ Google Cloud | Cloud Run | Serverless container platform |
| π¦ Azure | Container Instances | Simple container deployment |
| βΈοΈ Kubernetes | Any cluster | Full orchestration setup |
π Detailed Instructions: See docs/deployment_guide.md
| Metric | Target | Description |
|---|---|---|
| β‘ Response Time | < 50ms | Average for simple endpoints |
| π Throughput | 1000+ RPS | Requests per second with caching |
| π₯ Concurrent Users | 500+ | WebSocket connections |
| π File Upload | 100MB+ | Streaming support |
- πΎ Redis Caching - Database query caching
- π Connection Pooling - Efficient database connections
- β‘ Async/Await - Non-blocking operations throughout
- βοΈ Background Tasks - Offloaded processing
- ποΈ Response Compression - Reduced payload sizes
# π Run performance benchmarks
python scripts/benchmark_apis.py \
--concurrent 10 \
--total 1000 \
--export performance_report.json
# π Analyze results
# Check average response times, error rates, and throughput| Feature | Implementation | Description |
|---|---|---|
| π Authentication | JWT tokens | Stateless authentication |
| π Password Security | bcrypt hashing | Secure password storage |
| π CORS Protection | Starlette CORS | Explicit origins; wildcard refused in production |
| π¦ Rate Limiting | Sliding window (Redis ZSET) | Atomic, burst/minute/hour, fails open |
| β Input Validation | Pydantic models | Data sanitization |
| π‘οΈ SQL Injection | SQLAlchemy ORM | Parameterized queries |
| π File Security | Type validation | Safe file uploads |
| π Security Headers | Pure-ASGI middleware | nosniff, DENY framing, CSP, HSTS in prod |
| βοΈ Config guards | Settings validator | Placeholder secrets / DEBUG rejected in production |
# π Generate secure keys for production
python -c "import secrets; print(secrets.token_urlsafe(32))"
# π Security audit
uv pip install pip-audit bandit
pip-audit
bandit -r app/ -c pyproject.toml| Endpoint | Purpose |
|---|---|
/health/live |
Process up; never touches dependencies |
/health/ready |
DB + Redis checked with timeouts; 503 if not |
/metrics |
Prometheus: requests, latency histogram, in-flight, exceptions (by route template) |
Logs are structured (structlog); LOG_FORMAT=json in production. Every line and
every error body carries the request_id, which is also returned as
X-Request-ID and accepted from upstream proxies.
curl -s localhost:8000/metrics | grep http_request_duration_seconds_bucket | head
docker compose --profile monitoring up -d && open http://localhost:3001| Step | Resource | Duration | Focus |
|---|---|---|---|
| 1οΈβ£ | docs/learning_path.md |
2-3 weeks | Complete FastAPI journey |
| 2οΈβ£ | docs/quick_reference.md |
1 day | FastAPI patterns |
| 3οΈβ£ | docs/api_usage_guide.md |
2 days | API usage examples |
| 4οΈβ£ | docs/architecture_decisions.md |
1 day | Design decisions |
| 5οΈβ£ | docs/testing_guide.md |
3 days | Testing strategies |
| 6οΈβ£ | docs/deployment_guide.md |
2 days | Production deployment |
- β‘ Async Programming - Proper async/await usage patterns
- π Dependency Injection - FastAPI's powerful DI system
- β Data Validation - Pydantic models and custom validators
- π Authentication - JWT and OAuth2 implementation
- π Real-time Communication - WebSockets and Server-Sent Events
- π§ͺ Testing - Comprehensive testing strategies
- π API Design - RESTful best practices and standards
- π FastAPI Official Documentation
- π Pydantic Documentation
- π SQLAlchemy Documentation
- π pytest Documentation
- π Docker Documentation
We welcome contributions! Here's how to get started:
- π΄ Fork the repository
- πΏ Create a feature branch (
git checkout -b feature/amazing-feature) - π» Make your changes with tests
- π§ͺ Ensure
make lint typecheck testpasses - π Commit your changes (
git commit -m 'Add amazing feature') - β¬οΈ Push to branch (
git push origin feature/amazing-feature) - π Open a Pull Request
- π¨ Code Style -
ruff format+ruff check(configured inpyproject.toml) - π€ Type Hints - Add type hints to all functions
- π§ͺ Testing - Write tests for new functionality (aim for 90%+ coverage)
- π Documentation - Update relevant documentation
- β‘ Commits - Keep commits atomic and well-described
- π Bug Fixes - Fix issues and improve stability
- β¨ New Features - Add new functionality
- π Documentation - Improve docs and examples
- π¨ Code Quality - Refactoring and optimization
- π§ͺ Testing - Add or improve tests
- π Security - Security improvements
Look for issues labeled with:
good-first-issue- Perfect for beginnersdocumentation- Documentation improvementstests- Adding or improving testsenhancement- Small feature additions
ποΈ Database Connection Errors
# Check if database is running
docker compose ps db
# Check connection string
echo $DATABASE_URL
# Reset database
docker compose down -v
docker compose up -d db
# Check logs
docker compose logs dbπΎ Redis Connection Issues
# Test Redis connectivity
redis-cli ping # Should return PONG
# Check Redis URL
echo $REDIS_URL
# Restart Redis
docker compose restart redis
# Check Redis logs
docker compose logs redisπ¦ Import Errors
# Ensure virtual environment is activated
source venv/bin/activate
# Reinstall dependencies
pip install -e ".[dev]"
# Check Python path
python -c "import sys; print(sys.path)"
# Ensure __init__.py files exist
find app -name "__init__.py" | head -10π Permission Errors
# Fix upload directory permissions
chmod -R 755 uploads/
# Fix Docker volume permissions
sudo chown -R $USER:$USER uploads/
# Check file ownership
ls -la uploads/π Application Won't Start
# Check if port is in use
lsof -i :8000
# Check environment variables
python -c "from app.core.config import settings; print(settings.DATABASE_URL)"
# Start with debug mode
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload --log-level debug
# Check application logs
docker compose logs -f app- π GitHub Issues - Report bugs or request features
- π¬ Discussions - Ask questions and share ideas
- π§ Email - Contact the maintainer for urgent issues
This project serves as a comprehensive learning resource and production-ready template for:
- π Learning FastAPI - From basic concepts to advanced patterns
- π Best Practices - Industry-standard development patterns
- π Real-world Usage - Production-ready features and deployment
- π Community Education - Open-source learning resource
- π Template for Projects - Starter template for new FastAPI projects
- π§ͺ Tests: 300+ at 82% coverage (unit, API, migration drift, concurrency, security flows)
- π§Ή Lint / types: ruff clean, mypy 0 errors
- π API Endpoints: 60+ across v1 and v2
- π Docs: 8 guides + 17 ADRs, plus a changelog
- π οΈ Utility Scripts: 4
- π OAuth2 Social Login - Google, GitHub, Facebook integration
- π Admin Dashboard - Web-based administration interface
- π Full-text Search - Elasticsearch integration
- π± Mobile API - Mobile-optimized endpoints
- π Internationalization - Multi-language support
- π Tracing - OpenTelemetry spans exported alongside the existing metrics/logs
- π¨ Task queue - Move email and report generation to a worker (arq/Celery)
- ποΈ Object storage - S3-compatible backend for uploads
- πΊοΈ GraphQL - GraphQL endpoints alongside REST
- βΈοΈ Helm chart - Kubernetes-native deployment with the probes already provided
This project is licensed under the MIT License - see the LICENSE file for details.
MIT License - Free for commercial and private use
β
Commercial use β
Modification β
Distribution β
Private use
β Liability β Warranty
- β‘ FastAPI - The amazing web framework by SebastiΓ‘n Ramirez
- π Pydantic - Data validation and settings management
- ποΈ SQLAlchemy - The Python SQL toolkit and ORM
- β Starlette - Lightweight ASGI framework
- π§ͺ pytest - Testing framework
- **π **Open Source Community** - For inspiration and contributions
- Satvik Praveen - Project creator and maintainer
- Community Contributors - Thank you to everyone who contributes!
| Resource | URL | Description |
|---|---|---|
| π Documentation | docs/ | Complete project documentation |
| π¨ API Reference | http://localhost:8000/docs | Interactive API documentation |
| π Issues | GitHub Issues | Bug reports and feature requests |
| π¬ Discussions | GitHub Discussions | Community discussions |
| β Repository | GitHub Repo | Source code repository |
| π€ Author | @SatvikPraveen | Project maintainer |
π Happy coding! π
FastAPIVerseHub - Where FastAPI learning meets real-world application.
β If you find this project helpful, please give it a star! β