The Claude API gives you direct programmatic access to Anthropic’s models. This guide gets you from zero to a working integration in under an hour.

Prerequisites

  • Python 3.8+ or Node.js 18+
  • Anthropic API key (sign up at console.anthropic.com)
  • Basic programming knowledge

Step 1: Get Your API Key

  1. Go to console.anthropic.com
  2. Sign up or log in
  3. Navigate to API Keys → Create Key
  4. Copy and save your key securely

Set it as an environment variable:

export ANTHROPIC_API_KEY='your-key-here'

Or add to .env file:

ANTHROPIC_API_KEY=your-key-here

Step 2: Install the SDK

Python

pip install anthropic

Node.js

npm install @anthropic-ai/sdk

Step 3: Your First API Call

Python

import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-haiku-4-5-20251001",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "What is the capital of France?"}
    ]
)

print(message.content[0].text)

Node.js

import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic();

const message = await client.messages.create({
  model: 'claude-haiku-4-5-20251001',
  max_tokens: 1024,
  messages: [
    { role: 'user', content: 'What is the capital of France?' }
  ],
});

console.log(message.content[0].text);

Model Selection

ModelUse CaseCost
claude-haiku-4-5-20251001Fast, high-volume tasksCheapest
claude-sonnet-4-6Balanced capability/costMid
claude-opus-4-7Complex reasoningPremium

For most applications: start with Haiku and upgrade only when quality is insufficient.


System Prompts

System prompts define your AI assistant’s behavior:

message = client.messages.create(
    model="claude-haiku-4-5-20251001",
    max_tokens=1024,
    system="You are a helpful customer support agent for Acme Corp. \
            Be concise, friendly, and professional. \
            If you don't know something, say so and offer to escalate.",
    messages=[
        {"role": "user", "content": "How do I reset my password?"}
    ]
)

Multi-Turn Conversations

Build conversation history by appending to the messages array:

def chat(conversation_history, user_message):
    conversation_history.append({
        "role": "user",
        "content": user_message
    })
    
    response = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=1024,
        system="You are a helpful assistant.",
        messages=conversation_history
    )
    
    assistant_message = response.content[0].text
    conversation_history.append({
        "role": "assistant",
        "content": assistant_message
    })
    
    return assistant_message, conversation_history

# Usage
history = []
response, history = chat(history, "Hi! What can you help me with?")
print(response)

response, history = chat(history, "Can you help me write a Python function?")
print(response)

Structured Output

Get JSON responses by instructing the model:

import json

response = client.messages.create(
    model="claude-haiku-4-5-20251001",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": """Extract the following from this text and return as JSON:
        
Text: "John Smith, age 34, lives in Seattle and works as a software engineer at TechCorp."

Return only valid JSON with these fields:
{
  "name": "",
  "age": 0,
  "city": "",
  "job_title": "",
  "company": ""
}"""
    }]
)

data = json.loads(response.content[0].text)
print(data["name"])  # "John Smith"

Tool Use (Function Calling)

Allow Claude to call functions in your application:

tools = [
    {
        "name": "get_weather",
        "description": "Get current weather for a city",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "City name"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "Temperature unit"
                }
            },
            "required": ["city"]
        }
    }
]

response = client.messages.create(
    model="claude-haiku-4-5-20251001",
    max_tokens=1024,
    tools=tools,
    messages=[{
        "role": "user",
        "content": "What's the weather like in Tokyo?"
    }]
)

# Check if Claude wants to call a tool
if response.stop_reason == "tool_use":
    tool_call = response.content[1]  # ToolUseBlock
    tool_name = tool_call.name
    tool_input = tool_call.input
    
    # Execute your actual function
    weather_result = get_weather(tool_input["city"])
    
    # Return result to Claude
    final_response = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=1024,
        tools=tools,
        messages=[
            {"role": "user", "content": "What's the weather in Tokyo?"},
            {"role": "assistant", "content": response.content},
            {
                "role": "user",
                "content": [{
                    "type": "tool_result",
                    "tool_use_id": tool_call.id,
                    "content": str(weather_result)
                }]
            }
        ]
    )
    print(final_response.content[0].text)

Streaming Responses

Show output as it’s generated:

with client.messages.stream(
    model="claude-haiku-4-5-20251001",
    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)

Error Handling

from anthropic import APIError, APIConnectionError, RateLimitError

try:
    response = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=1024,
        messages=[{"role": "user", "content": "Hello"}]
    )
except RateLimitError:
    print("Rate limit hit — implement exponential backoff")
except APIConnectionError:
    print("Network error — retry with backoff")
except APIError as e:
    print(f"API error: {e.status_code} - {e.message}")

Cost Management

Track usage from the response object:

response = client.messages.create(...)

input_tokens = response.usage.input_tokens
output_tokens = response.usage.output_tokens

# Haiku pricing (approximate)
cost = (input_tokens * 0.25 + output_tokens * 1.25) / 1_000_000
print(f"Request cost: ${cost:.6f}")

Next Steps

  1. Prompting guide: Anthropic’s docs at docs.anthropic.com
  2. Extended thinking: Enable for complex reasoning tasks
  3. Computer use: Automate browser and desktop interactions
  4. Vision: Pass images via the content array with image type
  5. Rate limits: Review your tier’s limits and implement retry logic

The Claude API documentation at docs.anthropic.com covers all advanced features with up-to-date examples.