๐Ÿ“ LLM & AI

Anthropic SDK: Getting Started with the Claude API

P
Author
PyLand Team
๐Ÿ“…
Published
04.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
336
๐ŸŒฟ
Level
Medium

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

# The SDK reads ANTHROPIC_API_KEY from the environment:
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: user โ†’ assistant โ†’ user โ†’ …

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

๐Ÿ“

AI Agents: ReAct Loop and Autonomous Actions

A chatbot answers questions. An agent takes action: it calls tools, retrieves real data, and...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 335
๐Ÿ“

Pydantic v2: Data Validation in Python

Pydantic validates and converts data through type annotations. It is commonly used in APIs and...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 330
๐Ÿ“

asyncio in Python: Asynchronous Programming

asyncio is Python's standard library for asynchronous code. It lets you execute multiple tasks "simultaneously"...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 318
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

Neural Networks in Code: 5 AI Projects in Python with Claude Open course curriculum