Skip to content

Latest commit

Β 

History

History
1212 lines (988 loc) Β· 54.8 KB

File metadata and controls

1212 lines (988 loc) Β· 54.8 KB

πŸš€ FastAPI Backend API

FastAPI Python PostgreSQL SQLAlchemy License Status Docker

Enterprise-Grade FastAPI Backend API with Advanced Features

FastAPI Backend is a comprehensive, production-ready RESTful API built with FastAPI (Python), featuring JWT authentication with Instagram-style multi-token pattern, role-based access control, real-time activity logging, advanced security middleware, and comprehensive monitoring capabilities.

Repository: https://github.com/fullstack-open-source/fastapi-backend-with-sql

πŸ“‹ Table of Contents

πŸš€ Features

🎯 Core Capabilities

  • RESTful API: Comprehensive REST API with FastAPI framework
  • JWT Authentication: Instagram-style multi-token authentication system (Access, Session, Refresh tokens)
  • Role-Based Access Control: Flexible permission system with groups and permissions
  • Activity Logging: Comprehensive audit trail with detailed metadata
  • File Upload: Google Cloud Storage integration for media files
  • Email & SMS: Twilio integration for notifications and OTP
  • Error Tracking: Sentry integration for production monitoring and error tracking
  • API Documentation: Auto-generated Swagger/OpenAPI documentation
  • Rate Limiting: Request throttling and rate limiting for traffic management
  • Docker Ready: Production-ready containerization with multi-stage builds
  • Kubernetes Support: K8s deployment configurations included

πŸ”§ Technical Features

  • FastAPI 0.109+: Modern, fast web framework for building APIs with Python
  • Python 3.11+: Modern Python with type hints and async support (3.11+ recommended for Google Cloud libraries)
  • PostgreSQL 16+: Robust relational database with advanced features
  • SQLAlchemy 2.0+: Modern ORM with async support and type safety
  • Alembic: Database migration tool for schema versioning
  • Redis: Caching and session management for improved performance
  • JWT: Secure token-based authentication with multi-token pattern
  • Pydantic: Data validation using Python type annotations
  • Sentry: Error tracking and performance monitoring
  • Google Cloud Storage: Object storage for media files
  • Nginx Reverse Proxy: Production-ready reverse proxy configuration

πŸ” Authentication Features

  • Multi-Token System: Access token (1 hour), Session token (7 days), Refresh token (30 days)
  • Token Blacklisting: Redis-based token invalidation for secure logout
  • OTP Verification: Email, SMS, and WhatsApp OTP support
  • Password Management: Set, change, and reset password functionality
  • Email/Phone Verification: Two-step verification for contact changes
  • Session Management: Stateless session management with unique session IDs
  • Token Rotation: Automatic token rotation on refresh for enhanced security

πŸ—οΈ Architecture

System Architecture

The system follows a layered architecture with clear separation of concerns:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                        External Proxy                         β”‚
β”‚                    (api.example.com)                          β”‚
β”‚                    SSL/TLS Termination                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
                              β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Internal Nginx Proxy                        β”‚
β”‚                    (Port 9080:80)                              β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚  Security Layer:                                         β”‚  β”‚
β”‚  β”‚  - Rate Limiting (200 req/min per IP)                    β”‚  β”‚
β”‚  β”‚  - Request Size Validation (15MB max)                    β”‚  β”‚
β”‚  β”‚  - Attack Pattern Detection                              β”‚  β”‚
β”‚  β”‚  - Content Security Policy                               β”‚  β”‚
β”‚  β”‚  - DDoS Protection                                       β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                             β”‚
                             β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    FastAPI Application                         β”‚
β”‚                    (Port 8000)                                 β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚  Middleware Stack:                                       β”‚  β”‚
β”‚  β”‚  1. Sentry Request Handler                               β”‚  β”‚
β”‚  β”‚  2. CORS (Cross-Origin)                                  β”‚  β”‚
β”‚  β”‚  3. Advanced Security Middleware                         β”‚  β”‚
β”‚  β”‚  4. Input Sanitization                                   β”‚  β”‚
β”‚  β”‚  5. Permission Middleware                                β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚  Application Modules:                                    β”‚  β”‚
β”‚  β”‚  - Authentication (JWT, OTP, Login)                      β”‚  β”‚
β”‚  β”‚  - Profile Management                                    β”‚  β”‚
β”‚  β”‚  - Permissions (Groups, Permissions)                     β”‚  β”‚
β”‚  β”‚  - Dashboard (Analytics)                                 β”‚  β”‚
β”‚  β”‚  - Activity Logging                                      β”‚  β”‚
β”‚  β”‚  - File Upload (GCS)                                     β”‚  β”‚
β”‚  β”‚  - Health Monitoring                                     β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
└────────────────────────────┬──────────────────────────────-β”€β”€β”€β”€β”˜
                             β”‚
                β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                β–Ό                          β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   PostgreSQL Database    β”‚   β”‚   Redis Cache            β”‚
β”‚   (SQLAlchemy ORM)       β”‚   β”‚   (Sessions, Cache)      β”‚
β”‚   - User Data            β”‚   β”‚   - Session Storage      β”‚
β”‚   - Permissions          β”‚   β”‚   - OTP Cache            β”‚
β”‚   - Activity Logs        β”‚   β”‚   - Token Blacklist      β”‚
β”‚   - Groups               β”‚   β”‚   - Rate Limiting        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                β”‚
                β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Google Cloud Storage   β”‚
β”‚   (Media & Static Files) β”‚
β”‚   - User Uploads         β”‚
β”‚   - Generated Content    β”‚
β”‚   - Static Assets        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Authentication Architecture

The authentication system implements a stateless, multi-token architecture similar to Instagram:

Key Features:

  • Multi-Token System: Access token (1 hour), Session token (7 days), Refresh token (30 days)
  • Token Blacklisting: Redis-based cache for token invalidation
  • Session Management: Unique session_id links all tokens together
  • Token Rotation: Refresh tokens rotate on each refresh for security
  • Origin Validation: Domain-specific token validation

Complete Documentation: See Authentication Architecture

Request Flow

1. Client Request
   β”‚
   β”œβ”€β–Ί External Proxy (api.example.com)
   β”‚
   β”œβ”€β–Ί Internal Nginx (Port 9080)
   β”‚   β”œβ”€β–Ί Security Checks (Rate Limiting, Attack Detection)
   β”‚   β”œβ”€β–Ί Request Size Validation
   β”‚   β”œβ”€β–Ί Content Security Policy Headers
   β”‚   └─► Proxy to FastAPI (http://api:8000)
   β”‚
   β”œβ”€β–Ί FastAPI Middleware Stack
   β”‚   β”œβ”€β–Ί Sentry Request Handler
   β”‚   β”‚   └─► Request Context Capture
   β”‚   β”‚
   β”‚   β”œβ”€β–Ί CORS
   β”‚   β”‚   └─► Origin Validation
   β”‚   β”‚
   β”‚   β”œβ”€β–Ί Advanced Security Middleware
   β”‚   β”‚   β”œβ”€β–Ί Input Sanitization
   β”‚   β”‚   β”œβ”€β–Ί SQL Injection Detection
   β”‚   β”‚   β”œβ”€β–Ί XSS Detection
   β”‚   β”‚   └─► Command Injection Detection
   β”‚   β”‚
   β”‚   └─► Permission Middleware
   β”‚       └─► JWT Validation & Permission Check
   β”‚
   β”œβ”€β–Ί Route Handler
   β”‚   β”œβ”€β–Ί Request Validation (Pydantic)
   β”‚   β”œβ”€β–Ί Business Logic
   β”‚   β”œβ”€β–Ί Database Operations (SQLAlchemy)
   β”‚   └─► Response Formatting
   β”‚
   β”œβ”€β–Ί Activity Logging
   β”‚   └─► Log to Database
   β”‚
   └─► Response
       β”œβ”€β–Ί Error Handling (if any)
       β”œβ”€β–Ί Sentry Error Capture (if error)
       β”œβ”€β–Ί Security Headers
       └─► Client Response

Middleware Stack

The middleware stack processes requests in a specific order to ensure security, performance, and reliability:

  1. Sentry Request Handler - Captures request context for error tracking and performance monitoring
  2. CORS - Handles cross-origin requests with whitelist validation for allowed origins
  3. Advanced Security Middleware - Sanitizes input data and detects attack patterns
  4. Permission Middleware - Validates JWT tokens and checks user permissions
  5. Route Handlers - Application-specific logic execution
  6. Error Handler - Catches and formats errors with appropriate status codes
  7. Sentry Error Handler - Captures errors for monitoring and alerting

Database Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    PostgreSQL Database                      β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                             β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚  User Model                                          β”‚   β”‚
β”‚  β”‚  - user_id (UUID, Primary Key)                       β”‚   β”‚
β”‚  β”‚  - email, phone_number, user_name                    β”‚   β”‚
β”‚  β”‚  - password, auth_type                               β”‚   β”‚
β”‚  β”‚  - is_email_verified, is_phone_verified              β”‚   β”‚
β”‚  β”‚  - status, is_active, is_verified                    β”‚   β”‚
β”‚  β”‚  - profile_picture_url, bio                          β”‚   β”‚
β”‚  β”‚  - Relationships: UserGroup[], ActivityLog[]         β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                             β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚  Permission Model                                    β”‚   β”‚
β”‚  β”‚  - permission_id (UUID, Primary Key)                 β”‚   β”‚
β”‚  β”‚  - name, codename (unique)                           β”‚   β”‚
β”‚  β”‚  - description, category                             β”‚   β”‚
β”‚  β”‚  - Relationships: GroupPermission[]                  β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                             β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚  Group Model                                         β”‚   β”‚
β”‚  β”‚  - group_id (UUID, Primary Key)                      β”‚   β”‚
β”‚  β”‚  - name, codename (unique)                           β”‚   β”‚
β”‚  β”‚  - description, is_system, is_active                 β”‚   β”‚
β”‚  β”‚  - Relationships: GroupPermission[], UserGroup[]     β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                             β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚  GroupPermission Model (Many-to-Many)                β”‚   β”‚
β”‚  β”‚  - id (UUID, Primary Key)                            β”‚   β”‚
β”‚  β”‚  - group_id (FK β†’ Group)                             β”‚   β”‚
β”‚  β”‚  - permission_id (FK β†’ Permission)                   β”‚   β”‚
β”‚  β”‚  - Unique constraint: (group_id, permission_id)      β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                             β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚  UserGroup Model (Many-to-Many)                      β”‚   β”‚
β”‚  β”‚  - id (UUID, Primary Key)                            β”‚   β”‚
β”‚  β”‚  - user_id (FK β†’ User)                               β”‚   β”‚
β”‚  β”‚  - group_id (FK β†’ Group)                             β”‚   β”‚
β”‚  β”‚  - assigned_at, assigned_by_user_id                  β”‚   β”‚
β”‚  β”‚  - Unique constraint: (user_id, group_id)            β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                             β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚  ActivityLog Model                                   β”‚   β”‚
β”‚  β”‚  - log_id (UUID, Primary Key)                        β”‚   β”‚
β”‚  β”‚  - user_id (FK β†’ User, nullable)                     β”‚   β”‚
β”‚  β”‚  - level, message, action, module                    β”‚   β”‚
β”‚  β”‚  - ip_address, user_agent, device, browser, os       β”‚   β”‚
β”‚  β”‚  - endpoint, method, status_code                     β”‚   β”‚
β”‚  β”‚  - request_id, session_id                            β”‚   β”‚
β”‚  β”‚  - metadata, error_details (JSONB)                   β”‚   β”‚
β”‚  β”‚  - duration_ms, created_at                           β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Module Structure

FastAPI Backend API
β”œβ”€β”€ πŸ“ api/                              # Main application directory
β”‚   β”œβ”€β”€ πŸ“„ server.py                     # FastAPI server entry point
β”‚   β”œβ”€β”€ πŸ“„ db.py                         # Database CLI (Alembic wrapper)
β”‚   β”œβ”€β”€ πŸ“„ Dockerfile                    # Multi-stage Docker build
β”‚   β”œβ”€β”€ πŸ“„ requirements.txt              # Python dependencies
β”‚   β”œβ”€β”€ πŸ“„ start.sh                      # Container startup script
β”‚   β”œβ”€β”€ πŸ“„ alembic.ini                   # Alembic configuration
β”‚   β”‚
β”‚   β”œβ”€β”€ πŸ“ router/                       # API route handlers
β”‚   β”‚   β”œβ”€β”€ πŸ” authenticate/              # Authentication routes
β”‚   β”‚   β”‚   β”œβ”€β”€ authenticate.py          # Login, OTP, token management
β”‚   β”‚   β”‚   β”œβ”€β”€ authenticate.md          # Complete authentication docs
β”‚   β”‚   β”‚   β”œβ”€β”€ profile.py               # User profile management
β”‚   β”‚   β”‚   β”œβ”€β”€ profile.md               # Profile management docs
β”‚   β”‚   β”‚   β”œβ”€β”€ models.py                # Request validation schemas
β”‚   β”‚   β”‚   β”œβ”€β”€ query.py                 # Database queries
β”‚   β”‚   β”‚   └── utils.py                 # Helper functions
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“Š dashboard/                # Dashboard routes
β”‚   β”‚   β”‚   β”œβ”€β”€ api.py                   # Analytics and statistics
β”‚   β”‚   β”‚   └── dashboard.md            # Dashboard documentation
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ”‘ permissions/              # Permission management
β”‚   β”‚   β”‚   β”œβ”€β”€ api.py                   # Groups, permissions, users
β”‚   β”‚   β”‚   └── permissions.md          # Permissions documentation
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“ activity/                 # Activity logging
β”‚   β”‚   β”‚   β”œβ”€β”€ api.py                   # Activity log endpoints
β”‚   β”‚   β”‚   └── activity.md              # Activity logging docs
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“€ upload/                   # File upload
β”‚   β”‚   β”‚   β”œβ”€β”€ api.py                   # Media upload endpoints
β”‚   β”‚   β”‚   └── upload.md                # Upload documentation
β”‚   β”‚   β”‚
β”‚   β”‚   └── ❀️ health/                   # Health monitoring
β”‚   β”‚       β”œβ”€β”€ api.py                   # Health check endpoints
β”‚   β”‚       β”œβ”€β”€ health.md                # Health check docs
β”‚   β”‚       └── test_sentry.py          # Sentry test endpoint
β”‚   β”‚
β”‚   β”œβ”€β”€ πŸ“ src/                          # Source code modules
β”‚   β”‚   β”œβ”€β”€ πŸ” authenticate/             # Authentication logic
β”‚   β”‚   β”‚   β”œβ”€β”€ authenticate.py         # JWT validation
β”‚   β”‚   β”‚   β”œβ”€β”€ checkpoint.py            # User authentication
β”‚   β”‚   β”‚   β”œβ”€β”€ models.py                # User models
β”‚   β”‚   β”‚   β”œβ”€β”€ otp_cache.py             # OTP management
β”‚   β”‚   β”‚   └── session_manager.py       # Session management
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“Š activity/                 # Activity logging
β”‚   β”‚   β”‚   └── activityLog.py           # Activity log service
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ’Ύ cache/                    # Caching layer
β”‚   β”‚   β”‚   └── cache.py                # Redis cache utilities
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ—„οΈ db/                       # Database layer
β”‚   β”‚   β”‚   β”œβ”€β”€ models/                  # SQLAlchemy models
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ user.py              # User model
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ permission.py        # Permission model
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ group.py             # Group model
β”‚   β”‚   β”‚   β”‚   └── activity_log.py      # Activity log model
β”‚   β”‚   β”‚   └── postgres/                # PostgreSQL utilities
β”‚   β”‚   β”‚       β”œβ”€β”€ postgres.py          # Connection pool
β”‚   β”‚   β”‚       β”œβ”€β”€ triggers.py          # Database triggers
β”‚   β”‚   β”‚       └── init_triggers.py     # Trigger initialization
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“§ email/                    # Email service
β”‚   β”‚   β”‚   β”œβ”€β”€ email.py                 # Email sending
β”‚   β”‚   β”‚   └── templete.py              # Email templates
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“‹ enum/                     # Enumerations
β”‚   β”‚   β”‚   └── enum.py                  # Application enums
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“ logger/                   # Logging system
β”‚   β”‚   β”‚   └── logger.py                # Custom logger
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ›‘οΈ middleware/               # FastAPI middleware
β”‚   β”‚   β”‚   β”œβ”€β”€ advanced_security_middleware.py  # Security checks
β”‚   β”‚   β”‚   β”œβ”€β”€ input_sanitizer.py       # Input sanitization
β”‚   β”‚   β”‚   β”œβ”€β”€ permission_middleware.py # Permission checking
β”‚   β”‚   β”‚   └── security_middleware.py  # Security middleware
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ”‘ permissions/               # Permission system
β”‚   β”‚   β”‚   └── permissions.py            # Permission utilities
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“€ response/                  # Response handlers
β”‚   β”‚   β”‚   β”œβ”€β”€ success.py               # Success responses
β”‚   β”‚   β”‚   β”œβ”€β”€ error.py                 # Error responses
β”‚   β”‚   β”‚   └── map.py                   # Response mapping
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ“± sms/                       # SMS service
β”‚   β”‚   β”‚   └── sms.py                   # Twilio integration
β”‚   β”‚   β”‚
β”‚   β”‚   β”œβ”€β”€ πŸ’Ύ storage/                   # File storage
β”‚   β”‚   β”‚   β”œβ”€β”€ base_cloud_storage.py    # Base storage class
β”‚   β”‚   β”‚   └── media_storage.py         # Google Cloud Storage
β”‚   β”‚   β”‚
β”‚   β”‚   └── 🌐 multilingual/              # Multilingual support
β”‚   β”‚       └── multilingual.py          # Language utilities
β”‚   β”‚
β”‚   β”œβ”€β”€ πŸ“ alembic/                       # Database migrations
β”‚   β”‚   β”œβ”€β”€ versions/                     # Migration files
β”‚   β”‚   └── env.py                       # Alembic environment
β”‚   β”‚
β”‚   β”œβ”€β”€ πŸ“ credentials/                   # Service credentials
β”‚   β”‚   └── google-backend-master.json   # GCS credentials
β”‚   β”‚
β”‚   β”œβ”€β”€ πŸ“ logs/                          # Application logs
β”‚   β”‚   └── server.log                   # Server logs
β”‚   β”‚
β”‚   β”œβ”€β”€ πŸ“„ AUTH_ARCHITECTURE.md           # Authentication architecture
β”‚   └── πŸ“„ JWT_CONFIG.md                 # JWT configuration
β”‚
β”œβ”€β”€ πŸ“ docs/                              # Documentation
β”‚   β”œβ”€β”€ ARCHITECTURE.md                   # System architecture
β”‚   β”œβ”€β”€ TECHNICAL.md                      # Technical specifications
β”‚   β”œβ”€β”€ BACKEND_DEVELOPER.md              # Backend developer guide
β”‚   β”œβ”€β”€ FRONTEND_DEVELOPER.md             # Frontend developer guide
β”‚   └── README.md                         # Documentation index
β”‚
β”œβ”€β”€ πŸ“ nginx/                             # Nginx configuration
β”‚   β”œβ”€β”€ nginx.conf                        # Main nginx config
β”‚   β”œβ”€β”€ proxy.conf                        # Proxy settings
β”‚   β”œβ”€β”€ security.conf                    # Security headers
β”‚   └── conf.d/                          # Additional configs
β”‚
β”œβ”€β”€ πŸ“ k8s/                               # Kubernetes configurations
β”‚   β”œβ”€β”€ README.md                         # K8s documentation
β”‚   β”œβ”€β”€ ARCHITECTURE.md                   # K8s architecture
β”‚   └── SETUP.md                         # K8s setup guide
β”‚
β”œβ”€β”€ πŸ“„ docker-compose.yaml                # Docker Compose config
β”œβ”€β”€ πŸ“„ reload.sh                          # Deployment script
└── πŸ“„ README.md                          # This file

πŸ“š API Documentation

Authentication & User Management

Complete Documentation: Authentication Router

Endpoints:

  • POST /{MODE}/auth/login-with-password - Login with email/phone and password
  • POST /{MODE}/auth/login-with-otp - Login with OTP
  • POST /{MODE}/auth/send-one-time-password - Send OTP via email/SMS/WhatsApp
  • POST /{MODE}/auth/verify-one-time-password - Verify OTP
  • POST /{MODE}/auth/verify - Signup/Register with OTP
  • POST /{MODE}/auth/set-password - Set password for authenticated user
  • POST /{MODE}/auth/change-password - Change user password
  • POST /{MODE}/auth/forget-password - Reset password with OTP
  • POST /{MODE}/auth/refresh-token - Refresh access tokens
  • POST /{MODE}/auth/logout - Logout and revoke tokens
  • POST /{MODE}/auth/check-user-availability - Check email/phone availability
  • POST /{MODE}/auth/verify-email-and-phone - Verify email/phone with OTP

Profile Management: Profile Router

Endpoints:

  • GET /{MODE}/settings/profile - Get user profile
  • GET /{MODE}/settings/profile/{user_id} - Get profile by ID
  • POST /{MODE}/settings/profile-picture - Update profile picture
  • PUT /{MODE}/settings/profile - Update user profile
  • POST /{MODE}/settings/change-email - Change email with OTP verification
  • POST /{MODE}/settings/change-phone - Change phone with OTP verification
  • POST /{MODE}/settings/profile-accessibility - Update profile accessibility
  • POST /{MODE}/settings/profile-language - Update profile language
  • POST /{MODE}/settings/update-theme - Update theme preference
  • POST /{MODE}/settings/update-timezone - Update timezone
  • GET /{MODE}/settings - Get user settings
  • POST /{MODE}/settings/deactivate-account - Deactivate account
  • POST /{MODE}/settings/delete-account - Delete account

Permissions & Groups

Complete Documentation: Permissions Router

Endpoints:

  • GET /{MODE}/permissions - Get all permissions
  • GET /{MODE}/permissions/{permission_id} - Get permission by ID
  • POST /{MODE}/permissions - Create new permission
  • PUT /{MODE}/permissions/{permission_id} - Update permission
  • DELETE /{MODE}/permissions/{permission_id} - Delete permission
  • GET /{MODE}/groups - Get all groups
  • GET /{MODE}/groups/{group_id} - Get group by ID
  • POST /{MODE}/groups - Create new group
  • PUT /{MODE}/groups/{group_id} - Update group
  • DELETE /{MODE}/groups/{group_id} - Delete group
  • POST /{MODE}/groups/{group_id}/permissions - Assign permissions to group
  • GET /{MODE}/users/{user_id}/groups - Get user groups
  • GET /{MODE}/users/{user_id}/permissions - Get user permissions
  • POST /{MODE}/users/{user_id}/groups - Assign groups to user
  • GET /{MODE}/users/me/groups - Get current user groups
  • GET /{MODE}/users/me/permissions - Get current user permissions

Dashboard & Analytics

Complete Documentation: Dashboard Router

Endpoints:

  • GET /{MODE}/dashboard/overview - Get dashboard overview statistics
  • GET /{MODE}/dashboard/users-by-status - Get users grouped by status
  • GET /{MODE}/dashboard/users-by-type - Get users grouped by type
  • GET /{MODE}/dashboard/users-by-auth-type - Get users grouped by auth type
  • GET /{MODE}/dashboard/users-by-country - Get users grouped by country
  • GET /{MODE}/dashboard/users-by-language - Get users grouped by language
  • GET /{MODE}/dashboard/user-growth - Get user growth statistics
  • GET /{MODE}/dashboard/role-statistics - Get role/group statistics
  • GET /{MODE}/dashboard/recent-sign-ins - Get recent sign-in activity
  • GET /{MODE}/dashboard/all-statistics - Get all statistics

File Upload

Complete Documentation: Upload Router

Endpoints:

  • POST /{MODE}/upload/media - Upload media file (direct upload or URL)
  • DELETE /{MODE}/upload/media/{file_id} - Delete uploaded media

Features:

  • Direct file upload with multipart/form-data
  • URL-based upload (downloads and stores file from URL)
  • Google Cloud Storage integration
  • Automatic file validation and processing
  • Support for images, videos, and documents

Activity Logging

Complete Documentation: Activity Router

Endpoints:

  • GET /{MODE}/activity - Get activity logs with filtering
  • GET /{MODE}/activity/{log_id} - Get specific activity log
  • POST /{MODE}/activity - Create activity log entry

Features:

  • Comprehensive audit trail
  • User action tracking
  • Request/response logging
  • Error logging with details
  • Metadata storage (JSONB)

Health Monitoring

Complete Documentation: Health Router

Endpoints:

  • GET /health - Basic health check (no prefix)
  • GET /{MODE}/health - Detailed health check
  • GET /{MODE}/health/system - System health with metrics
  • GET /{MODE}/health/database - Database connection health
  • GET /{MODE}/health/storage - Storage (GCS) health check
  • GET /{MODE}/health/test-sentry - Test Sentry integration

πŸ“¦ Installation & Setup

Prerequisites

System Requirements:

  • OS: Linux (Ubuntu 20.04+), macOS, or Windows with WSL2
  • Python: 3.11 or higher (recommended for Google Cloud libraries compatibility)
    • ⚠️ Note: Python 3.10 will reach end-of-life for Google API Core in 2026-10-04
  • PostgreSQL: 12+ (for production)
  • Redis: 6+ (optional, for caching and token blacklisting)
  • Docker: 20.10+ (for containerized deployment)
  • Docker Compose: 2.0+ (for multi-container orchestration)
  • Google Cloud Storage: Account and bucket (for media files)

Development Tools:

  • Git 2.30+
  • Code editor (VS Code recommended)
  • Postman or similar API testing tool

Quick Start

Step 1: Clone Repository

git clone https://github.com/fullstack-open-source/fastapi-backend-with-sql.git
cd fastapi-backend-with-sql

Step 2: Setup Environment

# Copy example environment file
cp example.env .env

# Edit .env file with your configuration
nano .env

Step 3: Setup Google Cloud Storage Credentials (Optional)

If you plan to use file upload features, you need to configure Google Cloud Storage credentials:

# Navigate to credentials directory
cd api/credentials

# Copy the template credential file
cp "google-backend-master copy.json" google-backend-master.json

# Edit the credential file with your Google Cloud Service Account credentials
nano google-backend-master.json

How to get Google Cloud Service Account credentials:

  1. Go to Google Cloud Console
  2. Select or create a project
  3. Navigate to IAM & Admin β†’ Service Accounts
  4. Create a new service account or select an existing one
  5. Click on the service account β†’ Keys tab
  6. Click Add Key β†’ Create new key β†’ Choose JSON format
  7. Download the JSON file
  8. Copy the contents of the downloaded JSON file into api/credentials/google-backend-master.json

Step 4: Start Services with Docker Compose

# Create Docker network (if not exists)
docker network create fastapi_backend_with_postgresql_network

# Start all services
docker compose up -d

# Check service status
docker compose ps

# View logs
docker compose logs -f api

Step 5: Setup Database Schema

# Run database migrations
docker compose exec api python db.py upgrade

# Seed database (optional)
docker compose exec api python db.py seed

Step 6: Access Services

Note: Replace {MODE} with your configured MODE value (e.g., prod/v1 or dev/v1)

API Route Prefix (MODE)

All API routes are prefixed with the MODE environment variable. This allows you to version your API and separate environments.

Configuration in .env:

MODE=prod/v1    # For production API version 1
# or
MODE=dev/v1     # For development API version 1

API Route Examples:

If MODE=prod/v1, all routes will be prefixed with /prod/v1/:

  • Health Check: http://localhost:9080/prod/v1/health
  • Authentication: http://localhost:9080/prod/v1/auth/login-with-password
  • Profile: http://localhost:9080/prod/v1/settings/profile
  • Dashboard: http://localhost:9080/prod/v1/dashboard/overview
  • Permissions: http://localhost:9080/prod/v1/permissions
  • Activity: http://localhost:9080/prod/v1/activity
  • Upload: http://localhost:9080/prod/v1/upload/media

Note: The /health endpoint is available without the MODE prefix for health checks:

  • Direct Health Check: http://localhost:9080/health (no prefix)

Development Setup

Step 1: System Preparation

# Update system packages
sudo apt update && sudo apt upgrade -y

# Install Python 3.9+
sudo apt install python3.9 python3.9-venv python3-pip -y

# Install Docker (optional, for containerized development)
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo apt install docker-compose-plugin -y

Step 2: Project Setup

# Clone repository
git clone https://github.com/fullstack-open-source/fastapi-backend-with-sql.git
cd fastapi-backend-with-sql/api

# Create virtual environment
python3 -m venv venv

# Activate virtual environment
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

Step 3: Environment Configuration

# Copy example environment file
cp ../example.env ../.env

# Edit .env file with your settings
nano ../.env

Step 4: Database Setup (Local PostgreSQL)

# Install PostgreSQL
sudo apt install postgresql postgresql-contrib -y

# Create database and user
sudo -u postgres psql << EOF
CREATE DATABASE fastapi_backend;
CREATE USER fastapi_user WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE fastapi_backend TO fastapi_user;
\q
EOF

# Update .env with local database connection
# DATABASE_URL=postgresql://fastapi_user:your_password@localhost:5432/fastapi_backend

Step 5: Database Migrations

# Database CLI commands (using db.py)
python db.py upgrade       # Apply all pending migrations
python db.py migrate       # Create a new migration
python db.py downgrade     # Rollback last migration
python db.py history       # Show migration history
python db.py current       # Show current migration
python db.py seed          # Seed the database with default data
python db.py reset         # Reset database (drop all tables and recreate)

Step 6: Start Development Server

# Development mode with auto-reload
uvicorn server:app --reload --host 0.0.0.0 --port 8000

# Or using the start script
./start.sh

Step 7: Access Application

Note: Replace {MODE} with your configured MODE value (e.g., prod/v1 or dev/v1)

Production Setup

Step 1: Server Preparation

# Update system
sudo apt update && sudo apt upgrade -y

# Install Python 3.9+
sudo apt install python3.9 python3.9-venv python3-pip -y

# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo apt install docker-compose-plugin -y

Step 2: Clone and Setup Project

# Clone repository
git clone https://github.com/fullstack-open-source/fastapi-backend-with-sql.git
cd fastapi-backend-with-sql

# Create production .env file
cp example.env .env

# Edit .env file with production settings
nano .env

Important: Update .env file with production values:

  • Set API_MODE=production
  • Set DEBUG_MODE=false
  • Configure production database credentials
  • Set strong JWT secret (generate with: openssl rand -base64 32)
  • Configure production Redis, Sentry, and other services
  • Set GOOGLE_STORAGE_BUCKET_NAME with your production bucket name

Step 3: Deploy with Docker (Recommended)

# Build and start services
docker compose build
docker compose up -d

# Check status
docker compose ps

# View logs
docker compose logs -f api

# Run migrations
docker compose exec api python db.py upgrade

Step 4: Configure External Proxy (Nginx)

# Install Nginx
sudo apt install nginx -y

# Create Nginx config
sudo nano /etc/nginx/sites-available/api.example.com

Add configuration:

server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://localhost:9080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
# Enable site
sudo ln -s /etc/nginx/sites-available/api.example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Docker Setup

Step 1: Prerequisites

# Check Docker version
docker --version
docker compose version

# Install Docker if needed
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo apt install docker-compose-plugin -y

Step 2: Docker Compose Services

The docker-compose.yaml includes:

  • api: FastAPI application (Python server)
  • db: PostgreSQL database
  • redis: Redis cache and session store
  • nginx: Internal reverse proxy
  • pgadmin: PostgreSQL admin interface

Step 3: Build and Start Services

# Create Docker network
docker network create fastapi_backend_with_postgresql_network

# Build images
docker compose build

# Start all services
docker compose up -d

# View all logs
docker compose logs -f

# View specific service logs
docker compose logs -f api
docker compose logs -f nginx

Step 4: Service Management

# Stop services
docker compose stop

# Start services
docker compose start

# Restart services
docker compose restart

# Restart specific service
docker compose restart api

# Stop and remove containers
docker compose down

# Stop, remove containers, and volumes
docker compose down -v

Step 5: Execute Commands in Containers

# Run database migrations
docker compose exec api python db.py upgrade

# Seed database
docker compose exec api python db.py seed

# Access container shell
docker compose exec api sh

# Access PostgreSQL
docker compose exec db psql -U postgres -d postgres

Step 6: Health Checks

# Check service health
docker compose ps

# Test API health endpoint
curl http://localhost:9080/health

# Test Nginx health endpoint
curl http://localhost:9080/health

πŸ”„ Complete Project Workflow

Service Connection Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Docker Network                               β”‚
β”‚              (fastapi_backend_with_postgresql_network)          β”‚
β”‚                                                                 β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                                               β”‚
β”‚  β”‚   Client     β”‚                                               β”‚
β”‚  β”‚  (Browser)   β”‚                                               β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜                                               β”‚
β”‚         β”‚                                                       β”‚
β”‚         β”‚ HTTP/HTTPS (Port 9080)                                β”‚
β”‚         β–Ό                                                       β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚  Nginx Service                                           β”‚   β”‚
β”‚  β”‚  Container: fastapi-backend-nginx                        β”‚   β”‚
β”‚  β”‚  Port: 9080:80 (host:container)                          β”‚   β”‚
β”‚  β”‚  Config: ./nginx/nginx.conf                              β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚         β”‚                                                       β”‚
β”‚         β”‚ Proxy to http://api:8000                              β”‚
β”‚         β–Ό                                                       β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚  API Service (FastAPI)                                   β”‚   β”‚
β”‚  β”‚  Container: fastapi-backend                              β”‚   β”‚
β”‚  β”‚  Port: 8000 (internal only)                              β”‚   β”‚
β”‚  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚   β”‚
β”‚  β”‚  β”‚  SQLAlchemy ORM                                    β”‚  β”‚   β”‚
β”‚  β”‚  β”‚  - Database models                                 β”‚  β”‚   β”‚
β”‚  β”‚  β”‚  - Connection pooling                              β”‚  β”‚   β”‚
β”‚  β”‚  β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚            β”‚                                                    β”‚
β”‚            β”‚ PostgreSQL Connection                              β”‚
β”‚            β”‚ (postgresql://postgres:postgres@                   β”‚
β”‚            β”‚  fastapi-backend-db:5432/postgres)                 β”‚
β”‚            β–Ό                                                    β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚  PostgreSQL Service                                      β”‚   β”‚
β”‚  β”‚  Container: fastapi-backend-db                           β”‚   β”‚
β”‚  β”‚  Port: 5432 (internal only)                              β”‚   β”‚
β”‚  β”‚  Volume: postgres_data (persistent)                      β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚            β–²                                                    β”‚
β”‚            β”‚                                                    β”‚
β”‚            β”‚ Redis Connection                                   β”‚
β”‚            β”‚ (redis://fastapi-backend-redis:6379)               β”‚
β”‚            β”‚                                                    β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”‚
β”‚  β”‚  Redis Service                                         β”‚     β”‚
β”‚  β”‚  Container: fastapi-backend-redis                      β”‚     β”‚
β”‚  β”‚  Port: 6379 (internal only)                            β”‚     β”‚
β”‚  β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚     β”‚
β”‚  β”‚  β”‚  Cache Storage                                   β”‚  β”‚     β”‚
β”‚  β”‚  β”‚  - OTP cache                                     β”‚  β”‚     β”‚
β”‚  β”‚  β”‚  - Session storage                               β”‚  β”‚     β”‚
β”‚  β”‚  β”‚  - Token blacklist                               β”‚  β”‚     β”‚
β”‚  β”‚  β”‚  - Rate limiting data                            β”‚  β”‚     β”‚
β”‚  β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚     β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Service Startup Order

1. Docker Network
   └─► fastapi_backend_with_postgresql_network

2. Database Services (Start First)
   β”œβ”€β–Ί PostgreSQL (fastapi-backend-db:5432)
   └─► Redis (fastapi-backend-redis:6379)

3. API Service (Waits for Database Health Checks)
   β”œβ”€β–Ί Connects to PostgreSQL via SQLAlchemy
   └─► Connects to Redis for Cache

4. Nginx Service (Waits for API Health Check)
   └─► Proxies to API (http://api:8000)

5. pgAdmin Service (Optional, Waits for Database)
   └─► Connects to PostgreSQL

Connection Flow

Client Request
    β”‚
    β–Ό
Port 9080 (Host) ──► Nginx ──► Port 8000 ──► FastAPI Service
                                         β”‚
                                         β”œβ”€β–Ί PostgreSQL (Port 5432)
                                         └─► Redis (Port 6379)

πŸ“– Detailed Documentation

Core Documentation

API Router Documentation

Developer Documentation

Database Documentation

Kubernetes Documentation

πŸ” Authentication System

Multi-Token Architecture

The authentication system uses a three-token approach similar to Instagram:

  1. Access Token (1 hour)

    • Lightweight token for API authentication
    • Minimal payload for fast validation
    • Includes JTI (JWT ID) for efficient blacklisting
  2. Session Token (7 days) - Recommended

    • Contains full user profile and permissions
    • Fastest validation (no database lookup needed)
    • Preferred for frontend API calls
  3. Refresh Token (30 days)

    • Used to obtain new tokens when they expire
    • Cannot be used for API authentication
    • Rotates on each refresh for security

Complete Documentation: Authentication Architecture

Token Usage

Recommended Approach (Session Token):

# Store tokens after login
{
    "access_token": "...",
    "session_token": "...",  # RECOMMENDED for API calls
    "refresh_token": "...",
    "session_id": "..."
}

# Use session_token for API calls (fastest validation)
headers = {
    "X-Session-Token": session_token  # Preferred
    # OR
    "Authorization": f"Bearer {session_token}"  # Also works
}

πŸ“„ License & Open Source

This project is open source and free to use for all purposes with no restrictions.

🎯 Open Source License

This project is released under the MIT License, which means:

  • βœ… Free to use for any purpose (commercial or personal)
  • βœ… No restrictions on usage, modification, or distribution
  • βœ… No warranty provided
  • βœ… Attribution is appreciated but not required

πŸ“„ Full License Text: See LICENSE file for complete license terms and conditions.

πŸ™ Technologies & Acknowledgments

This project is built with amazing open-source technologies. Special thanks to:

Core Framework & Runtime

  • FastAPI - Modern, fast web framework for building APIs with Python
  • Python - High-level programming language

Database & ORM

  • PostgreSQL - Advanced open-source relational database
  • SQLAlchemy - Python SQL toolkit and ORM
  • Alembic - Database migration tool
  • Redis - In-memory data structure store

Security & Authentication

  • PyJWT - JSON Web Token implementation
  • bcrypt - Password hashing library
  • passlib - Password hashing library

Monitoring & Logging

API Documentation

Utilities & Validation

  • Pydantic - Data validation using Python type annotations
  • python-dotenv - Environment variable management

Communication Services

  • Twilio - Cloud communications platform

Storage

Containerization

Web Server

  • Nginx - High-performance web server and reverse proxy

🌟 Contributing

Contributions are welcome! This is an open-source project, and we encourage:

  • πŸ› Bug reports
  • πŸ’‘ Feature requests
  • πŸ“ Documentation improvements
  • πŸ”§ Code contributions
  • ⭐ Starring the repository

πŸ“ž Support

For issues, questions, or contributions, please visit:


Made with ❀️ using open-source technologies

This project is free to use, modify, and distribute for any purpose without restrictions.


πŸ“œ License

Copyright (c) 2025 Full Stack Open Source

This project is licensed under the MIT License - see the LICENSE file for details.