FastAPI is Python’s modern, async-native web framework — combining OpenAPI documentation generation, Pydantic data validation, and async/await performance in a developer-friendly package. Deployed on a Hong Kong VPS, FastAPI’s async architecture handles concurrent requests efficiently, and CN2 GIA routing delivers API responses to mainland Chinese clients at latency that Python-on-Heroku or AWS Lambda cannot match from US regions.
FastAPI vs Django vs Flask: When to Choose Each
| Factor | FastAPI | Django | Flask |
|---|---|---|---|
| Async support | Native (ASGI) | Partial (ASGI via Daphne) | Bolt-on (Quart) |
| API development speed | Fastest (auto-docs, validation) | Good (DRF) | Manual |
| ORM | SQLAlchemy/Tortoise (external) | Built-in Django ORM | SQLAlchemy (external) |
| Admin panel | No built-in | Built-in (excellent) | No built-in |
| Best for | Microservices, AI/ML APIs | Full-stack web apps | Simple APIs, prototypes |
Step 1: Install Python and Create Virtual Environment
<code">apt update && apt upgrade -y apt install -y python3.11 python3.11-venv python3-pip \ nginx certbot python3-certbot-nginx postgresql postgresql-contrib ufw useradd -m -s /bin/bash fastapi mkdir -p /opt/fastapi-app chown fastapi:fastapi /opt/fastapi-app su - fastapi cd /opt/fastapi-app python3.11 -m venv venv source venv/bin/activate pip install fastapi uvicorn[standard] gunicorn \ sqlalchemy asyncpg alembic pydantic-settings \ python-jose[cryptography] passlib[bcrypt] \ redis aioredis httpx python-multipart
Step 2: Application Structure
<code"># Project layout
mkdir -p {app/{routers,models,schemas,services},alembic}
cat > app/main.py << 'EOF'
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from app.routers import auth, users, products
from app.database import engine, Base
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup: create tables (use Alembic migrations in production)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
# Shutdown: close connections
await engine.dispose()
app = FastAPI(
title="HK API",
description="Hong Kong VPS FastAPI — CN2 GIA powered",
version="1.0.0",
docs_url="/docs", # Swagger UI
redoc_url="/redoc", # ReDoc
lifespan=lifespan
)
# Security middleware
app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=["api.yourdomain.com", "localhost"]
)
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.yourdomain.com"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Routers
app.include_router(auth.router, prefix="/api/v1/auth", tags=["auth"])
app.include_router(users.router, prefix="/api/v1/users", tags=["users"])
app.include_router(products.router, prefix="/api/v1/products", tags=["products"])
@app.get("/health")
async def health_check():
return {"status": "healthy", "region": "hong-kong-cn2gia"}
EOF
Async Database Setup
<code"># app/database.py
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import DeclarativeBase, sessionmaker
import os
DATABASE_URL = os.getenv("DATABASE_URL").replace(
"postgresql://", "postgresql+asyncpg://"
)
engine = create_async_engine(
DATABASE_URL,
pool_size=20,
max_overflow=10,
pool_pre_ping=True,
echo=False # Set True for SQL query logging in development
)
AsyncSessionLocal = sessionmaker(
engine, class_=AsyncSession, expire_on_commit=False
)
class Base(DeclarativeBase):
pass
# Dependency for route handlers
async def get_db():
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
Example Router with Pydantic Validation
<code"># app/routers/products.py
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Optional
import uuid
from app.database import get_db
from app.models.product import Product
router = APIRouter()
class ProductCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=200)
price: float = Field(..., gt=0, description="Price in HKD")
description: Optional[str] = None
sku: str = Field(..., pattern=r'^[A-Z0-9-]+$')
class ProductResponse(BaseModel):
id: uuid.UUID
name: str
price: float
description: Optional[str]
sku: str
class Config:
from_attributes = True
@router.get("/", response_model=list[ProductResponse])
async def list_products(
skip: int = Query(0, ge=0),
limit: int = Query(20, ge=1, le=100),
db: AsyncSession = Depends(get_db)
):
result = await db.execute(
select(Product).offset(skip).limit(limit)
)
return result.scalars().all()
@router.post("/", response_model=ProductResponse, status_code=201)
async def create_product(
product_in: ProductCreate,
db: AsyncSession = Depends(get_db)
):
product = Product(**product_in.model_dump())
db.add(product)
await db.flush()
await db.refresh(product)
return product
Step 3: Environment Configuration
<code"># app/config.py — Pydantic Settings
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
redis_url: str = "redis://localhost:6379/0"
secret_key: str
algorithm: str = "HS256"
access_token_expire_minutes: int = 30
allowed_hosts: list[str] = ["api.yourdomain.com"]
class Config:
env_file = ".env"
settings = Settings()
# .env file:
cat > /opt/fastapi-app/.env << 'ENVEOF'
DATABASE_URL=postgresql://fastapi:Password!@localhost/fastapi_db
REDIS_URL=redis://:RedisPass@localhost:6379/0
SECRET_KEY=GENERATE_64_CHAR_SECRET
ALGORITHM=HS256
ENVEOF
chmod 600 /opt/fastapi-app/.env
Step 4: Gunicorn + Uvicorn Workers
<code"># gunicorn.conf.py import multiprocessing workers = multiprocessing.cpu_count() * 2 + 1 worker_class = "uvicorn.workers.UvicornWorker" bind = "127.0.0.1:8000" keepalive = 75 timeout = 60 graceful_timeout = 30 max_requests = 1000 max_requests_jitter = 100 loglevel = "info" accesslog = "/opt/fastapi-app/logs/access.log" errorlog = "/opt/fastapi-app/logs/error.log"
<code">exit # Back to root
mkdir -p /opt/fastapi-app/logs
chown fastapi:fastapi /opt/fastapi-app/logs
cat > /etc/systemd/system/fastapi.service << 'EOF'
[Unit]
Description=FastAPI Application
After=network.target postgresql.service
[Service]
User=fastapi
Group=fastapi
WorkingDirectory=/opt/fastapi-app
EnvironmentFile=/opt/fastapi-app/.env
ExecStart=/opt/fastapi-app/venv/bin/gunicorn \
-c /opt/fastapi-app/gunicorn.conf.py \
app.main:app
ExecReload=/bin/kill -s HUP $MAINPID
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
EOF
systemctl enable --now fastapi
systemctl status fastapi
Step 5: Nginx with Rate Limiting
<code">cat > /etc/nginx/sites-available/fastapi << 'EOF'
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=30r/s;
limit_req_zone $binary_remote_addr zone=auth_limit:10m rate=5r/m;
upstream fastapi_backend {
server 127.0.0.1:8000;
keepalive 32;
}
server {
listen 443 ssl http2;
server_name api.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/api.yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.yourdomain.com/privkey.pem;
client_max_body_size 10m;
server_tokens off;
location /api/v1/auth/ {
limit_req zone=auth_limit burst=10 nodelay;
proxy_pass http://fastapi_backend;
include proxy_params;
}
location /api/ {
limit_req zone=api_limit burst=100 nodelay;
proxy_pass http://fastapi_backend;
include proxy_params;
}
# Auto-generated API docs — restrict in production
location /docs {
allow YOUR_OFFICE_IP;
deny all;
proxy_pass http://fastapi_backend;
include proxy_params;
}
location /health {
proxy_pass http://fastapi_backend;
access_log off;
}
}
EOF
ln -s /etc/nginx/sites-available/fastapi /etc/nginx/sites-enabled/
certbot --nginx -d api.yourdomain.com
nginx -t && systemctl reload nginx
Step 6: Background Tasks with Celery
<code"># FastAPI background tasks for simple async operations (in-process)
from fastapi import BackgroundTasks
@router.post("/send-report")
async def trigger_report(
background_tasks: BackgroundTasks,
report_config: ReportConfig
):
# Returns immediately — report generates in background
background_tasks.add_task(generate_and_email_report, report_config)
return {"message": "Report generation started"}
# For heavy tasks, use Celery with Redis broker:
pip install celery[redis]
# celery_app.py
from celery import Celery
celery = Celery(
"hk-api",
broker=os.getenv("REDIS_URL"),
backend=os.getenv("REDIS_URL")
)
@celery.task
def process_heavy_job(job_id: str):
# Long-running task — runs in separate worker process
result = heavy_computation(job_id)
return result
Step 7: Redis Caching with aioredis
<code"># Async Redis caching for FastAPI endpoints
from redis.asyncio import from_url
import json
redis = from_url(os.getenv("REDIS_URL"), decode_responses=True)
def cache(ttl_seconds: int = 60):
def decorator(func):
async def wrapper(*args, **kwargs):
# Generate cache key from function name + arguments
cache_key = f"{func.__name__}:{hash(str(args) + str(kwargs))}"
cached = await redis.get(cache_key)
if cached:
return json.loads(cached)
result = await func(*args, **kwargs)
await redis.setex(cache_key, ttl_seconds, json.dumps(result))
return result
return wrapper
return decorator
# Usage
@router.get("/products/featured")
@cache(ttl_seconds=300) # Cache for 5 minutes
async def get_featured_products(db: AsyncSession = Depends(get_db)):
# Expensive query cached automatically
...
Conclusion
FastAPI on a Hong Kong VPS with Uvicorn workers and Gunicorn process management handles high-concurrency Python API workloads efficiently — async database queries with asyncpg, async Redis caching, and Pydantic validation create a complete, type-safe API backend that serves mainland Chinese clients at 30–60ms TTFB via CN2 GIA routing. The automatic OpenAPI documentation generation at /docs accelerates frontend integration, and the Celery/Redis combination offloads heavy background processing without blocking API responses.
Deploy your FastAPI: Browse Server.HK Hong Kong VPS plans — a 4 GB plan with 4 vCPU handles Gunicorn with multiple Uvicorn workers for most FastAPI production workloads.