Working with AI APIs

Working with Anthropic Claude API

Learn how to use the Anthropic API to build applications with Claude — featuring long context, safety, and advanced reasoning.

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.

bash
export ANTHROPIC_API_KEY="sk-ant-your-key-here"

2. Install the SDK

bash
# Python
pip install anthropic

# Node.js
npm install @anthropic-ai/sdk

Your First Claude API Call

Python

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

javascript
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:

python
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

ModelStrengthsContext Window
Claude Opus 4Most capable, complex reasoning200K tokens
Claude Sonnet 4Best balance of speed and quality200K tokens
Claude Haiku 3.5Fastest, most affordable200K 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

python
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

python
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:

python
# 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:

python
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:

python
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:

python
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

python
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

python
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

FeatureClaudeOpenAI
System promptSeparate system parameterIn messages array
Response formatmessage.content[0].textresponse.choices[0].message.content
Max tokensRequired parameterOptional
Context window200K tokens4K–128K
Streamingmessages.stream() context managerstream=True parameter
XML in promptsHighly effectiveWorks but less optimized

Best Practices for Claude

  1. Use XML tags — Claude handles structured XML prompts exceptionally well
  2. Leverage the long context — Process entire documents, codebases, or conversation histories
  3. Be specific in system prompts — Claude follows system instructions closely
  4. Use Haiku for simple tasks — Save costs on classification, extraction, routing
  5. 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.