Skip to content

Python FastAPI Backend API โ€‹

HaloLight FastAPI backend API is built on FastAPI 0.115+, providing modern asynchronous Python backend service.

API Documentation: https://halolight-api-python.h7ml.cn/api/docs

GitHub: https://github.com/halolight/halolight-api-python

Features โ€‹

  • ๐Ÿ” JWT Dual-Token - Access Token + Refresh Token, auto renewal
  • ๐Ÿ›ก๏ธ RBAC Permissions - Role-based access control, wildcard matching
  • ๐Ÿ“ก RESTful API - Standardized interface design, OpenAPI docs
  • ๐Ÿ—„๏ธ SQLAlchemy 2.0 - Type-safe database operations
  • โœ… Data Validation - Request parameter validation, error handling
  • ๐Ÿ“Š Logging System - Request logging, error tracking
  • ๐Ÿณ Docker Support - Containerized deployment

Tech Stack โ€‹

TechnologyVersionDescription
Python3.11+Runtime
FastAPI0.115+Web Framework
SQLAlchemy2.0+Database ORM
PostgreSQL16Data Storage
Pydanticv2Data Validation
JWTpython-joseAuthentication
Swagger UI-API Documentation

Quick Start โ€‹

Requirements โ€‹

  • Python >= 3.11
  • pip >= 23.0
  • PostgreSQL 16 (optional, defaults to SQLite)

Installation โ€‹

bash
# Clone repository
git clone https://github.com/halolight/halolight-api-python.git
cd halolight-api-python

# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate  # Windows: .venv\Scripts\activate

# Install dependencies
pip install -e .

Environment Variables โ€‹

bash
cp .env.example .env
env
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/halolight_db

# JWT Secret
JWT_SECRET=your-super-secret-key
JWT_ACCESS_EXPIRES=15m
JWT_REFRESH_EXPIRES=7d

# Service Config
PORT=8000
NODE_ENV=development

Database Initialization โ€‹

bash
alembic upgrade head           # Run migrations
python scripts/seed.py         # Seed data

Start Service โ€‹

bash
# Development mode
uvicorn app.main:app --reload --port 8000

# Production mode
uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4

Visit http://localhost:8000

Project Structure โ€‹

halolight-api-python/
โ”œโ”€โ”€ app/
โ”‚   โ”œโ”€โ”€ api/              # Controllers/Route handlers
โ”‚   โ”‚   โ”œโ”€โ”€ auth.py       # Auth endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ users.py      # User management
โ”‚   โ”‚   โ””โ”€โ”€ ...
โ”‚   โ”œโ”€โ”€ services/         # Business logic layer
โ”‚   โ”œโ”€โ”€ models/           # Data models
โ”‚   โ”œโ”€โ”€ schemas/          # Request validation
โ”‚   โ”œโ”€โ”€ core/             # Utility functions
โ”‚   โ””โ”€โ”€ main.py           # App entry
โ”œโ”€โ”€ alembic/              # Database migrations/Schema
โ”œโ”€โ”€ tests/                # Test files
โ”œโ”€โ”€ Dockerfile            # Docker config
โ”œโ”€โ”€ docker-compose.yml
โ””โ”€โ”€ pyproject.toml

API Modules โ€‹

Authentication Endpoints โ€‹

MethodPathDescriptionPermission
POST/api/auth/loginUser loginPublic
POST/api/auth/registerUser registrationPublic
POST/api/auth/refreshRefresh tokenPublic
POST/api/auth/logoutLogoutAuthenticated
POST/api/auth/forgot-passwordForgot passwordPublic
POST/api/auth/reset-passwordReset passwordPublic

User Management Endpoints โ€‹

MethodPathDescriptionPermission
GET/api/usersGet user listusers:view
GET/api/users/:idGet user detailsusers:view
POST/api/usersCreate userusers:create
PUT/api/users/:idUpdate userusers:update
DELETE/api/users/:idDelete userusers:delete
GET/api/users/meGet current userAuthenticated

Complete Endpoint List โ€‹

Document Management (Documents) - 5 endpoints โ€‹

MethodPathDescription
GET/api/documentsGet document list
GET/api/documents/:idGet document details
POST/api/documentsCreate document
PUT/api/documents/:idUpdate document
DELETE/api/documents/:idDelete document

File Management (Files) - 5 endpoints โ€‹

MethodPathDescription
GET/api/filesGet file list
GET/api/files/:idGet file details
POST/api/files/uploadUpload file
PUT/api/files/:idUpdate file info
DELETE/api/files/:idDelete file

Message Management (Messages) - 5 endpoints โ€‹

MethodPathDescription
GET/api/messagesGet message list
GET/api/messages/:idGet message details
POST/api/messagesSend message
PUT/api/messages/:id/readMark as read
DELETE/api/messages/:idDelete message

Notification Management (Notifications) - 4 endpoints โ€‹

MethodPathDescription
GET/api/notificationsGet notification list
PUT/api/notifications/:id/readMark as read
PUT/api/notifications/read-allMark all as read
DELETE/api/notifications/:idDelete notification

Calendar Management (Calendar) - 5 endpoints โ€‹

MethodPathDescription
GET/api/calendar/eventsGet event list
GET/api/calendar/events/:idGet event details
POST/api/calendar/eventsCreate event
PUT/api/calendar/events/:idUpdate event
DELETE/api/calendar/events/:idDelete event

Dashboard (Dashboard) - 6 endpoints โ€‹

MethodPathDescription
GET/api/dashboard/statsStatistics data
GET/api/dashboard/visitsVisit trends
GET/api/dashboard/salesSales data
GET/api/dashboard/piePie chart data
GET/api/dashboard/tasksTask list
GET/api/dashboard/calendarToday's schedule

Authentication Mechanism โ€‹

JWT Dual-Token โ€‹

Access Token:  15 minutes validity, used for API requests
Refresh Token: 7 days validity, used to refresh Access Token

Request Header โ€‹

http
Authorization: Bearer <access_token>

Refresh Flow โ€‹

python
# Token refresh example
import requests

response = requests.post(
    'http://localhost:8000/api/auth/refresh',
    json={'refreshToken': refresh_token}
)
new_tokens = response.json()

Permission System โ€‹

Role Definitions โ€‹

RoleDescriptionPermissions
super_adminSuper Admin* (all permissions)
adminAdministratorusers:*, documents:*, ...
userRegular Userdocuments:view, files:view, ...
guestGuestdashboard:view

Permission Format โ€‹

{resource}:{action}

Examples:
- users:view      # View users
- users:create    # Create user
- users:*         # All user operations
- *               # All permissions

Error Handling โ€‹

Error Response Format โ€‹

json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request parameter validation failed",
    "details": [
      { "field": "email", "message": "Invalid email format" }
    ]
  }
}

Error Codes โ€‹

Status CodeError CodeDescription
400VALIDATION_ERRORParameter validation failed
401UNAUTHORIZEDUnauthorized
403FORBIDDENForbidden
404NOT_FOUNDResource not found
409CONFLICTResource conflict
500INTERNAL_ERRORServer error

Database Models โ€‹

User Model โ€‹

python
# app/models/user.py
from sqlalchemy import Column, Integer, String, DateTime
from app.core.database import Base

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    email = Column(String, unique=True, nullable=False)
    username = Column(String, unique=True, nullable=False)
    hashed_password = Column(String, nullable=False)
    role = Column(String, default="user")
    created_at = Column(DateTime, server_default=func.now())
    updated_at = Column(DateTime, onupdate=func.now())

Document Model โ€‹

python
# app/models/document.py
from sqlalchemy import Column, Integer, String, Text, ForeignKey
from sqlalchemy.orm import relationship
from app.core.database import Base

class Document(Base):
    __tablename__ = "documents"

    id = Column(Integer, primary_key=True)
    title = Column(String, nullable=False)
    content = Column(Text)
    author_id = Column(Integer, ForeignKey("users.id"))
    author = relationship("User", back_populates="documents")

Environment Variables โ€‹

VariableDescriptionDefault
DATABASE_URLDatabase connection stringsqlite:///./halolight.db
JWT_SECRETJWT signing key-
JWT_ACCESS_EXPIRESAccess Token expiry15m
JWT_REFRESH_EXPIRESRefresh Token expiry7d
PORTService port8000
NODE_ENVRuntime environmentdevelopment
CORS_ORIGINSCORS allowed origins["http://localhost:3000"]

Unified Response Format โ€‹

Success Response โ€‹

json
{
  "success": true,
  "data": {
    "id": 1,
    "name": "Example data"
  },
  "message": "Operation successful"
}

Paginated Response โ€‹

json
{
  "success": true,
  "data": {
    "items": [...],
    "total": 100,
    "page": 1,
    "pageSize": 10,
    "totalPages": 10
  }
}

Error Response โ€‹

json
{
  "success": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Error description",
    "details": []
  }
}

Deployment โ€‹

Docker โ€‹

bash
docker build -t halolight-api-python .
docker run -p 8000:8000 halolight-api-python

Docker Compose โ€‹

bash
docker-compose up -d
yaml
# docker-compose.yml
version: '3.8'

services:
  app:
    build: .
    ports:
      - "8000:8000"
    environment:
      - NODE_ENV=production
      - DATABASE_URL=${DATABASE_URL}
      - JWT_SECRET=${JWT_SECRET}
    restart: unless-stopped

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: halolight
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

Production Configuration โ€‹

env
NODE_ENV=production
DATABASE_URL=postgresql://user:pass@host:5432/db
JWT_SECRET=your-production-secret

Testing โ€‹

Running Tests โ€‹

bash
pytest
pytest --cov=app tests/

Test Examples โ€‹

python
def test_login_success(client):
    response = client.post(
        "/api/auth/login",
        json={"email": "admin@example.com", "password": "123456"}
    )
    assert response.status_code == 200
    assert "accessToken" in response.json()

def test_get_users_with_permission(client, admin_token):
    response = client.get(
        "/api/users",
        headers={"Authorization": f"Bearer {admin_token}"}
    )
    assert response.status_code == 200
    assert isinstance(response.json()["data"], list)

Performance Metrics โ€‹

Benchmarks โ€‹

MetricValueDescription
Request Throughput5000+ QPSSingle-core uvicorn
Avg Response Time< 10msSimple queries
Memory Usage~100MBBase runtime
CPU Usage30-50%High load

Observability โ€‹

Logging System โ€‹

python
import logging

logger = logging.getLogger(__name__)
logger.info("User logged in", extra={"user_id": user.id})

Health Check โ€‹

python
@app.get("/health")
async def health_check():
    return {"status": "ok", "timestamp": datetime.now()}

Monitoring Metrics โ€‹

python
# Prometheus metrics endpoint
from prometheus_fastapi_instrumentator import Instrumentator

Instrumentator().instrument(app).expose(app)

Common Commands โ€‹

bash
# Development
uvicorn app.main:app --reload --port 8000

# Build
pip install -e .

# Testing
pytest
pytest --cov=app tests/

# Database
alembic upgrade head
alembic revision --autogenerate -m "description"

# Code Quality
black app tests
ruff check app tests --fix

FAQ โ€‹

Q: How to configure database connection pool? โ€‹

A: Configure SQLAlchemy connection pool in core/database.py

python
engine = create_engine(
    DATABASE_URL,
    pool_size=10,
    max_overflow=20,
    pool_timeout=30
)

Q: How to enable CORS? โ€‹

A: Configure CORS middleware in main.py

python
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Q: How to implement file upload? โ€‹

A: Use FastAPI's UploadFile type

python
from fastapi import UploadFile, File

@app.post("/api/upload")
async def upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    # Process file contents
    return {"filename": file.filename}

Development Tools โ€‹

  • Black - Python code formatter
  • Ruff - Fast linter
  • mypy - Type checker
  • pytest - Testing framework

Architecture Features โ€‹

Async Advantages โ€‹

FastAPI is based on Python's asyncio, supporting high-concurrency asynchronous operations:

python
@app.get("/api/async-example")
async def async_endpoint():
    result = await async_database_query()
    return result

Automatic Documentation โ€‹

FastAPI automatically generates OpenAPI (Swagger) documentation with no extra configuration:

  • Swagger UI: /docs
  • ReDoc: /redoc
  • OpenAPI Schema: /openapi.json

Dependency Injection System โ€‹

python
from fastapi import Depends

def get_current_user(token: str = Depends(oauth2_scheme)):
    return verify_token(token)

@app.get("/api/protected")
async def protected_route(user = Depends(get_current_user)):
    return {"user": user}

Backend Comparison โ€‹

FeatureFastAPINestJSGo FiberSpring Boot
LanguagePythonTypeScriptGoJava
ORMSQLAlchemyPrismaGORMJPA
Performanceโญโญโญโญโญโญโญโญโญโญโญโญโญโญโญโญ
Learning Curveโญโญโญโญโญโญโญโญโญโญโญโญโญ