Tutorial6 min read
Deploy a Python FastAPI App with OpenClaw
FastAPI's async support and automatic docs make it ideal for AI backends. Here's how to deploy with OpenClaw.
FastAPI is the best Python framework for AI backends. It has native async support, automatic OpenAPI docs, and Pydantic validation.
The FastAPI App
# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
openclaw.init()
yield
# Shutdown
openclaw.close()
app = FastAPI(lifespan=lifespan)
class ChatRequest(BaseModel):
message: str
userId: str | None = None
@app.get('/health')
async def health():
return {'status': 'ok'}
@app.post('/chat')
async def chat(req: ChatRequest):
response = await openclaw.chat(req.message, user_id=req.userId)
return {'response': response}
Run
uvicorn main:app --host 0.0.0.0 --port 3000
Deploy
fly launch --no-deploy
fly secrets set OPENAI_API_KEY=sk-...
fly deploy
API Docs
FastAPI automatically generates OpenAPI docs at /docs. Swagger UI at /docs, ReDoc at /redoc.