How to beginner · 3 min read

How to use Claude API with Flask

Quick answer
Use the anthropic Python SDK with Flask by initializing the Anthropic client with your API key from os.environ. Create a Flask route that calls client.messages.create with your chosen Claude model and user messages, then return the AI response in your web app.

PREREQUISITES

  • Python 3.8+
  • Anthropic API key
  • pip install anthropic flask

Setup

Install the required packages and set your Anthropic API key as an environment variable.

  • Install packages: pip install anthropic flask
  • Set environment variable in your shell: export ANTHROPIC_API_KEY='your_api_key_here'
bash
pip install anthropic flask

Step by step

Create a simple Flask app that uses the Anthropic SDK to send a prompt to Claude and returns the response.

python
import os
from flask import Flask, request, jsonify
import anthropic

app = Flask(__name__)

client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

@app.route('/chat', methods=['POST'])
def chat():
    user_input = request.json.get('message', '')
    if not user_input:
        return jsonify({'error': 'No message provided'}), 400

    response = client.messages.create(
        model="claude-3-5-sonnet-20241022",
        max_tokens=500,
        system="You are a helpful assistant.",
        messages=[{"role": "user", "content": user_input}]
    )

    return jsonify({'response': response.content[0].text})

if __name__ == '__main__':
    app.run(debug=True, port=5000)
output
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

# Example POST request to http://127.0.0.1:5000/chat with JSON {"message": "Hello Claude!"}
# Response JSON: {"response": "Hello! How can I assist you today?"}

Common variations

You can customize your Flask + Claude integration by:

  • Using different Claude models like claude-3-5-haiku-20241022 for shorter responses.
  • Adding async support with asyncio and an async web framework like FastAPI.
  • Streaming responses by handling partial outputs if supported by the SDK.

Troubleshooting

  • If you get an authentication error, verify your ANTHROPIC_API_KEY environment variable is set correctly.
  • For timeout errors, increase max_tokens or check your network connection.
  • If Flask returns 400, ensure your POST request includes valid JSON with a message field.

Key Takeaways

  • Use the Anthropic SDK v0.20+ with Flask by importing and initializing the client with your API key from environment variables.
  • Create a Flask POST endpoint that sends user input to Claude using client.messages.create and returns the AI's response.
  • Customize your integration by switching Claude models or adopting async frameworks like FastAPI for better performance.
  • Always handle errors such as missing API keys or invalid requests to ensure a robust Flask app.
Verified 2026-04 · claude-3-5-sonnet-20241022, claude-3-5-haiku-20241022
Verify ↗