📝 LLM & AI

Anthropic SDK: Getting Started with the Claude API

0
Author
04e5cc8b-58ac-4bdc-bdee-661bbb
📅
Published
04.06.2026
⏱️
Reading time
1 min
👁️
Views
16
🌱
Level
Beginner

Anthropic Python SDK is the official library for working with Claude. It hides the complexity of raw HTTP requests, adds type annotations, and automatically handles transient network errors.

Installation

uv add anthropic

Creating a Client

import anthropic

# Passing the key explicitly:
client = anthropic.Anthropic(api_key="sk-ant-api03-...")

# Or the SDK reads ANTHROPIC_API_KEY from the environment automatically:
client = anthropic.Anthropic()

Your First Request

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Hi! Explain what an API is."}
    ]
)

print(message.content[0].text)

The response text lives in message.content[0].text — not in message.text. This is intentional: Claude can return multiple content blocks (text, tool calls, JSON), so content is a list.

Request Structure

client.messages.create(
    model="claude-sonnet-4-6",   # required
    max_tokens=1024,             # required
    system="You are a Python tutor.", # optional — sets the role
    temperature=0.7,             # optional — 0.0–1.0
    messages=[                   # required
        {"role": "user", "content": "First question"},
        {"role": "assistant", "content": "First answer"},
        {"role": "user", "content": "Second question"},
    ]
)

Roles in messages must alternate: userassistantuser → …

Response Structure

message.id                      # unique request ID
message.model                   # model that responded
message.stop_reason             # "end_turn" or "max_tokens"
message.content[0].text         # response text
message.usage.input_tokens      # request tokens (billing)
message.usage.output_tokens     # response tokens (billing)

Available Models (2026)

Model Use Case
claude-haiku-4-5 Simple tasks, high traffic
claude-sonnet-4-6 Most tasks — optimal balance
claude-opus-4-7 Complex tasks, deep analysis

Error Handling

try:
    message = client.messages.create(...)
except anthropic.AuthenticationError:
    print("Invalid API key. Check your .env")
except anthropic.RateLimitError:
    print("Rate limit exceeded — wait a moment")
except anthropic.APIConnectionError:
    print("No connection to the Anthropic API")
except anthropic.APIStatusError as e:
    print(f"API error {e.status_code}: {e.message}")

Automatic Retries

The SDK automatically retries on 429 Too Many Requests and 5xx Server Error:

# Configure retry behavior:
client = anthropic.Anthropic(
    api_key=API_KEY,
    max_retries=3,      # default is 2
    timeout=30.0,       # timeout in seconds
)

Messages API vs Legacy API

client.messages.create() is the Messages API — the current way to work with Claude. The old completions API is deprecated and does not support new features (tool use, streaming, vision).

Always use the Messages API.

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

Streaming LLM Responses: Getting the Answer Piece…

By default, messages.create() waits until the model has fully generated its response before returning anything....

📅 04.06.2026 👁️ 17
📝

uv: The Modern Python Package Manager

uv is a next-generation tool for managing Python dependencies. Written in Rust by Astral, it...

📅 04.06.2026 👁️ 16
📝

System Prompts: Defining the Model's Role

A system prompt is a hidden instruction for the model set by the developer. The...

📅 04.06.2026 👁️ 13

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!