All templates
Template7 min read

Python Template: FastAPI with SQLAlchemy and Pydantic

A production-ready Python FastAPI template with SQLAlchemy, Pydantic validation, async support, and OpenClaw deployment.

A production-ready Python FastAPI template with async database access, Pydantic validation, and automatic OpenClaw deployment.

What's Included

  • FastAPI — modern, fast async framework
  • SQLAlchemy 2.0 — async ORM
  • Pydantic v2 — validation
  • ** Alembic** — database migrations
  • Uvicorn — ASGI server
  • Gunicorn — production process manager

Quick Start

mkdir my-app && cd my-app
python -m venv .venv && source .venv/bin/activate
pip install fastapi sqlalchemy pydantic alembic uvicorn gunicorn

Project Structure

my-app/
├── app/
│   ├── main.py           # App entry point
│   ├── models.py         # SQLAlchemy models
│   ├── schemas.py        # Pydantic schemas
│   ├── database.py       # DB connection
│   └── routers/
│       └── tasks.py      # API routes
├── alembic/
│   └── migrations/
├── openclaw.json
└── requirements.txt

app/main.py

from fastapi import FastAPI
from app.database import engine, Base
from app.routers import tasks

app = FastAPI(title="My FastAPI App")

app.include_router(tasks.router)

@app.get("/health")
async def health():
    return {"status": "ok"}

app/models.py

from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.orm import DeclarativeBase
from datetime import datetime

class Base(DeclarativeBase):
    pass

class Task(Base):
    __tablename__ = "tasks"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow)

app/schemas.py

from pydantic import BaseModel
from datetime import datetime

class TaskCreate(BaseModel):
    title: str

class TaskResponse(TaskCreate):
    id: int
    created_at: datetime

    class Config:
        from_attributes = True

app/routers/tasks.py

from fastapi import APIRouter, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.models import Task
from app.schemas import TaskCreate, TaskResponse

router = APIRouter(prefix="/tasks", tags=["tasks"])

@router.get("", response_model=list[TaskResponse])
async def list_tasks(db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(Task).order_by(Task.created_at.desc()))
    return result.scalars().all()

@router.post("", response_model=TaskResponse)
async def create_task(task: TaskCreate, db: AsyncSession = Depends(get_db)):
    db_task = Task(**task.model_dump())
    db.add(db_task)
    await db.commit()
    await db.refresh(db_task)
    return db_task

openclaw.json

{
  "name": "my-fastapi-app",
  "runtime": "python",
  "port": 8000,
  "startCommand": "gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000",
  "healthCheck": "/health"
}

Deploy with OpenClaw

openclaw deploy

Deploy with EZClaw

Pair this backend with OpenClaw for AI assistant capabilities. EZClaw deploys OpenClaw to Fly.io in under a minute — no DevOps required.

Why FastAPI Over Flask

  • Async by default — handles more concurrent connections
  • Auto-generated docs — Swagger UI at /docs
  • Pydantic integration — automatic request/response validation
  • Type hints — better IDE support, fewer bugs

Skip the self-hosting

Deploy OpenClaw in under a minute

No servers. No SSH. No terminal. Pick a model, connect Telegram, and go.

Deploy free with Testflight