← Blog

Claude API Python Flask Integration Example

2026-11-16 · 5 min read · SubToAPI Team

If you're looking to integrate the Claude API into a Python Flask application, this guide walks through a complete working example: setting up the Flask project, calling Claude from a route, handling streaming responses, and dealing with errors and rate limits properly.

The short answer is that you install the anthropic Python SDK, create a client with your API key, and call client.messages.create() from inside a Flask route handler, returning the result as JSON or as a streamed response. The rest of this article covers the details that actually matter in production: environment variable handling, streaming with Flask's response objects, async considerations, and an alternative setup using an OpenAI-compatible endpoint if you want to avoid vendor-specific SDK code entirely.

Setting Up the Project

Start with a clean virtual environment and install the dependencies:

python -m venv venv
source venv/bin/activate
pip install flask anthropic python-dotenv

Create a .env file to hold your API key — never hardcode it in source:

ANTHROPIC_API_KEY=sk-ant-your-key-here

Basic Flask App Structure

# app.py
import os
from flask import Flask, request, jsonify
from anthropic import Anthropic
from dotenv import load_dotenv

load_dotenv()

app = Flask(__name__)
client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))

@app.route("/chat", methods=["POST"])
def chat():
    data = request.get_json()
    user_message = data.get("message", "")

    if not user_message:
        return jsonify({"error": "message is required"}), 400

    try:
        response = client.messages.create(
            model="claude-opus-4-20250514",
            max_tokens=1024,
            messages=[{"role": "user", "content": user_message}],
        )
        reply = response.content[0].text
        return jsonify({"reply": reply, "usage": response.usage.model_dump()})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(debug=True, port=5000)

This is a minimal, working endpoint. Send a POST request with {"message": "Explain Flask blueprints"} to /chat and you'll get a JSON reply with the model's response and token usage.

Adding System Prompts and Conversation History

Real applications need more than a single message. Here's a version that accepts a conversation array and an optional system prompt:

@app.route("/chat", methods=["POST"])
def chat():
    data = request.get_json()
    messages = data.get("messages", [])
    system_prompt = data.get("system", "You are a helpful assistant.")

    if not messages:
        return jsonify({"error": "messages array is required"}), 400

    try:
        response = client.messages.create(
            model="claude-opus-4-20250514",
            max_tokens=1024,
            system=system_prompt,
            messages=messages,
        )
        return jsonify({
            "reply": response.content[0].text,
            "stop_reason": response.stop_reason,
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

This structure maps cleanly to how a frontend chat UI would send data — the client keeps the message history and sends the whole array on each turn.

Streaming Responses in Flask

Streaming is where Flask integrations often get messy, because anthropic's streaming SDK produces a generator that needs to be wrapped in a Flask Response with the right mimetype.

from flask import Response, stream_with_context

@app.route("/chat/stream", methods=["POST"])
def chat_stream():
    data = request.get_json()
    messages = data.get("messages", [])

    def generate():
        with client.messages.stream(
            model="claude-opus-4-20250514",
            max_tokens=1024,
            messages=messages,
        ) as stream:
            for text in stream.text_stream:
                yield text

    return Response(stream_with_context(generate()), mimetype="text/plain")

On the frontend, consume this with fetch() and read the body as a stream, or point an EventSource-style client at it if you convert the output to SSE format. For most internal tools, plain chunked text streaming is enough.

Handling Rate Limits and Retries

Direct API calls to any LLM provider will eventually hit rate limits, especially under load from multiple Flask workers (gunicorn with several processes multiplies your effective request rate). A simple retry wrapper helps:

import time
from anthropic import RateLimitError

def call_with_retry(**kwargs):
    for attempt in range(3):
        try:
            return client.messages.create(**kwargs)
        except RateLimitError:
            time.sleep(2 ** attempt)
    raise RuntimeError("Rate limit exceeded after retries")

This is fine for low-traffic apps. For anything serving real users, you want centralized rate limit handling, retries, and usage tracking that doesn't live inside every route handler.

Simplifying the Integration Layer

One pattern worth considering if you're deploying this Flask app for a team or a product: route Claude calls through a single HTTPS API key instead of distributing your raw Anthropic key across environments, CI pipelines, and teammates' laptops. SubToAPI turns your existing Claude access into an API with its own sub_live_... keys, so your Flask code barely changes — you just point the base URL at https://api.subtoapi.app/v1/messages and swap the key.

import requests
import os

response = requests.post(
    "https://api.subtoapi.app/v1/messages",
    headers={
        "Authorization": f"Bearer {os.environ['SUBTOAPI_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "model": "claude-opus-4-20250514",
        "max_tokens": 1024,
        "messages": [{"role": "user", "content": "Hello from Flask"}],
    },
)
print(response.json())

This gives you per-key usage metadata, team seats, and streaming support without rewriting your Flask routes, which matters once more than one person on your team needs access to Claude from shared backend services. Check the quickstart and messages endpoint docs for the full request/response shape, and the streaming guide if you're building the /chat/stream route above against SubToAPI instead of the raw Anthropic SDK.

Production Considerations

A few things worth fixing before this goes live:

If you're deciding between managing the Anthropic SDK directly versus a hosted key-management layer, pricing is usually the deciding factor — see pricing for plan details, or sign up for a free trial to test against your existing Flask routes.

Questions

Do I need the official anthropic Python package, or can I just use requests? Either works. The SDK handles retries, typed responses, and streaming helpers for you, but a plain requests.post() call to the messages endpoint works fine if you want fewer dependencies.

How do I handle streaming in Flask without blocking workers? Use a generator function wrapped in flask.Response with stream_with_context, and run your app behind gunicorn with worker classes suited to long-lived connections (e.g., gevent or eventlet) rather than plain sync workers under heavy concurrent streaming load.

Can multiple Flask instances share one Claude API key safely? Yes, but you lose per-instance usage visibility and risk shared rate limits. Using a dedicated key per service, or a management layer like SubToAPI's dashboard with per-key usage metadata, makes debugging and cost attribution much easier.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →