Anthropic Claude API in Python
anthropic.Anthropic(), messages.create(), content blocks, extended thinking, streaming.
Anthropic Claude API in Python is a free Learn AI with Python lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn AI with Python learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The Anthropic SDK
Anthropic's Claude models are accessed through the anthropic Python package. Install with pip install anthropic. Claude excels at long-context reasoning, careful instruction following, and tool use.
pip install anthropic
import anthropicCreating the Client
Build the client with anthropic.Anthropic(). It reads your key from the ANTHROPIC_API_KEY environment variable by default, keeping credentials out of code.
import anthropic
client = anthropic.Anthropic()
# Or explicitly
client = anthropic.Anthropic(api_key="sk-ant-...")The Messages API
Claude uses client.messages.create(). Unlike OpenAI, the system prompt is a separate parameter, not a message in the list. The messages list only holds user and assistant turns.
message = client.messages.create(
model="claude-opus-4-8",
max_tokens=1024,
system="You are a concise expert.",
messages=[{"role": "user", "content": "Explain RAG in one sentence."}]
)max_tokens is Required
A key difference: max_tokens is mandatory in the Anthropic API. It caps how many tokens Claude may generate in its reply. Set it high enough for your expected output, but it also protects against runaway cost.
message = client.messages.create(
model="claude-opus-4-8",
max_tokens=2048,
messages=[{"role": "user", "content": "Write a haiku about Python."}]
)Reading the Response
Claude returns a content list of blocks. For plain text, the reply is at message.content[0].text. It is a list because a response can contain multiple blocks, such as text plus a tool-use request.
print(message.content[0].text)
# Inspect block type
print(message.content[0].type) # "text"Conversation History
Like other chat APIs, Claude is stateless. To continue a conversation, append the assistant reply and the next user turn into messages yourself.
messages = [{"role": "user", "content": "Hello"}]
resp = client.messages.create(model="claude-opus-4-8", max_tokens=512, messages=messages)
messages.append({"role": "assistant", "content": resp.content[0].text})
messages.append({"role": "user", "content": "Tell me more"})Streaming with a Context Manager
For real-time output, Claude offers client.messages.stream() used as a context manager with the with statement. This safely opens and closes the connection.
with client.messages.stream(
model="claude-opus-4-8",
max_tokens=1024,
messages=[{"role": "user", "content": "Count to five."}]
) as stream:
pass # iterate insideIterating the Text Stream
Inside the with block, loop over stream.text_stream to receive text deltas as Claude generates them. Each item is a string ready to print.
with client.messages.stream(
model="claude-opus-4-8",
max_tokens=1024,
messages=[{"role": "user", "content": "Count to five."}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)Getting the Final Message
After streaming finishes, call stream.get_final_message() to retrieve the complete assembled message object, including usage data and the full content blocks.
with client.messages.stream(model="claude-opus-4-8", max_tokens=1024,
messages=[{"role": "user", "content": "Hi"}]) as stream:
for text in stream.text_stream:
print(text, end="")
final = stream.get_final_message()Token Usage
The response carries a usage object with input_tokens and output_tokens. Note the naming differs from OpenAI (which uses prompt/completion), but the meaning is the same: track cost per call.
print(message.usage.input_tokens)
print(message.usage.output_tokens)OpenAI vs Anthropic Differences
Key contrasts to remember: Anthropic puts the system prompt in its own parameter, requires max_tokens, reads text from content[0].text, and streams via a with context manager. Knowing these lets you switch between providers confidently.
Quick Check
Test your Anthropic knowledge.
Recap: Claude in Python
You created an anthropic.Anthropic() client and called messages.create() with a required max_tokens and a separate system prompt. You read replies from content[0].text and tracked cost via usage.input_tokens / output_tokens.
For streaming you used client.messages.stream() as a with context manager, iterated text_stream, and fetched the assembled result with get_final_message().
Frequently asked questions
Is the “Anthropic Claude API in Python” lesson free?
Yes — the full text of “Anthropic Claude API in Python” is free to read here on the web, and the Learn AI with Python course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn AI with Python course, upgrade to CoddyKit PRO.
What will I learn in “Anthropic Claude API in Python”?
anthropic.Anthropic(), messages.create(), content blocks, extended thinking, streaming. You practise Learn AI with Python with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn AI with Python?
No prior experience is required. Learn AI with Python on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Anthropic Claude API in Python” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn AI with Python lesson?
Yes. Every Learn AI with Python lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.