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 | 200K context |
Get Claude API Access
Register at APIMaster.ai to get a Claude API key that works worldwide, with discounted pricing and fingerprint-verified authentic models.
See also: Claude API Pricing · How to Get a Claude API Key