Skip to content

A modern, high-performance FastAPI backend application built with Python 3.12+, featuring real-time Socket.IO communication, PostgreSQL database support, and a clean layered architecture.

Notifications You must be signed in to change notification settings

nicksonthc/py-backend-boilerplate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

5 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Python Backend Boilerplate

A modern, high-performance FastAPI backend application built with Python 3.12+, featuring real-time Socket.IO communication, PostgreSQL database support, and a clean layered architecture.

πŸš€ Features

  • Modern Python 3.12+ - Latest language features and performance improvements
  • FastAPI - High-performance web framework with automatic API documentation
  • Socket.IO - Real-time bidirectional communication
  • SQLModel - Modern SQL database toolkit combining SQLAlchemy + Pydantic
  • PostgreSQL - Robust open-source database with timezone support
  • Alembic - Database migration management
  • Async/Await - Full asynchronous support throughout the stack
  • Type Safety - Comprehensive type hints with Python 3.12+ syntax
  • Layered Architecture - Clean separation of concerns
  • RESTful API - Standardized API endpoints with filtering and pagination
  • Real-time Events - Live updates via WebSocket connections
  • Production Ready - Comprehensive error handling and logging

πŸ“‹ Prerequisites

  • Python 3.12+ (Required for modern type hints and features)
  • PostgreSQL 13+ (Local, Cloud, or Docker)
  • Git (For version control)

πŸ› οΈ Installation & Setup

1. Clone the Repository

git clone <repository-url>
cd py-backend-boilerplate

2. Create Virtual Environment

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

3. Install Dependencies

pip install -r requirements.txt

4. Environment Configuration

cp env.example .env

Edit .env with your configuration:

ENV=dev

# API configuration
API_HOST=127.0.0.1
API_PORT=3100

# TCP configuration
TCP_HOST=127.0.0.1
TCP_PORT=2525

# PostgreSQL Database
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your_password
POSTGRES_DB=backend-server

# Legacy MSSQL (for migration reference)
MSSQL_HOST=localhost
MSSQL_PORT=1433
MSSQL_USER=sa
MSSQL_PASSWORD=your_password
MSSQL_DB=py-backend

TIME_ZONE=Asia/Kuala_Lumpur

5. Database Setup

Option A: Local PostgreSQL

# Install PostgreSQL (Ubuntu/Debian)
sudo apt update
sudo apt install postgresql postgresql-contrib

# Create database
sudo -u postgres createdb backend-server

# Create user (optional)
sudo -u postgres createuser --interactive your_username

Option B: Docker PostgreSQL

# Run PostgreSQL in Docker
docker run --name postgres-backend \
  -e POSTGRES_PASSWORD=your_password \
  -e POSTGRES_DB=backend-server \
  -p 5432:5432 \
  -d postgres:15

# Or using docker-compose
docker-compose up -d postgres

Option C: WSL2 with Windows PostgreSQL

If running on WSL2 with PostgreSQL on Windows host:

  1. Update POSTGRES_HOST in .env to your Windows IP (e.g., 172.21.64.1)
  2. Configure PostgreSQL to accept connections from WSL2 network
  3. Update postgresql.conf: listen_addresses = '*'
  4. Update pg_hba.conf: Add host all all 172.21.0.0/16 md5

6. Initialize Database

# Initialize database and create tables
python -c "
import asyncio
from app.db.init_db import init_db
asyncio.run(init_db())
"

# Or run database migrations
alembic upgrade head

7. Validate Configuration

# Validate your setup
python validate_config.py

8. Start the Application

Development Mode

python run.py

Using Startup Script

./start.sh --dev

Production Mode

./start.sh --prod

πŸ—οΈ Project Structure

py-backend-boilerplate/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ api/v1/                 # API route definitions
β”‚   β”‚   β”œβ”€β”€ auth_routes.py      # Authentication endpoints
β”‚   β”‚   β”œβ”€β”€ job_routes.py       # Job endpoints
β”‚   β”‚   β”œβ”€β”€ order_routes.py     # Order endpoints
β”‚   β”‚   β”œβ”€β”€ setting_routes.py   # Settings endpoints
β”‚   β”‚   β”œβ”€β”€ log_event_routes.py # Log event endpoints
β”‚   β”‚   └── http_retry_routes.py # HTTP retry endpoints
β”‚   β”œβ”€β”€ auth/                   # Authentication services
β”‚   β”‚   β”œβ”€β”€ auth_services.py    # Auth business logic
β”‚   β”‚   └── token.py            # JWT token handling
β”‚   β”œβ”€β”€ controllers/            # Business logic layer
β”‚   β”‚   β”œβ”€β”€ base_controller.py  # Base controller class
β”‚   β”‚   β”œβ”€β”€ job_controller.py   # Job business logic
β”‚   β”‚   β”œβ”€β”€ order_controller.py # Order business logic
β”‚   β”‚   β”œβ”€β”€ setting_controller.py # Settings business logic
β”‚   β”‚   β”œβ”€β”€ log_controller.py   # Log business logic
β”‚   β”‚   β”œβ”€β”€ log_event_controller.py # Log event business logic
β”‚   β”‚   └── http_retry_controller.py # HTTP retry business logic
β”‚   β”œβ”€β”€ dal/                    # Data Access Layer
β”‚   β”‚   β”œβ”€β”€ base_dal.py         # Base DAL class
β”‚   β”‚   β”œβ”€β”€ job_dal.py          # Job data access
β”‚   β”‚   β”œβ”€β”€ order_dal.py        # Order data access
β”‚   β”‚   β”œβ”€β”€ setting_dal.py      # Settings data access
β”‚   β”‚   β”œβ”€β”€ log_dal.py          # Log data access
β”‚   β”‚   β”œβ”€β”€ log_event_dal.py    # Log event data access
β”‚   β”‚   └── http_retry_dal.py   # HTTP retry data access
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ entities/           # SQLModel database entities
β”‚   β”‚   β”‚   β”œβ”€β”€ base_timestamp.py # Base timestamp fields
β”‚   β”‚   β”‚   β”œβ”€β”€ job_model.py    # Job entity
β”‚   β”‚   β”‚   β”œβ”€β”€ order_model.py  # Order entity
β”‚   β”‚   β”‚   β”œβ”€β”€ setting_model.py # Settings entity
β”‚   β”‚   β”‚   β”œβ”€β”€ log_model.py    # Log entity
β”‚   β”‚   β”‚   β”œβ”€β”€ log_event_model.py # Log event entity
β”‚   β”‚   β”‚   └── http_retry_model.py # HTTP retry entity
β”‚   β”‚   └── schemas/            # Pydantic request/response schemas
β”‚   β”‚       β”œβ”€β”€ job_schema.py   # Job request/response models
β”‚   β”‚       β”œβ”€β”€ order_schema.py # Order request/response models
β”‚   β”‚       β”œβ”€β”€ setting_schema.py # Settings request/response models
β”‚   β”‚       β”œβ”€β”€ log_event_schema.py # Log event request/response models
β”‚   β”‚       └── http_retry_schema.py # HTTP retry request/response models
β”‚   β”œβ”€β”€ dto/                    # Data Transfer Objects
β”‚   β”‚   β”œβ”€β”€ auth_dto.py         # Authentication DTOs
β”‚   β”‚   └── setting_dto.py      # Settings DTOs
β”‚   β”œβ”€β”€ core/                   # Core configuration and utilities
β”‚   β”‚   β”œβ”€β”€ config.py           # Environment configuration
β”‚   β”‚   β”œβ”€β”€ middleware.py       # Response middleware
β”‚   β”‚   β”œβ”€β”€ response.py         # Standardized response models
β”‚   β”‚   β”œβ”€β”€ decorators.py       # Common decorators
β”‚   β”‚   β”œβ”€β”€ circuit_breaker.py  # Circuit breaker implementation
β”‚   β”‚   β”œβ”€β”€ socketio_manager.py # Socket.IO event management
β”‚   β”‚   β”œβ”€β”€ log_manager.py      # Log processing manager
β”‚   β”‚   β”œβ”€β”€ log_event_manager.py # Log event processing
β”‚   β”‚   β”œβ”€β”€ http_retry_manager.py # HTTP retry logic
β”‚   β”‚   β”œβ”€β”€ http_headers_manager.py # HTTP headers management
β”‚   β”‚   └── tcpip/              # TCP/IP communication
β”‚   β”‚       β”œβ”€β”€ tcp_server.py   # TCP server implementation
β”‚   β”‚       β”œβ”€β”€ async_tcp_server.py # Async TCP server
β”‚   β”‚       └── async_tcp_client.py # Async TCP client
β”‚   β”œβ”€β”€ db/                     # Database configuration
β”‚   β”‚   β”œβ”€β”€ base.py             # SQLAlchemy base
β”‚   β”‚   β”œβ”€β”€ session.py          # Async session management
β”‚   β”‚   └── init_db.py          # Database initialization
β”‚   β”œβ”€β”€ services/               # External service integrations
β”‚   β”œβ”€β”€ utils/                  # Utility functions
β”‚   β”‚   β”œβ”€β”€ console.py          # Console output utilities
β”‚   β”‚   β”œβ”€β”€ conversion.py       # Data conversion utilities
β”‚   β”‚   β”œβ”€β”€ enum.py             # Common enumerations
β”‚   β”‚   β”œβ”€β”€ logger.py           # Logging utilities
β”‚   β”‚   └── scheduler.py        # Task scheduling utilities
β”‚   └── main.py                 # FastAPI application entry point
β”œβ”€β”€ alembic/                    # Database migrations
β”‚   β”œβ”€β”€ versions/               # Migration version files
β”‚   β”œβ”€β”€ env.py                  # Alembic environment config
β”‚   └── script.py.mako          # Migration script template
β”œβ”€β”€ scripts/                    # Utility scripts
β”‚   β”œβ”€β”€ build_push_aws.sh       # AWS ECR build and push
β”‚   β”œβ”€β”€ bump_version.py         # Version bumping script
β”‚   β”œβ”€β”€ azuresql_docker.sh      # Azure SQL Docker setup
β”‚   └── mssql_docker.sh         # MSSQL Docker setup
β”œβ”€β”€ static/                     # Static files
β”‚   β”œβ”€β”€ swagger-ui/             # Custom Swagger UI assets
β”‚   └── redoc/                  # Custom ReDoc assets
β”œβ”€β”€ docs/                       # Documentation
β”œβ”€β”€ requirements.txt            # Python dependencies
β”œβ”€β”€ pyproject.toml              # Python project configuration
β”œβ”€β”€ run.py                      # Development server runner
β”œβ”€β”€ asgi.py                     # ASGI application for production
β”œβ”€β”€ seed.py                     # Database seeding script
β”œβ”€β”€ validate_config.py          # Configuration validation
β”œβ”€β”€ version.py                  # Application version
β”œβ”€β”€ start.sh                    # Startup script
β”œβ”€β”€ dockerfile                  # Docker configuration
β”œβ”€β”€ docker_compose.yml          # Docker Compose configuration
β”œβ”€β”€ Procfile                    # Process file for deployment
β”œβ”€β”€ env.example                 # Environment variables template
β”œβ”€β”€ alembic.ini                 # Alembic configuration
β”œβ”€β”€ MIGRATION_GUIDE.md          # Database migration guide
└── README.md                   # This file

🌐 API Documentation

Once the application is running, access the interactive API documentation:

Available Endpoints

Orders

  • GET /api/v1/orders - List orders with filtering and pagination
  • POST /api/v1/orders - Create new order
  • GET /api/v1/orders/{order_id} - Get specific order
  • PUT /api/v1/orders/{order_id} - Update order
  • DELETE /api/v1/orders/{order_id} - Delete order

Jobs

  • GET /api/v1/jobs - List jobs
  • POST /api/v1/jobs - Create new job
  • GET /api/v1/jobs/{job_id} - Get specific job
  • PUT /api/v1/jobs/{job_id} - Update job
  • DELETE /api/v1/jobs/{job_id} - Delete job

System

  • GET / - API welcome page
  • GET /health - Health check endpoint

πŸ”Œ Real-time Socket.IO

Connection Details

  • URL: ws://127.0.0.1:3100/ws/socket.io
  • Path: /ws/socket.io
  • Transport: WebSocket

Client Example

import socketio

# Create Socket.IO client
sio = socketio.Client()

# Connect to server
url = "ws://127.0.0.1:3100/ws/socket.io"
sio.connect(
    url, 
    socketio_path="/ws/socket.io", 
    wait_timeout=10, 
    transports=["websocket"]
)

# Listen for events
@sio.event
def connect():
    print("Connected to server!")

@sio.event
def disconnect():
    print("Disconnected from server!")

@sio.on("welcome")
def on_welcome(data):
    print(f"Welcome message: {data}")

# Emit events
sio.emit("ping", {"message": "Hello server!"})

Available Events

  • connect - Client connects
  • disconnect - Client disconnects
  • ping - Ping server (responds with pong)
  • join_room - Join a room
  • leave_room - Leave a room
  • welcome - Welcome message from server

πŸ—„οΈ Database Management

Generate Migrations

# Create new migration
alembic revision --autogenerate -m "Add new table"

# Apply migrations
alembic upgrade head

# Check current status
alembic current

# Rollback migration
alembic downgrade -1

Database Models

The application uses SQLModel entities with PostgreSQL timezone support and modern Python 3.12+ type hints:

from sqlmodel import SQLModel, Field
from datetime import datetime, timezone
from sqlalchemy import DateTime
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from .order_model import Order

class Job(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str = Field(max_length=100)
    status: str = Field(default="pending")
    order_id: int = Field(foreign_key="order.id")
    
    # Timezone-aware datetime with PostgreSQL support
    created_at: datetime = Field(
        default_factory=lambda: datetime.now(timezone.utc),
        sa_type=DateTime(timezone=True),
        nullable=False
    )
    
    # Relationships
    order: "Order" = Relationship(back_populates="jobs")

Timezone Support

All datetime fields use:

  • DateTime(timezone=True) for PostgreSQL TIMESTAMP WITH TIME ZONE
  • datetime.now(timezone.utc) for UTC defaults
  • Proper timezone-aware datetime handling throughout the application

πŸ§ͺ Development

Code Style

This project uses modern Python 3.12+ features:

  • Type Hints: str | None instead of Optional[str]
  • Type Aliases: type UserID = int
  • Pattern Matching: match/case statements
  • Enhanced F-strings: Latest f-string capabilities

Running Tests

# Run all tests
pytest

# Run with coverage
pytest --cov=app

# Run specific test file
pytest tests/test_orders.py

Code Formatting

# Format code with Black
black app/

# Sort imports with isort
isort app/

# Type checking with mypy
mypy app/

πŸš€ Deployment

Production Setup

  1. Set ENV=production in .env
  2. Configure production database credentials
  3. Set up proper CORS origins
  4. Configure logging and monitoring
  5. Use ASGI server (Gunicorn + Uvicorn)

Docker Deployment

AWS ECR Setup

Prerequisites:

  • Docker must be installed and running locally
  • AWS CLI configured with proper ECR permissions
  • Valid AWS credentials (via ~/.aws/credentials or environment variables)

1. Configure ECR Environment:

# Copy the example configuration
cp .env.aws.example .env.aws

# Edit .env.aws with your actual ECR details
# Update ECR_REGISTRY with your AWS account ID

2. Build and Push to ECR:

# Build and push Docker image (default tag: latest)
# The script automatically loads .env.aws
cd scripts
./build_push_aws.sh

# To use a custom image tag:
./build_push_aws.sh my_custom_tag

The build_push_aws.sh script will:

  1. Automatically load environment variables from .env.aws
  2. Validate required environment variables are set
  3. Build the Docker image with the specified tag (default: latest)
  4. Authenticate with AWS ECR using your AWS credentials
  5. Push the image to your configured ECR repository

Environment Variables Required:

  • ECR_REGISTRY: Your ECR registry URL (e.g., 123456789012.dkr.ecr.ap-southeast-1.amazonaws.com)
  • ECR_REPOSITORY: Repository name (default: py-backend)
  • AWS_REGION: AWS region (default: ap-southeast-1)

Environment Variables

Variable Description Default
ENV Environment (dev/prod) dev
API_HOST API server host 127.0.0.1
API_PORT API server port 3100
POSTGRES_HOST PostgreSQL host localhost
POSTGRES_PORT PostgreSQL port 5432
POSTGRES_USER PostgreSQL username postgres
POSTGRES_PASSWORD PostgreSQL password -
POSTGRES_DB PostgreSQL database backend-server
TIME_ZONE Application timezone Asia/Kuala_Lumpur

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ License

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

πŸ†˜ Support

  • Documentation: Check the /docs endpoint when server is running
  • Issues: Create an issue in the repository
  • Migration Guide: See MIGRATION_GUIDE.md for database changes

πŸ”— Related Links

About

A modern, high-performance FastAPI backend application built with Python 3.12+, featuring real-time Socket.IO communication, PostgreSQL database support, and a clean layered architecture.

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •  

Languages