A modern, modular FastAPI backend template for building secure and scalable Python APIs.
Includes JWT authentication, PostgreSQL, Redis, WebSockets, Docker, and full test coverage β perfect for learning, refactoring, or production use.
- 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
- License
- β RESTful API Design - Complete CRUD operations with proper HTTP methods
- β
 Automatic OpenAPI Documentation - Interactive docs at /docsand/redoc
- β Request/Response Validation - Pydantic models with automatic validation
- β Dependency Injection - Clean, testable code with FastAPI's DI system
- β Authentication & Authorization - JWT-based auth with OAuth2 flow
- β
 API Versioning - Support for multiple API versions (/api/v1/,/api/v2/)
- π Real-time Communication - WebSockets and Server-Sent Events
- π File Upload/Download - Streaming file operations with validation
- β‘ Background Tasks - Asynchronous task processing
- ποΈ Caching - Redis-based caching for performance
- ποΈ Database Integration - SQLAlchemy ORM with async support
- π§ Middleware - Custom middleware for CORS, rate limiting, and monitoring
- π§ͺ Comprehensive Testing - Unit, integration, and performance tests
- π³ Docker Support - Multi-service container setup
- π Database Migrations - Alembic for schema management
- π Monitoring & Logging - Structured logging and health checks
- π Performance Benchmarking - Built-in API performance testing
| Category | Technology | Version | Purpose | 
|---|---|---|---|
| Framework | FastAPI | 0.104+ | Web framework | 
| Language | Python | 3.11+ | Programming language | 
| Database | PostgreSQL | 15+ | Primary database | 
| ORM | SQLAlchemy | 2.0+ | Database ORM | 
| Cache | Redis | 7+ | Caching layer | 
| Authentication | python-jose | 3.3+ | JWT handling | 
| Testing | pytest | 7.4+ | Testing framework | 
| Documentation | OpenAPI/Swagger | 3.0+ | API documentation | 
| Containerization | Docker | 20+ | Container platform | 
| Web Server | Uvicorn | 0.24+ | ASGI server | 
FastAPIVerseHub/                    # π  Project root
βββ app/                            # π¦ Main application package
β   βββ __init__.py                 # π Package initializer
β   βββ main.py                     # π Application entry point
β   βββ core/                       # βοΈ Core configurations
β   β   βββ __init__.py
β   β   βββ config.py               # π§ Settings & environment config
β   β   βββ dependencies.py         # π Dependency injection
β   β   βββ logging.py              # π Logging configuration
β   β   βββ security.py             # π Security utilities (JWT, hashing)
β   βββ api/                        # π API route definitions
β   β   βββ __init__.py
β   β   βββ v1/                     # π API version 1
β   β   β   βββ __init__.py
β   β   β   βββ auth.py             # π Authentication endpoints
β   β   β   βββ users.py            # π₯ User management
β   β   β   βββ courses.py          # π Course CRUD operations
β   β   β   βββ uploads.py          # π File upload/download
β   β   β   βββ websocket.py        # π WebSocket connections
β   β   β   βββ sse.py              # π‘ Server-Sent Events
β   β   β   βββ forms.py            # π Form data handling
β   β   βββ v2/                     # π API version 2 (Enhanced)
β   β       βββ __init__.py
β   β       βββ advanced_auth.py    # π Enhanced authentication
β   β       βββ advanced_courses.py # π Advanced course features
β   βββ models/                     # ποΈ Database models
β   β   βββ __init__.py
β   β   βββ user.py                 # π€ User database model
β   β   βββ course.py               # π Course database model
β   β   βββ token.py                # π« Token/session models
β   βββ schemas/                    # π Pydantic request/response models
β   β   βββ __init__.py
β   β   βββ user.py                 # π€ User validation schemas
β   β   βββ course.py               # π Course validation schemas
β   β   βββ auth.py                 # π Authentication schemas
β   β   βββ common.py               # π§ Shared schemas
β   βββ services/                   # π’ Business logic layer
β   β   βββ __init__.py
β   β   βββ auth_service.py         # π Authentication logic
β   β   βββ user_service.py         # π₯ User management logic
β   β   βββ course_service.py       # π Course business logic
β   β   βββ notification_service.py # π’ Real-time notifications
β   βββ common/                     # π οΈ Shared utilities
β   β   βββ __init__.py
β   β   βββ cache_utils.py          # πΎ Caching helpers
β   β   βββ file_utils.py           # π File handling utilities
β   β   βββ email_utils.py          # π§ Email utilities
β   β   βββ validators.py           # β
 Custom validators
β   βββ exceptions/                 # β Custom exception classes
β   β   βββ __init__.py
β   β   βββ base_exceptions.py      # ποΈ Base exception classes
β   β   βββ auth_exceptions.py      # π Auth-related errors
β   β   βββ validation_exceptions.py # β Validation errors
β   βββ middleware/                 # π§ Custom middleware
β   β   βββ __init__.py
β   β   βββ cors_middleware.py      # π CORS configuration
β   β   βββ rate_limiter.py         # π¦ API rate limiting
β   β   βββ request_timer.py        # β±οΈ Request timing
β   βββ tests/                      # π§ͺ Test suite
β   β   βββ __init__.py
β   β   βββ conftest.py             # βοΈ Pytest configuration
β   β   βββ test_auth.py            # π Authentication tests
β   β   βββ test_courses.py         # π Course tests
β   β   βββ test_uploads.py         # π File upload tests
β   β   βββ test_websockets.py      # π WebSocket tests
β   β   βββ test_sse.py             # π‘ SSE tests
β   β   βββ test_middleware.py      # π§ Middleware tests
β   βββ templates/                  # π Jinja2 templates
β       βββ welcome_email.html      # π§ Welcome email template
β       βββ reset_password.html     # π Password reset template
β       βββ api_docs.html           # π Custom API docs
βββ docs/                           # π Documentation
β   βββ concepts_map.md             # πΊοΈ FastAPI concepts mapping
β   βββ quick_reference.md          # β‘ Quick reference guide
β   βββ architecture_decisions.md   # ποΈ Architecture decisions (ADRs)
β   βββ learning_path.md            # π Structured learning guide
β   βββ api_usage_guide.md          # π API usage examples
β   βββ async_best_practices.md     # β‘ Async/await best practices
β   βββ testing_guide.md            # π§ͺ Testing strategies
β   βββ deployment_guide.md         # π Deployment instructions
βββ scripts/                        # π οΈ Development scripts
β   βββ generate_fake_data.py       # π Sample data generation
β   βββ benchmark_apis.py           # π Performance benchmarking
β   βββ run_tests.sh               # π§ͺ Test execution script
β   βββ generate_openapi_spec.py    # π OpenAPI spec generation
βββ .env.example                    # π§ Environment variables template
βββ .gitignore                      # π« Git ignore rules
βββ Dockerfile                      # π³ Container configuration
βββ docker-compose.yml              # π³ Multi-service orchestration
βββ pyproject.toml                  # π¦ Project configuration
βββ README.md                       # π This file
- π Python 3.11+ - Download Python
- π³ Docker & Docker Compose - Install Docker
- π¦ Git - Install Git
# 1οΈβ£ Clone the repository
git clone https://github.com/mhhoss/fastapi-.git
cd fastapi-stack
# 2οΈβ£ Copy environment configuration
cp .env.example .env
# 3οΈβ£ Create required __init__.py files
touch app/__init__.py app/core/__init__.py app/api/__init__.py \
      app/api/v1/__init__.py app/api/v2/__init__.py app/models/__init__.py \
      app/schemas/__init__.py app/services/__init__.py app/common/__init__.py \
      app/exceptions/__init__.py app/middleware/__init__.py app/tests/__init__.py
# 4οΈβ£ Start all services
docker-compose up -d
# 5οΈβ£ Check service status
docker-compose ps
# 6οΈβ£ View logs (optional)
docker-compose logs -f app
# π Access the application
# API: http://localhost:8000
# Docs: http://localhost:8000/docs
# Admin Panel: http://localhost:5050 (pgAdmin)# 1οΈβ£ Clone and setup
git clone https://github.com/mhhoss/fastapi-stack.git
cd fastapi-stack
# 2οΈβ£ Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
# 3οΈβ£ Install dependencies
pip install -e ".[dev]"
# 4οΈβ£ Setup environment
cp .env.example .env
# Edit .env with your database and Redis URLs
# 5οΈβ£ Create __init__.py files (same as Docker option step 3)
# 6οΈβ£ Setup database (if using local PostgreSQL)
createdb fastapi_verse_hub  # or use your preferred method
# 7οΈβ£ Run database migrations
alembic upgrade head
# 8οΈβ£ Start the application
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
# π Open http://localhost:8000 in your browser# Test if everything is working
curl http://localhost:8000/health
# Expected response:
# {"status":"healthy","timestamp":"...","version":"1.0.0"}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 | 
For testing purposes, use these credentials:
- π§ Email: admin@example.com
- π Password: admin123
- π Role: Administrator
| Method | Endpoint | Description | Auth Required | 
|---|---|---|---|
| POST | /api/v1/auth/register | User registration | β | 
| POST | /api/v1/auth/token | User login | β | 
| POST | /api/v1/auth/refresh | Token refresh | β | 
| Method | Endpoint | Description | Auth Required | 
|---|---|---|---|
| GET | /api/v1/users/me | Get current user | β | 
| PUT | /api/v1/users/me | Update current user | β | 
| GET | /api/v1/users/ | List users (paginated) | β | 
| Method | Endpoint | Description | Auth Required | 
|---|---|---|---|
| GET | /api/v1/courses/ | List courses | β | 
| POST | /api/v1/courses/ | Create course | β | 
| GET | /api/v1/courses/{id} | Get course details | β | 
| PUT | /api/v1/courses/{id} | Update course | β | 
| DELETE | /api/v1/courses/{id} | Delete course | β | 
| Method | Endpoint | Description | Auth Required | 
|---|---|---|---|
| POST | /api/v1/uploads/ | Upload file | β | 
| GET | /api/v1/uploads/{id}/download | Download file | β | 
| GET | /api/v1/uploads/my-files | List user files | β | 
| Method | Endpoint | Description | Auth Required | 
|---|---|---|---|
| GET | /health | Basic health status | β | 
| GET | /ready | Readiness probe | β | 
// Connect to WebSocket
const ws = new WebSocket("ws://localhost:8000/api/v1/ws");
// Authenticate
ws.onopen = () => {
  ws.send(
    JSON.stringify({
      type: "authenticate",
      token: "your-jwt-token",
    })
  );
};
// Send message
ws.send(
  JSON.stringify({
    type: "message",
    content: "Hello, World!",
    room: "general",
  })
); // Subscribe to notifications
const eventSource = new EventSource(
  "http://localhost:8000/api/v1/sse/notifications?token=your-jwt-token"
);
eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log("Notification:", data);
};# Run all tests
./scripts/run_tests.sh
# Run with coverage report
./scripts/run_tests.sh --coverage
# Run specific test types
./scripts/run_tests.sh --type unit --verbose
./scripts/run_tests.sh --type integration
./scripts/run_tests.sh --type performance# Generate sample users and courses
python scripts/generate_fake_data.py
# Options:
# - 50 users (including 1 admin)
# - 30 courses with realistic data
# - Course enrollments
# - Sample file records# Run API performance tests
python scripts/benchmark_apis.py --total 100 --concurrent 10
# Export results to JSON
python scripts/benchmark_apis.py --export results.json- Unit Tests: 90%+ coverage
- Integration Tests: All API endpoints
- Performance Tests: Sub-100ms response times
- E2E Tests: Critical user workflows
# π Generate fake data for testing
python scripts/generate_fake_data.py
# π Export OpenAPI specification
python scripts/generate_openapi_spec.py
# π Run performance benchmarks
python scripts/benchmark_apis.py
# ποΈ Database migrations
alembic revision --autogenerate -m "Add new feature"
alembic upgrade head
alembic downgrade -1
# π¨ Code formatting and linting
black app/          # Format code
isort app/          # Sort imports
flake8 app/         # Lint code
mypy app/           # Type checking- πΏ Branch: Create feature branch from main
- π» Code: Implement feature with tests
- π§ͺ Test: Run full test suite
- π¨ Format: Apply code formatting
- π Document: Update documentation
- π Review: Create pull request
- π Deploy: Merge and deploy
# ποΈ Build and start development environment
docker-compose up -d --build
# π View service logs
docker-compose logs -f app
# ποΈ Access database directly
docker-compose exec db psql -U fastapi_user -d fastapi_verse_hub
# πΎ Access Redis CLI
docker-compose exec redis redis-cli
# π Monitor with management tools
# pgAdmin: http://localhost:5050 (admin@example.com / admin)
# Redis Commander: http://localhost:8081 (admin / admin)- ποΈ 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
# π Production deployment
docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d
# π With SSL (requires nginx configuration)
docker-compose --profile production up -d
# π Monitor deployment
docker-compose ps
docker-compose logs -f# π¦ 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 | Custom middleware | Cross-origin request control | 
| π¦ Rate Limiting | Token bucket | API abuse prevention | 
| β Input Validation | Pydantic models | Data sanitization | 
| π‘οΈ SQL Injection | SQLAlchemy ORM | Parameterized queries | 
| π File Security | Type validation | Safe file uploads | 
| π Security Headers | Custom middleware | OWASP recommendations | 
# π Generate secure keys for production
python -c "import secrets; print(secrets.token_urlsafe(32))"
# π Security audit
pip install safety bandit
safety check
bandit -r app/
# π‘οΈ Update dependencies regularly
pip-audit| Endpoint | Purpose | Response | 
|---|---|---|
| GET /health | Basic health | Service status | 
| GET /ready | Readiness probe | Dependencies status | 
- π Structured Logging - JSON format with correlation IDs
- β±οΈ Request Timing - Response time tracking
- β Error Tracking - Comprehensive error logging
- π Custom Metrics - Business metrics collection
- π Prometheus - Metrics endpoint for monitoring
# π View application logs
docker-compose logs -f app
# π Access metrics endpoint
curl http://localhost:8000/metrics
# π₯ Check health status
curl http://localhost:8000/health
curl http://localhost:8000/ready| 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 all tests pass (./scripts/run_tests.sh)
- π Commit your changes (git commit -m 'Add amazing feature')
- β¬οΈ Push to branch (git push origin feature/amazing-feature)
- π Open a Pull Request
- π¨ Code Style - Follow PEP 8 and use blackformatter
- π€ 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 beginners
- documentation- Documentation improvements
- tests- Adding or improving tests
- enhancement- 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
- π Total Files: 77
- π¦ Directories: 17
- π§ͺ Test Coverage: 80%+ (target: 90%+)
- π API Endpoints: 15+ (across v1 and v2)
- π Documentation Pages: 8
- π οΈ Utility Scripts: 4
- π OAuth2 Social Login - Google, GitHub, Facebook integration
- π Admin Dashboard - Web-based administration interface
- π Analytics & Metrics - Detailed usage analytics
- π Full-text Search - Elasticsearch integration
- π± Mobile API - Mobile-optimized endpoints
- π Internationalization - Multi-language support
- π¦ Microservices - Service decomposition guide
- π Event Sourcing - Event-driven architecture patterns
- πΊοΈ GraphQL - GraphQL endpoints alongside REST
- π€ ML Integration - Machine learning model serving
- βοΈ Cloud Native - Kubernetes-native deployment
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
- Mahdi Hosseini β Maintainer of Fastapi-stack with personal improvements and modular enhancements
- 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 | 
| π€ Owner | @mhhoss | Project maintainer | 
Based on FastAPIVerseHub
π Happy coding! π
FastAPI Stack - Where FastAPI learning meets real-world application.
β If you find this project helpful, please give it a star! β