Integrating the Claude API into your own application
Integrating the Claude API into your own application
This article explains how to integrate Anthropic's Claude API into your own application, including authentication, request handling, and error handling. Aimed at developers working with Python 3.9+ or Node.js 18+.
Requirements
- An Anthropic account with API access. Go to [console.anthropic.com](https://console.anthropic.com) to create your API key. - Python 3.9 or higher, or Node.js 18 or higher. - The `anthropic` SDK. Install it with pip or npm. - Basic knowledge of REST APIs and JSON.
Steps
1. Install the Anthropic SDK
For Python:
pip install anthropic==0.40.0
For Node.js:
npm install @anthropic-ai/sdk@0.32.1
The SDK version is important. Check the [Anthropic changelog](https://github.com/anthropics/anthropic-sdk-python/releases) for the latest version.
2. Set your API key as an environment variable
Do not store your API key in code. Use an environment variable.
export ANTHROPIC_API_KEY="sk-ant-..."
On Windows (PowerShell):
$env:ANTHROPIC_API_KEY="sk-ant-..."
3. Initialize the client
Python:
from anthropic import Anthropic</p><p>client = Anthropic()
The client automatically reads the `ANTHROPIC_API_KEY` environment variable. You can also pass the key explicitly:
client = Anthropic(api_key="sk-ant-...")
Node.js:
const Anthropic = require('@anthropic-ai/sdk');
const client = new Anthropic();4. Make your first API call
Python:
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[
{"role": "user", "content": "Explain in one sentence what an API is."}
]
)</p><p>print(response.content[0].text)Node.js:
async function main() {
const response = await client.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1024,
messages: [
{ role: "user", content: "Explain in one sentence what an API is." }
]
});
console.log(response.content[0].text);
}</p><p>main();5. Add system prompts and parameters
You can control the model's behavior with a `system` prompt and parameters like `temperature`.
Python:
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
temperature=0.7,
system="You are a helpful assistant that always answers in English.",
messages=[
{"role": "user", "content": "What is the capital of France?"}
]
)6. Handle streaming responses
For long responses, use streaming. This provides a better user experience.
Python:
with client.messages.stream(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[
{"role": "user", "content": "Write a short poem about the sea."}
]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)7. Implement error handling
The SDK throws exceptions on errors. Catch and log them.
Python:
from anthropic import APIError, APIStatusError, APIConnectionError</p><p>try:
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}]
)
except APIConnectionError as e:
print("Server could not be reached")
print(e.__cause__)
except APIStatusError as e:
print("Status code:", e.status_code)
print("Response:", e.response)
except APIError as e:
print("API error:", e)8. Manage rate limits
Anthropic enforces rate limits per account. The SDK automatically retries on rate limit errors, but you can configure the number of retries.
Python:
from anthropic import Anthropic</p><p>client = Anthropic(
max_retries=3, default is 2
timeout=60.0, timeout in seconds
)Verification
Check whether your integration works with a minimal test. The response should contain a `content` array with a `text` field.
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=10,
messages=[{"role": "user", "content": "Say 'ok'"}]
)</p><p>assert response.content[0].text == "ok"
print("API integration works correctly")You can also inspect the response:
print(response.model) claude-3-5-sonnet-20241022
print(response.stop_reason) end_turn
print(response.usage) input_tokens and output_tokensCommon issues
1. AuthenticationError: invalid x-api-key
Your API key is incorrect or not set. Check whether the environment variable is correct:
echo $ANTHROPIC_API_KEY
If the key is empty, set it again. Also check whether your key is still active in the Anthropic console.
2. Model not found
You are using a model name that does not exist or is not available for your account. Check the available models in the [Anthropic docs](https://docs.anthropic.com/en/docs/about-claude/models). The model name must match exactly, including the date suffix.
3. Rate limit errors (429)
You are exceeding the number of requests per minute. Increase the number of retries in the client configuration:
client = Anthropic(max_retries=5)
Consider batching requests or implementing a queue for production environments.
The integration is now complete. You have a working connection with the Claude API, including streaming, error handling, and rate limit management. The next step is building a robust application layer that processes these API calls — but those choices depend on your specific use case and architecture.