Working with Anthropic Claude API
Anthropic's Claude models are known for long context windows, strong reasoning, and a focus on being helpful, harmless, and honest. This topic covers how to build with the Claude API.
Setting Up
1. Get API Access
Sign up at console.anthropic.com and create an API key.
export ANTHROPIC_API_KEY="sk-ant-your-key-here"2. Install the SDK
# Python
pip install anthropic
# Node.js
npm install @anthropic-ai/sdkYour First Claude API Call
Python
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{"role": "user", "content": "Explain recursion in simple terms."}
]
)
print(message.content[0].text)Node.js
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
const message = await anthropic.messages.create({
model: "claude-sonnet-4-20250514",
max_tokens: 1024,
messages: [
{ role: "user", content: "Explain recursion in simple terms." }
]
});
console.log(message.content[0].text);Claude's Message Format
Claude uses a similar messages structure to OpenAI, with one key difference — the system prompt is a separate parameter:
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
system="You are an expert Python developer. Be concise and practical.",
messages=[
{"role": "user", "content": "How do I handle errors in async Python?"},
{"role": "assistant", "content": "Use try/except within async functions..."},
{"role": "user", "content": "Show me a real-world example."}
]
)Available Models
| Model | Strengths | Context Window |
|---|---|---|
| Claude Opus 4 | Most capable, complex reasoning | 200K tokens |
| Claude Sonnet 4 | Best balance of speed and quality | 200K tokens |
| Claude Haiku 3.5 | Fastest, most affordable | 200K tokens |
Choosing the Right Model
- Haiku: Simple tasks, classification, extraction, high-volume
- Sonnet: General-purpose, code generation, analysis
- Opus: Complex reasoning, research, nuanced tasks
Key Parameters
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2048, # Required: max response tokens
system="System instructions", # Optional: system prompt
messages=[...], # Required: conversation
temperature=0.7, # Optional: 0-1 (default: 1)
top_p=0.9, # Optional: nucleus sampling
stop_sequences=["\n\nHuman:"], # Optional: stop generation
)Streaming
with client.messages.stream(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a poem about coding"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)Working with Long Documents
Claude's 200K token context window (~150K words) is ideal for processing long documents:
# Read a long document
with open("annual_report.txt") as f:
document = f.read()
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2048,
messages=[
{
"role": "user",
"content": f"""Analyze this annual report and provide:
1. Key financial highlights
2. Major risks identified
3. Strategic priorities for next year
<document>
{document}
</document>"""
}
]
)Vision (Image Understanding)
Claude can analyze images:
import base64
with open("screenshot.png", "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": image_data
}
},
{
"type": "text",
"text": "Describe what you see in this screenshot."
}
]
}
]
)Tool Use (Function Calling)
Claude can call functions you define:
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=[
{
"name": "get_weather",
"description": "Get current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name, e.g., 'London'"
}
},
"required": ["location"]
}
}
],
messages=[
{"role": "user", "content": "What's the weather in Tokyo?"}
]
)
# Check if Claude wants to use a tool
for block in message.content:
if block.type == "tool_use":
print(f"Tool: {block.name}")
print(f"Input: {block.input}")
# → Tool: get_weather
# → Input: {"location": "Tokyo"}XML Tags — Claude's Secret Weapon
Claude responds especially well to XML-structured prompts:
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2048,
messages=[
{
"role": "user",
"content": """
<context>
You are reviewing a Node.js Express application for security vulnerabilities.
The application handles payment processing.
</context>
<code>
app.post('/pay', (req, res) => {
const amount = req.body.amount;
const query = `UPDATE accounts SET balance = balance - ${amount}`;
db.execute(query);
res.json({ success: true });
});
</code>
<task>
Identify all security vulnerabilities and provide fixed code.
</task>
"""
}
]
)Error Handling
import anthropic
client = anthropic.Anthropic()
try:
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}]
)
except anthropic.RateLimitError:
print("Rate limited — implement backoff")
except anthropic.APIConnectionError:
print("Connection failed — check network")
except anthropic.APIStatusError as e:
print(f"API error: {e.status_code}")Usage Tracking
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}]
)
print(f"Input tokens: {message.usage.input_tokens}")
print(f"Output tokens: {message.usage.output_tokens}")Claude vs OpenAI: Key API Differences
| Feature | Claude | OpenAI |
|---|---|---|
| System prompt | Separate system parameter | In messages array |
| Response format | message.content[0].text | response.choices[0].message.content |
| Max tokens | Required parameter | Optional |
| Context window | 200K tokens | 4K–128K |
| Streaming | messages.stream() context manager | stream=True parameter |
| XML in prompts | Highly effective | Works but less optimized |
Best Practices for Claude
- Use XML tags — Claude handles structured XML prompts exceptionally well
- Leverage the long context — Process entire documents, codebases, or conversation histories
- Be specific in system prompts — Claude follows system instructions closely
- Use Haiku for simple tasks — Save costs on classification, extraction, routing
- Use Sonnet for code — Best balance of quality and speed for development tasks
Next, we'll explore Google's Gemini API and then compare all three providers.