APIMaster.ai

Claude API Python Tutorial 2026 | APIMaster.ai

How to use the Claude API with Python. Complete examples using the Anthropic SDK and OpenAI-compatible client—chat, streaming, vision, and function calling—via APIMaster.ai.

Claude API Python Tutorial

This guide covers using the Claude API in Python with both the native Anthropic SDK and the OpenAI-compatible client. All examples work with APIMaster.ai—swap in your own base URL and API key.

Installation

pip install anthropic          # Native Anthropic SDK
pip install openai             # OpenAI-compatible (optional)

Basic Setup

import anthropic

client = anthropic.Anthropic(
    api_key="YOUR_APIMASTER_KEY",
    base_url="https://apimaster.ai",  # No /v1 for Anthropic SDK
)

Or with OpenAI SDK (easier if you already use OpenAI):

from openai import OpenAI

client = OpenAI(
    api_key="YOUR_APIMASTER_KEY",
    base_url="https://apimaster.ai/v1",
)

Your First Claude API Call

import anthropic

client = anthropic.Anthropic(
    api_key="YOUR_APIMASTER_KEY",
    base_url="https://apimaster.ai",
)

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Explain the difference between lists and tuples in Python."}
    ],
)

print(message.content[0].text)

System Prompts

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=512,
    system="You are a senior Python engineer. Be concise and use code examples.",
    messages=[
        {"role": "user", "content": "What's the fastest way to flatten a nested list?"}
    ],
)
print(response.content[0].text)

Multi-Turn Conversation

conversation = []

def chat(user_message):
    conversation.append({"role": "user", "content": user_message})
    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        messages=conversation,
    )
    assistant_message = response.content[0].text
    conversation.append({"role": "assistant", "content": assistant_message})
    return assistant_message

print(chat("What is a decorator in Python?"))
print(chat("Can you show me a practical example?"))

Streaming Responses

Streaming returns tokens as they're generated—better UX for long outputs:

with client.messages.stream(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Write a Python web scraper using requests and BeautifulSoup."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
print()  # newline at end

Vision: Analyzing Images

Claude Sonnet and Opus support image inputs (base64 or URL):

import base64

with open("chart.png", "rb") as f:
    image_data = base64.standard_b64encode(f.read()).decode("utf-8")

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=512,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": "image/png",
                        "data": image_data,
                    },
                },
                {"type": "text", "text": "Summarize what this chart shows."},
            ],
        }
    ],
)
print(response.content[0].text)

Tool Use (Function Calling)

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

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

# Check if Claude wants to call a tool
if response.stop_reason == "tool_use":
    tool_call = next(b for b in response.content if b.type == "tool_use")
    print(f"Tool: {tool_call.name}, Input: {tool_call.input}")

Async Usage

import asyncio
import anthropic

async def main():
    client = anthropic.AsyncAnthropic(
        api_key="YOUR_APIMASTER_KEY",
        base_url="https://apimaster.ai",
    )
    response = await client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=256,
        messages=[{"role": "user", "content": "Hello!"}],
    )
    print(response.content[0].text)

asyncio.run(main())

Error Handling

import anthropic

try:
    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=256,
        messages=[{"role": "user", "content": "Hello"}],
    )
except anthropic.AuthenticationError:
    print("Invalid API key")
except anthropic.RateLimitError:
    print("Rate limit—add retry logic")
except anthropic.APIStatusError as e:
    print(f"API error {e.status_code}: {e.message}")

Choosing the Right Claude Model for Python Projects

Task Model Reason
Chatbots, Q&A claude-haiku-4-5 Fast + cheap
Code generation claude-sonnet-4-6 Best balance
Complex reasoning claude-opus-4-8 Highest accuracy
Document analysis claude-sonnet-4-6 1M context

Get Claude API Access

Frequently Asked Questions

How do I install the Claude API Python library? Run pip install anthropic for the official SDK, or pip install openai to use APIMaster's OpenAI-compatible endpoint with Claude models.

Which Python SDK should I use for Claude API? The anthropic SDK is the official choice and supports all Claude-specific features (tool use, vision, streaming). The openai SDK works via APIMaster's compatibility layer—useful if you're already using OpenAI and want to switch models.

How do I stream Claude API responses in Python? Pass stream=True with the openai library, or use client.messages.stream() with the anthropic SDK. See the streaming example above.

Does Claude API support function calling (tool use)? Yes—Claude supports tool use both in the native Anthropic SDK and through APIMaster's OpenAI-compatible endpoint using the standard tools parameter.

What is the maximum context window for Claude in Python? Claude Sonnet 4.6 and Opus 4.8 support 1M tokens each. You can pass very long documents directly in the messages array.

Register at APIMaster.ai to get Claude API access through a unified endpoint, with live pricing and fingerprint verification data.

See also: Claude API Pricing · How to Get a Claude API Key