Getting Started with the Claude API: A Practical Guide for Developers
Learn how to integrate Claude AI into your applications using the official Anthropic API. Includes Python and TypeScript examples, authentication setup, and best practices.
This guide walks you through setting up the Claude API, authenticating requests, sending your first prompt, and handling responses in Python and TypeScript. You'll learn key parameters, error handling, and practical tips for production use.
Introduction
Claude, developed by Anthropic, offers a powerful API that lets you integrate advanced AI capabilities into your own applications. Whether you're building a chatbot, content generator, code assistant, or any other AI-powered tool, the Claude API provides a reliable and flexible foundation.
This guide is designed for developers who are new to the Claude API. We'll cover everything from getting your API key to making your first successful request, with practical code examples in both Python and TypeScript.
Prerequisites
Before you start, make sure you have:
- An Anthropic account (sign up is free)
- An API key from the Anthropic Console
- Basic familiarity with REST APIs and either Python or TypeScript
- A development environment with
curl, Python 3.8+, or Node.js 18+
Step 1: Get Your API Key
- Log in to the Anthropic Console.
- Navigate to Account Settings > API Keys.
- Click Create Key and give it a descriptive name (e.g., "My App - Production").
- Copy the key immediately — you won't be able to see it again.
Step 2: Understand the API Endpoint
The Claude API uses a single primary endpoint for text generation:
POST https://api.anthropic.com/v1/messages
All requests must include:
- Header:
x-api-keywith your API key - Header:
anthropic-version(currently2023-06-01) - Body: A JSON object containing your prompt and parameters
Step 3: Make Your First API Call
Using cURL (Quick Test)
curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data '{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Hello, Claude!"}
]
}'
Using Python (with the official SDK)
First, install the Anthropic Python SDK:
pip install anthropic
Then create a simple script:
import anthropic
import os
Initialize the client
client = anthropic.Anthropic(
api_key=os.environ.get("ANTHROPIC_API_KEY")
)
Send a message
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[
{"role": "user", "content": "Explain quantum computing in one sentence."}
]
)
Print the response
print(message.content[0].text)
Using TypeScript (with the official SDK)
Install the Node.js SDK:
npm install @anthropic-ai/sdk
Then create a script:
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
async function main() {
const message = await anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'Explain quantum computing in one sentence.' }
],
});
console.log(message.content[0].text);
}
main().catch(console.error);
Step 4: Understand Key Parameters
The /v1/messages endpoint accepts several important parameters:
| Parameter | Type | Description |
|---|---|---|
model | string | The Claude model version (e.g., claude-3-5-sonnet-20241022) |
messages | array | Conversation history as an array of message objects |
max_tokens | integer | Maximum tokens in the response (1-4096 for most models) |
temperature | float | Randomness (0-1, default 0.7). Lower = more deterministic |
system | string | System prompt to set Claude's behavior |
stop_sequences | array | Strings that stop Claude from generating further |
stream | boolean | Enable streaming responses (default false) |
Example with System Prompt and Temperature
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
temperature=0.3,
system="You are a helpful coding assistant. Provide concise, working code examples.",
messages=[
{"role": "user", "content": "Write a Python function to reverse a linked list."}
]
)
Step 5: Handle Streaming Responses
For real-time applications, streaming reduces perceived latency. Here's how to stream in Python:
with client.messages.stream(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[
{"role": "user", "content": "Write a short poem about AI."}
]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
And in TypeScript:
const stream = await anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Write a short poem about AI.' }],
stream: true,
});
for await (const chunk of stream) {
if (chunk.type === 'content_block_delta') {
process.stdout.write(chunk.delta.text);
}
}
Step 6: Error Handling Best Practices
Always handle API errors gracefully. Common HTTP status codes:
- 400 — Bad request (check your parameters)
- 401 — Unauthorized (invalid API key)
- 429 — Rate limited (slow down requests)
- 500 — Server error (retry with exponential backoff)
Python Error Handling Example
import time
from anthropic import APIError, APIConnectionError, RateLimitError
def send_with_retry(client, params, max_retries=3):
for attempt in range(max_retries):
try:
return client.messages.create(**params)
except RateLimitError:
if attempt < max_retries - 1:
time.sleep(2 ** attempt) # Exponential backoff
continue
raise
except (APIError, APIConnectionError) as e:
print(f"API error: {e}")
raise
Step 7: Manage Conversation History
For multi-turn conversations, maintain the full message history:
conversation = [
{"role": "user", "content": "What is the capital of France?"},
{"role": "assistant", "content": "The capital of France is Paris."},
{"role": "user", "content": "What is its population?"}
]
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=conversation
)
Important: Claude has a context window limit (e.g., 200K tokens for Claude 3.5 Sonnet). For long conversations, you may need to truncate or summarize older messages.
Step 8: Monitor Usage and Costs
Track your API usage in the Anthropic Console under Usage. Key metrics:
- Input tokens (your prompts)
- Output tokens (Claude's responses)
- Cost per request (varies by model)
Next Steps
Now that you've made your first API call, explore more advanced features:
- Tool use — Let Claude call external functions
- Vision — Analyze images alongside text
- Batch processing — Send multiple requests efficiently
- Custom models — Fine-tune Claude for your domain
Key Takeaways
- Authentication is simple — Use your API key in the
x-api-keyheader or the official SDKs for Python and TypeScript. - The
/v1/messagesendpoint is your primary interface for text generation, supporting system prompts, conversation history, and streaming. - Always handle errors — Implement retry logic with exponential backoff for rate limits and transient failures.
- Manage context windows — Keep track of token usage and truncate conversation history when needed to stay within model limits.
- Start with the SDK — The official Anthropic SDKs handle authentication, streaming, and error handling, letting you focus on building features.