How to Deploy an AI API Wrapper with Postgres

Flask app wrapping Claude or OpenAI, with Postgres for storing conversations.

What you're building

A REST API that accepts chat messages, forwards them to Claude (or OpenAI), stores the conversation in Postgres, and returns the response.

The app

# app.py
import os
from flask import Flask, request, jsonify
from sqlalchemy import create_engine, text
import anthropic

app = Flask(__name__)
engine = create_engine(os.environ["DATABASE_URL"])
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

@app.route("/health")
def health():
    return jsonify({"status": "ok"})

@app.route("/api/chat", methods=["POST"])
def chat():
    user_msg = request.json["message"]

    response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=1024,
        messages=[{"role": "user", "content": user_msg}]
    )
    reply = response.content[0].text

    with engine.connect() as conn:
        conn.execute(text(
            "INSERT INTO chats (user_message, ai_response) VALUES (:u, :a)"
        ), {"u": user_msg, "a": reply})
        conn.commit()

    return jsonify({"response": reply})

requirements.txt:

flask
gunicorn
anthropic
psycopg2-binary
sqlalchemy

How do I deploy it?

Step 1: Create the app

create_app(
  name: "my-ai-api",
  github_repo: "github.com/me/my-ai-api"
)

Step 2: Attach Postgres

attach_postgres(
  app_name: "my-ai-api",
  environment: "dev",
  tier: "pg-1"
)

Step 3: Set your API key as a secret

set_secret(
  app_name: "my-ai-api",
  environment: "dev",
  key: "ANTHROPIC_API_KEY",
  value: "sk-ant-..."
)

Step 4: Add a Dockerfile and deploy

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE $PORT
CMD gunicorn --bind 0.0.0.0:$PORT app:app
deploy_app(app_name: "my-ai-api", branch: "main")

Create your table: After deploying, use query_postgres to create the chats table:

query_postgres(
  app_name: "my-ai-api",
  environment: "dev",
  sql: "CREATE TABLE IF NOT EXISTS chats (id SERIAL PRIMARY KEY, user_message TEXT, ai_response TEXT, created_at TIMESTAMP DEFAULT NOW())"
)

How do I use OpenAI instead?

Swap anthropic for openai in requirements.txt, use OPENAI_API_KEY as your secret, and change the API call. Everything else stays the same.

Next steps