Claude API Python Flask Backend Setup Guide
Setting up a Python Flask backend that talks to the Claude API means three things: a Flask app that exposes your own routes, a server-side client that calls Claude (never from the browser), and a clean way to pass responses back to your frontend — including streamed tokens if you need them. This guide walks through the whole setup, from project structure to a working /chat endpoint, plus the common mistakes that break things in production.
The short version: install anthropic (or point requests at an OpenAI-compatible gateway), store your key in an environment variable, build a Flask route that forwards the user's message to Claude, and return the JSON response or stream it with Flask's Response generator. The rest of this article fills in the details that matter once you move past a toy script.
Project structure
A minimal but production-sane layout:
claude-flask-app/
├── app.py
├── .env
├── requirements.txt
└── routes/
└── chat.py
Install dependencies:
pip install flask python-dotenv anthropic gunicorn
Keep your API key out of source control entirely:
# .env
ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxx
FLASK_ENV=production
Basic Flask app with a Claude-backed route
# app.py
import os
from flask import Flask, request, jsonify
from dotenv import load_dotenv
from anthropic import Anthropic
load_dotenv()
app = Flask(__name__)
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
@app.route("/chat", methods=["POST"])
def chat():
data = request.get_json(silent=True) or {}
user_message = data.get("message", "").strip()
if not user_message:
return jsonify({"error": "message field is required"}), 400
try:
response = client.messages.create(
model="claude-3-5-sonnet-latest",
max_tokens=1024,
messages=[{"role": "user", "content": user_message}],
)
reply = response.content[0].text
return jsonify({"reply": reply})
except Exception as e:
app.logger.error(f"Claude API error: {e}")
return jsonify({"error": "upstream error"}), 502
if __name__ == "__main__":
app.run(debug=True, port=5000)
This covers the essentials: validate input, call the model, catch upstream failures, and never leak the raw exception to the client.
Adding system prompts and conversation history
Most real apps need a system prompt and multi-turn context, not just a single message:
@app.route("/chat", methods=["POST"])
def chat():
data = request.get_json(silent=True) or {}
history = data.get("history", []) # list of {"role": ..., "content": ...}
system_prompt = data.get("system", "You are a concise, helpful assistant.")
response = client.messages.create(
model="claude-3-5-sonnet-latest",
max_tokens=1024,
system=system_prompt,
messages=history,
)
return jsonify({"reply": response.content[0].text})
Keep history management on the server or in a database tied to a session ID — don't trust the client to send an unbounded array of past messages without a length cap, or you'll blow through your token budget fast.
Streaming responses from Flask
If your frontend needs tokens as they arrive, Flask can stream a generator back using text/event-stream or chunked plain text:
from flask import Response
@app.route("/chat/stream", methods=["POST"])
def chat_stream():
data = request.get_json(silent=True) or {}
user_message = data.get("message", "")
def generate():
with client.messages.stream(
model="claude-3-5-sonnet-latest",
max_tokens=1024,
messages=[{"role": "user", "content": user_message}],
) as stream:
for text in stream.text_stream:
yield text
return Response(generate(), mimetype="text/plain")
This works fine behind gunicorn with sync workers for low concurrency, but if you expect many simultaneous streaming connections, switch to an async-friendly worker class (gevent or eventlet) or move to an ASGI framework for that specific route.
Handling errors and rate limits properly
Claude's API returns structured errors for rate limiting, overload, and invalid requests. Don't just catch a generic exception — branch on status when you can:
from anthropic import APIStatusError, APIConnectionError
try:
response = client.messages.create(...)
except APIStatusError as e:
if e.status_code == 429:
return jsonify({"error": "rate limited, retry shortly"}), 429
return jsonify({"error": "claude api error"}), 502
except APIConnectionError:
return jsonify({"error": "network issue reaching claude"}), 503
Add a retry with backoff for transient 429/529 errors, and log the request ID if the SDK exposes one — it's the fastest way to debug an issue with support.
Configuration checklist before deploying
- Load the API key from environment variables, never hardcode it.
- Set a
max_tokensceiling appropriate to your use case to control cost. - Rate-limit your own
/chatendpoint (Flask-Limiter works well) so one user can't exhaust your Claude quota. - Run Flask behind
gunicornwith a reasonable worker count, not the dev server. - Add CORS headers only for the origins your frontend actually uses.
Skipping the plumbing with SubToAPI
If you'd rather not manage SDK versions, retries, and streaming plumbing yourself, SubToAPI turns your existing Claude access into a plain HTTPS API with an application key (sub_live_...). Your Flask route then just does a normal HTTPS POST instead of managing the Anthropic SDK directly:
import requests
resp = requests.post(
"https://api.subtoapi.app/v1/messages",
headers={"Authorization": f"Bearer {os.environ['SUBTOAPI_KEY']}"},
json={
"model": "claude-3-5-sonnet-latest",
"max_tokens": 1024,
"messages": [{"role": "user", "content": user_message}],
},
)
Streaming, tool use, and usage metadata work the same way as the native API — see the quickstart, messages docs, and streaming guide for details. Plans start with a free trial at signup, and pricing is on the pricing page.
questions
Do I need Flask specifically, or does this work with FastAPI too? The pattern is the same for any Python framework — Flask, FastAPI, Django. You still need a server-side client call to Claude and a route that forwards requests. FastAPI's async support makes streaming slightly cleaner, but Flask handles it fine with the right worker setup.
Should I call the Claude API directly from my frontend JavaScript? No. Your API key would be exposed in the browser. Always route calls through your Flask backend, which holds the key server-side and forwards only the response data to the client.
What's the minimum Flask setup to test the Claude API locally? A single route like the /chat example above, a .env file with your key, and flask run is enough to test locally. Add error handling, rate limiting, and logging before deploying to production.