Lightning FastAPI - A containerised quick starter template for FastAPI backends with pre-configured authentication, database connections, and Docker support.
Project description
⚡️ Lightning-FastAPI Backend Starter
┌────────────────────────────────────────────────────────────────────┐
│ │
│▗ ▝ ▐ ▗ ▝ ▗▄▄▖ ▗ ▗▖ ▗▄▄ ▗▄▄ │
│▐ ▗▄ ▄▄ ▐▗▖ ▗▟▄ ▗▗▖ ▗▄ ▗▗▖ ▄▄ ▐ ▄▖ ▄▖ ▗▟▄ ▐▌ ▐ ▝▌ ▐ │
│▐ ▐ ▐▘▜ ▐▘▐ ▐ ▐▘▐ ▐ ▐▘▐ ▐▘▜ ▐▄▄▖▝ ▐ ▐ ▝ ▐ ▌▐ ▐▄▟▘ ▐ │
│▐ ▐ ▐ ▐ ▐ ▐ ▐ ▐ ▐ ▐ ▐ ▐ ▐ ▐ ▐ ▗▀▜ ▀▚ ▐ ▙▟ ▐ ▐ │
│▐▄▄▖▗▟▄ ▝▙▜ ▐ ▐ ▝▄ ▐ ▐ ▗▟▄ ▐ ▐ ▝▙▜ ▐ ▝▄▜ ▝▄▞ ▝▄ ▐ ▌▐ ▗▟▄ │
│ ▖▐ ▖▐ │
│ ▝▘ ▝▘ │
└────────────────────────────────────────────────────────────────────┘
⚡️ By JY
Table of Contents
- Lightning-FastAPI Backend Starter
Introduction
This is a FastAPI-based backend starter project that provides complete user authentication, database integration, and Docker deployment support to help you quickly start new backend project development.
Acknowledgements
Shoutout to @liseami for the inspiration.
Features
- ✅ Complete user authentication system (registration, login, JWT tokens)
- ✅ Row-level security (RLS) support
- ✅ SMS verification code functionality
- ✅ Todo list example API
- ✅ Docker containerized deployment
- ✅ Automated database migration
- ✅ Development and production environment configuration
- ✅ Optimized project structure
- ✅ Cursor smart rules (Python FastAPI rule)
- ✅ SQLModel integration with FastAPI
- ✅ Multi-environment support (development, staging, production)
- ✅ Complete CI/CD workflow configuration
- ✅ Global error handling mechanisms
- ✅ Asynchronous database operations
- ✅ API performance optimization guidelines
- ✅ Lifecycle management (lifespan)
- ✅ Automated deployment scripts
- ✅ Fast project creation CLI tool
Quick Start ⚡
Method 1: Using Python Package (Simplest)
The easiest way is to install and use our Python command-line tool:
# Install the tool
pip3 install lightning-fastapi
# Create a new project named "my-backend"
lightning-fastapi my-backend
# Or create interactively without specifying a name
lightning-fastapi
This command will:
- Automatically create a new project directory
- Clone and configure all necessary files
- Create a new Git repository
- Automatically start the project using Docker
Note: The
lightning-fastapicommand is a tool for creating new projects; it will automatically start Docker containers. The created project itself still uses Poetry for dependency management.
Method 2: One-Click Startup
If you already have Docker and Docker Compose installed, you can use our one-click startup script:
# Clone the repository
git clone [repository URL] lighting-fastapi
cd lighting-fastapi
# Run the one-click startup script
chmod +x scripts/quickstart.sh
./scripts/quickstart.sh
This script will automatically:
- Check if Docker and Docker Compose are installed
- Create default environment configuration
- Start Docker containers with PostgreSQL database
- Setup and initialize the application
After successful startup, you can access the API documentation in your browser at http://localhost:8000/docs.
Technology Stack
- Database Mapping: SQLModel
- Dependency Management: Poetry
- API Framework: FastAPI
- Database Migration: Alembic
- Authentication: JWT Token
- Containerization: Docker & Docker Compose
Project Structure
The project uses a modular directory structure for easy extension and maintenance:
.
├── app/ # Main application code
│ ├── alembic/ # Database migration configuration
│ ├── api/ # API routes and dependencies
│ ├── core/ # Core configuration
│ ├── crud/ # Database operations
│ ├── models/ # Data models
│ ├── tool/ # Utility functions
│ ├── backend_pre_start.py # Pre-startup checks
│ ├── initial_data.py # Initial data
│ ├── log_info.py # Logging utility
│ └── main.py # Application entry point
├── config/ # Configuration files directory
│ ├── .env # Environment variable configuration
│ ├── .env.staging # Testing environment configuration
│ └── alembic.ini # Alembic migration configuration
├── docker/ # Docker-related files
│ ├── Dockerfile # Application container configuration
│ └── docker-compose.yml # Container orchestration configuration
├── docs/ # Documentation directory
│ └── PUBLISH.md # NPM package publishing guide
├── scripts/ # Scripts directory
│ ├── quickstart.sh # Quick start script
│ └── start.sh # Application startup script
├── tools/ # Development tools
│ ├── create-lighting-fastapi.js # NPX project creation script
│ └── package.json # NPM package configuration
├── .github/ # GitHub workflow configuration
├── .gitignore # Git ignore file
├── LICENSE # Project license
├── poetry.lock # Poetry locked dependencies
├── pyproject.toml # Python project configuration
└── README.md # Project documentation
Directory Description
- app/ - Core application code containing all business logic, API routes, and data models
- config/ - Project configuration files, such as environment variables and database migration settings
- docker/ - Docker-related files for containerized deployment
- docs/ - Project documentation directory
- scripts/ - Automation scripts for deployment, startup, and configuration
- tools/ - Development tools, such as NPX scripts for quick project creation
Complete Setup Guide
Here is a complete step-by-step guide to setting up the FastAPI Backend Starter project from scratch. Follow each step in order to quickly build a fully functional backend service.
1. Get the Code
# Clone the repository
git clone [repository URL] lighting-fastapi
cd lighting-fastapi
# Remove existing Git version control (if creating your own project)
rm -rf .git
2. Configure Environment Variables
Modify the .env file in the project root directory, updating the following configurations based on your PostgreSQL setup:
# Database configuration - Local development environment
POSTGRES_SERVER=host.docker.internal # Address for connecting to local database from Docker
# POSTGRES_SERVER=localhost # Use localhost if not using Docker
POSTGRES_PORT=5432 # PostgreSQL default port
POSTGRES_USER=postgres # Change to your PostgreSQL username
POSTGRES_PASSWORD=postgres # Change to your PostgreSQL password
POSTGRES_DB=fastapi_starter # The database name you created
# Superadmin configuration - Please modify to your own settings
FIRST_SUPERUSER=admin
FIRST_SUPERUSER_PHONE_NUMBER=13800138000
FIRST_SUPERUSER_PASSWORD=admin123
# Whether to open registration
USERS_OPEN_REGISTRATION=True
3. Start the Project with Docker
Make sure you have Docker and Docker Compose installed, then execute the following commands:
# Build and start containers
docker compose -f docker/docker-compose-local.yml up -d
# Check running status
docker compose -f docker/docker-compose-local.yml ps
Note: First startup requires downloading images and installing dependencies, which may take several minutes. Please be patient.
4. Verify Project Status
You can verify if the project is running normally using the following methods:
# View container logs
docker compose -f docker/docker-compose-local.yml logs -f
After successful startup, you will see output similar to the following:
app-1 | 🚀 —————————————————— Program started
app-1 | 🌍 Running environment: development
app-1 | 📝 Project name: lightning-fastapi
app-1 | 🔗 API path: /api/v1
app-1 | ✅ —————————————————— Program started
Also, opening http://localhost:8000/docs in your browser should display the API documentation interface.
5. Database Migration (If Needed)
If you have modified the data models and need to update the database structure, follow these steps:
# Enter the application container
docker compose -f docker/docker-compose-local.yml exec app bash
# Generate migration script
alembic revision --autogenerate -m "describe your changes"
# Apply migration
alembic upgrade head
# Exit container
exit
6. Initialize New Git Repository (Optional)
If you plan to use this starter project as the foundation for your own project, you can initialize a new Git repository:
# Initialize new Git repository
git init
# Add all files
git add .
# Commit initial code
git commit -m "Initialize FastAPI Backend Starter Project"
# Add remote repository (replace with your own GitHub repository address)
git remote add origin https://github.com/your-username/your-repo-name.git
git branch -M main
git push -u origin main
Troubleshooting
If the project does not start normally, check the following points:
-
Port conflicts:
- Ensure port 8000 is not occupied by other applications
- To use another port, modify the port mapping in the
docker/docker-compose-local.ymlfile (e.g., "8080:8000")
-
Docker-related issues:
- Ensure Docker and Docker Compose are correctly installed (check using
docker --versionanddocker compose version) - Try rebuilding containers:
docker compose -f docker/docker-compose-local.yml up -d --build --force-recreate
- Ensure Docker and Docker Compose are correctly installed (check using
-
Permission issues:
- On Linux systems, you may need to use
sudoto run Docker commands
- On Linux systems, you may need to use
-
Clear Docker cache (if encountering strange issues):
docker compose -f docker/docker-compose-local.yml down docker system prune -a docker compose -f docker/docker-compose-local.yml up -d
Development Guide
Project Structure
app/
├── alembic/ # Database migration configuration
├── api/ # API routes and dependencies
│ ├── routes/ # API endpoint definitions
│ └── depends.py # Dependency injection
├── core/ # Core configuration
│ ├── config.py # Application configuration
│ ├── db.py # Database connection
│ └── security.py # Security-related
├── crud/ # Database operations
├── models/ # Data models
│ ├── base_models/ # Base models
│ ├── public_models/ # Public models
│ └── table.py # Table definitions
├── tool/ # Utility functions
├── backend_pre_start.py # Pre-startup checks
├── initial_data.py # Initial data
├── log_info.py # Logging utility
└── main.py # Application entry point
API Documentation
After starting the project, access the API documentation:
http://localhost:8000/docs
Dependency Management
The project uses Poetry for dependency management, which is independent of the lightning-fastapi tool:
- Install project dependencies:
# Enter your created project directory
cd your-project-name
poetry install
- Add new dependencies:
poetry add [package name]
- Remove dependencies:
poetry remove [package name]
- Activate virtual environment:
poetry shell
- Run commands in virtual environment:
poetry run uvicorn app.main:app --reload
Tip: Do not confuse the
lightning-fastapicommand-line tool with the project's own dependency management. The former is a tool for creating new projects, while the latter is the dependency management system for the project itself.
Custom Development
-
Add new models:
- Create new base models in
app/models/base_models/ - Add table definitions in
app/models/table.py
- Create new base models in
-
Add new CRUD operations:
- Create new CRUD files in
app/crud/
- Create new CRUD files in
-
Add new API routes:
- Create new route files in
app/api/routes/ - Register new routes in
app/api/main.py
- Create new route files in
Deployment & Customization
Deployment Configuration
This project includes complete deployment workflows and configuration files:
-
Local Development Environment:
docker/docker-compose-local.yml- Docker Compose configuration for local development environment
-
Production/Testing Environment:
docker/docker-compose.yml- Docker Compose configuration for production environmentconfig/.env.staging- Configuration file for testing environmentscripts/deploy.sh- Deployment script for deploying and restarting the application on servers
-
CI/CD Workflow:
.github/workflows/deploy-staging.yml- GitHub Actions workflow file for automatic deployment to testing environment
Project Customization
When using this Starter for your own project, remember to modify the following:
-
Project Name:
- Update
PROJECT_NAMEin the.envand.env.stagingfiles - Update image name and container name in
docker/docker-compose.ymlanddocker/docker-compose-local.yml - Update the following in
scripts/deploy.sh:# Change DEPLOY_DIR=/home/ubuntu/lightning-fastapi to DEPLOY_DIR=/home/ubuntu/your-project-name # Change ARCHIVE_NAME="lightning-fastapi.tar.gz" to ARCHIVE_NAME="your-project-name.tar.gz"
- Update
-
Deployment Path:
- Update the
DEPLOY_DIRvariable inscripts/deploy.sh - Update deployment path in
.github/workflows/deploy-staging.yml
- Update the
-
Database Configuration:
- Update database connection information in all environment files
-
Keys:
- Generate a new
SECRET_KEYfor JWT token signing, using the following command:openssl rand -base64 32
- Generate a new
-
Logo and Branding:
- Update startup logo and project information in
app/main.py
- Update startup logo and project information in
Error Handling
Database Migration Issues
If you encounter database table not existing errors when starting the application (e.g., relation "user" does not exist), you can resolve it using the following steps:
- Stop all running containers:
docker compose -f docker/docker-compose-quickstart.yml down
- Run the fix script:
chmod +x scripts/fix_migration.sh
./scripts/fix_migration.sh
License
This project is licensed under the MIT License - see the LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file lightning_fastapi-0.1.0.tar.gz.
File metadata
- Download URL: lightning_fastapi-0.1.0.tar.gz
- Upload date:
- Size: 15.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cc76b5fd9d9e926c5281ea2a96ef5a872e960ea273e9351d6bf39c8089d0d5b3
|
|
| MD5 |
66da900e5f6df2313bcb9541b5b280ce
|
|
| BLAKE2b-256 |
9fa3245219673c05ee51759904c182c53937e9315497c64dad429d34603c13fb
|
File details
Details for the file lightning_fastapi-0.1.0-py3-none-any.whl.
File metadata
- Download URL: lightning_fastapi-0.1.0-py3-none-any.whl
- Upload date:
- Size: 12.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bdc970986e7bbb661eba66b79e798450d3ea9173246c6d69391d88f24c88e768
|
|
| MD5 |
50371d60f0033486f840a904a2838d42
|
|
| BLAKE2b-256 |
65e4aabb2e07127a46d3bf7e65dc41836ef3d047e0190a91f16f27ce9e0fc686
|