FastAPI Integration Guide

The ztlayer-fastapi package provides a native ASGI Middleware optimized for FastAPI and Starlette. It leverages asyncio to query the ZTLayer Edge network concurrently without blocking your event loop, maintaining FastAPI's extreme performance.


1. Installation

Install the package via pip.

pip install ztlayer-fastapi

2. Configuration & Initialization

Ensure your API key is set in your environment variables.

# .env
ZTLAYER_API_KEY="zt_live_xxxxxxxxxxxxxxxxxxxxxxxx"

To protect your application, use FastAPI's add_middleware method.

import os
from fastapi import FastAPI
from ztlayer_fastapi import ZTLayerMiddleware
 
app = FastAPI()
 
# 1. Attach the global security middleware
app.add_middleware(
    ZTLayerMiddleware,
    api_key=os.environ.get("ZTLAYER_API_KEY"),
    fail_mode="open",
    timeout_ms=1500,
    # Optional: Exclude Swagger UI and static files from inspection
    exclude_paths=["/docs", "/openapi.json", "/redoc"]
)
 
# 2. Define routes
@app.get("/")
async def root():
    return {"message": "Protected by ZTLayer Edge Security"}
 
@app.get("/api/data")
async def get_data():
    return {"status": "success", "data": [1, 2, 3]}

3. Route-Specific Protection (Dependencies)

If you prefer explicit control rather than global middleware, you can use FastAPI's Dependency Injection system to secure specific endpoints.

Note: You should not use both the Middleware and the Dependency on the same route.

from fastapi import FastAPI, Depends
from ztlayer_fastapi import ZTLayerSecurity
 
app = FastAPI()
 
# Initialize the dependency provider
zt_security = ZTLayerSecurity(api_key=os.environ.get("ZTLAYER_API_KEY"))
 
# 1. Unprotected public route
@app.get("/health")
async def health_check():
    return {"status": "ok"}
 
# 2. Protected sensitive route using Depends()
@app.post("/api/auth/login", dependencies=[Depends(zt_security.protect)])
async def login(credentials: dict):
    # This block only executes if ZTLayer verifies the request
    return {"token": "jwt_token_here"}

4. Handling Reverse Proxies

FastAPI apps are typically deployed behind uvicorn and a reverse proxy like Nginx or Traefik.

To ensure ZTLayer receives the correct client IP instead of the proxy IP, you must configure uvicorn to trust the X-Forwarded-For headers using the --proxy-headers and --forwarded-allow-ips flags.

# Correct Uvicorn Startup
uvicorn main:app --proxy-headers --forwarded-allow-ips='*' --host 0.0.0.0 --port 8000

Without these flags, ZTLayer will block your proxy IP if rate limits are triggered.