Skip to main content
โšก Calmops

Claude API Complete Guide 2026: Building with Anthropic Claude

Introduction

Anthropic’s Claude has emerged as one of the leading large language models, known for its strong reasoning capabilities, safety features, and versatility. This comprehensive guide covers everything you need to know to integrate Claude API into your applications, from basic setup to advanced production patterns.


Getting Started with Claude API

Installation

pip install anthropic

Basic Client Setup

from anthropic import Anthropic

client = Anthropic(
    api_key="sk-ant-api03-..."
)

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Hello, Claude!"}
    ]
)

print(response.content[0].text)

Understanding Claude Models

Model Best For Context Window Speed
Claude Opus Complex reasoning, analysis 200K Slow
Claude Sonnet Balanced tasks 200K Medium
Claude Haiku Fast, simple tasks 200K Fast

Claude API Fundamentals

Message API

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=2048,
    messages=[
        {
            "role": "user",
            "content": "Explain quantum computing in simple terms"
        }
    ],
    system="You are a helpful science educator.",
    temperature=0.7,
    top_p=0.9
)

# Access the response
for content_block in response.content:
    if hasattr(content_block, 'text'):
        print(content_block.text)

Streaming Responses

with client.messages.stream(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Write a story about a robot"}
    ]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

Advanced Claude API Usage

Multi-turn Conversations

messages = [
    {"role": "user", "content": "What is Python?"},
    {"role": "assistant", "content": "Python is a high-level programming language..."},
    {"role": "user", "content": "What are its main features?"}
]

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=messages
)

System Prompts

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Help me with coding"}
    ],
    system="""You are an expert Python developer.
    Always provide well-commented code.
    Include error handling in your examples."""
)

Function Calling with Claude

Tool Definitions

from anthropic import Anthropic

client = Anthropic(api_key="sk-ant-api03-...")

tools = [
    {
        "name": "get_weather",
        "description": "Get current weather for a location",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City name"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "default": "fahrenheit"
                }
            },
            "required": ["location"]
        }
    },
    {
        "name": "calculate",
        "description": "Perform mathematical calculations",
        "input_schema": {
            "type": "object",
            "properties": {
                "expression": {
                    "type": "string",
                    "description": "Mathematical expression to evaluate"
                }
            },
            "required": ["expression"]
        }
    }
]

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

# Check for tool use
if response.stop_reason == "tool_use":
    tool_use = response.content[-1]
    print(f"Tool: {tool_use.name}")
    print(f"Input: {tool_use.input}")

Claude Vision API

Image Analysis

import base64

# Encode image
with open("image.jpg", "rb") as f:
    image_data = base64.b64encode(f.read()).decode()

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": "image/jpeg",
                        "data": image_data
                    }
                },
                {
                    "type": "text",
                    "text": "What's in this image?"
                }
            ]
        }
    ]
)

print(response.content[0].text)

Best Practices

1. Error Handling

from anthropic import APIError, RateLimitError

try:
    response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=1024,
        messages=[{"role": "user", "content": "Hello"}]
    )
except RateLimitError:
    print("Rate limited. Wait before retrying.")
except APIError as e:
    print(f"API error: {e}")

2. Cost Optimization

# Use appropriate models
# Haiku: Fast, cheap for simple tasks
# Sonnet: Balanced for most tasks
# Opus: Complex reasoning only

response = client.messages.create(
    model="claude-haiku-3-20250619",  # Use cheaper model
    max_tokens=256,  # Limit output
    messages=[{"role": "user", "content": "Simple question?"}]
)

External Resources


Conclusion

Claude API provides a powerful, safe, and versatile way to integrate AI into your applications. With strong reasoning, function calling, and vision capabilities, Claude is excellent for production AI systems.

Comments