Claude API Flask Backend Integration Tutorial
If you're building a Flask backend and want to add Claude for chat, summarization, or structured data extraction, the integration itself is straightforward: you send HTTP requests to an API endpoint, handle the JSON response, and expose your own route for the frontend to call. This tutorial walks through a complete working setup — a Flask route that calls Claude, handles streaming, manages errors, and stays secure in production.
We'll cover two integration paths: calling Anthropic's API directly with the requests library, and using SubToAPI as a drop-in HTTPS layer when you want API keys, usage metadata, and team access management without building that infrastructure yourself. Both use the same request/response shape, so the Flask code barely changes between them.
Project setup
Start with a minimal Flask app and a .env file for secrets. Install dependencies:
pip install flask python-dotenv requests
# .env
CLAUDE_API_KEY=sub_live_xxxxxxxxxxxxxxxx
CLAUDE_API_URL=https://api.subtoapi.app/v1/messages
Load environment variables at startup instead of hardcoding keys in source files. This matters even more in Flask apps that get committed to shared repos.
from flask import Flask, request, jsonify
import os
import requests
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
CLAUDE_API_KEY = os.environ["CLAUDE_API_KEY"]
CLAUDE_API_URL = os.environ.get("CLAUDE_API_URL", "https://api.subtoapi.app/v1/messages")
A basic chat endpoint
The core pattern: your frontend POSTs a message to your Flask route, Flask forwards it to Claude, and the response comes back as JSON.
@app.route("/api/chat", methods=["POST"])
def chat():
data = request.get_json(force=True)
user_message = data.get("message", "")
if not user_message:
return jsonify({"error": "message is required"}), 400
payload = {
"model": "claude-sonnet-4",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": user_message}
]
}
headers = {
"Authorization": f"Bearer {CLAUDE_API_KEY}",
"Content-Type": "application/json"
}
response = requests.post(CLAUDE_API_URL, json=payload, headers=headers, timeout=30)
if response.status_code != 200:
return jsonify({"error": "upstream error", "detail": response.text}), 502
result = response.json()
reply = result["content"][0]["text"]
return jsonify({"reply": reply})
This is enough to run locally and test with curl:
curl -X POST http://localhost:5000/api/chat \
-H "Content-Type: application/json" \
-d '{"message": "Summarize this ticket in one sentence."}'
Keep your Flask route as the only place that holds the API key — never pass it to the client. The browser or mobile app should only ever talk to your own backend.
Handling multi-turn conversations
For anything beyond single-shot prompts, you need to track conversation history per user or session. A simple approach stores messages server-side keyed by a session ID, then appends to the messages array on each request:
conversations = {}
@app.route("/api/chat", methods=["POST"])
def chat():
data = request.get_json(force=True)
session_id = data.get("session_id", "default")
user_message = data.get("message", "")
history = conversations.setdefault(session_id, [])
history.append({"role": "user", "content": user_message})
payload = {
"model": "claude-sonnet-4",
"max_tokens": 1024,
"messages": history
}
headers = {
"Authorization": f"Bearer {CLAUDE_API_KEY}",
"Content-Type": "application/json"
}
response = requests.post(CLAUDE_API_URL, json=payload, headers=headers, timeout=30)
result = response.json()
reply = result["content"][0]["text"]
history.append({"role": "assistant", "content": reply})
return jsonify({"reply": reply})
In production, replace the in-memory conversations dict with Redis or a database table — the dict will leak memory and won't survive a worker restart or a multi-process deployment under Gunicorn.
Streaming responses from Flask
If you want tokens to appear as they're generated rather than waiting for the full response, Flask supports this with a generator and Response object. Check the streaming docs for the exact event format if you're integrating against SubToAPI.
from flask import Response
import json
@app.route("/api/chat/stream", methods=["POST"])
def chat_stream():
data = request.get_json(force=True)
user_message = data.get("message", "")
payload = {
"model": "claude-sonnet-4",
"max_tokens": 1024,
"stream": True,
"messages": [{"role": "user", "content": user_message}]
}
headers = {
"Authorization": f"Bearer {CLAUDE_API_KEY}",
"Content-Type": "application/json"
}
def generate():
with requests.post(CLAUDE_API_URL, json=payload, headers=headers, stream=True) as r:
for line in r.iter_lines():
if line:
yield f"{line.decode('utf-8')}\n"
return Response(generate(), mimetype="text/event-stream")
On the frontend, read this with EventSource or a fetch reader to render partial output as it arrives. Streaming is especially useful for chat UIs where long responses otherwise feel slow.
Error handling and timeouts
Three failure modes are common and worth handling explicitly: network timeouts, rate limits, and malformed input. Wrap the request call and return meaningful status codes rather than letting Flask's default 500 page leak details:
try:
response = requests.post(CLAUDE_API_URL, json=payload, headers=headers, timeout=30)
response.raise_for_status()
except requests.exceptions.Timeout:
return jsonify({"error": "request timed out"}), 504
except requests.exceptions.HTTPError:
return jsonify({"error": "upstream rejected request", "status": response.status_code}), 502
Set max_tokens conservatively for your use case — overly large values increase both latency and cost per request without improving quality for short exchanges.
Why route through SubToAPI instead of calling Anthropic directly
The Flask code above works identically whether you point CLAUDE_API_URL at Anthropic directly or at SubToAPI. The practical difference is operational: SubToAPI gives you application-scoped API keys (sub_live_...) instead of one shared account credential, per-key usage metadata in a dashboard, and team seat management — useful once more than one developer or service touches the same Claude access. Plans start at €9/month for solo use, with Team and Scale tiers for shared workloads, and a free trial at signup if you want to test the Flask integration before committing. See pricing for tier details and the quickstart for a minimal working example outside Flask.
questions
Do I need an official Anthropic SDK to use Flask with Claude? No. Claude's API is plain HTTPS/JSON, so Python's requests library (as used above) is enough. An SDK saves boilerplate but isn't required for a Flask integration.
How do I keep multiple users' conversations separate in Flask? Key conversation history by a session or user ID and store it in Redis or a database, not in-memory, especially if you deploy with multiple Gunicorn workers.
Can I stream Claude responses through Flask to a React or Vue frontend? Yes — use a Flask generator with Response(mimetype="text/event-stream") on the backend and EventSource or a streaming fetch reader on the frontend, as shown in the streaming example above.