API Beginner easy · 3 min

response.content[0].text: extracting the response

What you will learn
Extract the actual text response from Claude's API response object by accessing the first content block's text property.

Why this matters

Claude's API wraps the response in a structured object. Without knowing to access <code>response.content[0].text</code>, you'll get a Message object instead of the string you need, breaking downstream processing.

Skip if: If you're using streaming mode (<code>stream=True</code>), you won't access <code>response.content[0].text</code> at all: you'll iterate over event chunks instead. Also, if you need metadata like token usage or stop reason, you might access other fields on the response object directly.

Explanation

What it does: The client.messages.create() method returns a Message object, not a plain string. This object contains the text response in a nested structure: content (a list of content blocks) → index [0] (first block) → .text (the actual string). How it works: Anthropic structures responses as a list of content blocks to support multimodal responses and future extensibility. Even for text-only requests, the response is wrapped in this object model. The first block is typically a TextBlock with a text attribute containing the model's output. When to use it: Every time you call messages.create() without streaming, you'll extract the text this way. It's the standard, non-negotiable step before using the response in your application logic.

Request code

python
from anthropic import Anthropic
import os

client = Anthropic(api_key=os.environ.get('ANTHROPIC_API_KEY'))

message = client.messages.create(
    model='claude-opus-4-6',
    max_tokens=1024,
    messages=[
        {'role': 'user', 'content': 'Explain quantum entanglement in one sentence.'}
    ]
)

response_text = message.content[0].text
print(response_text)

Authentication

Set ANTHROPIC_API_KEY environment variable before importing: export ANTHROPIC_API_KEY='sk-ant-...'. The Anthropic SDK reads this automatically at client instantiation.

Response shape

FieldDescription
content List of content blocks; typically contains one TextBlock for text-only responses
content[0] First (and usually only) content block
content[0].text String containing the model's response
content[0].type Always 'text' for text responses
model The model ID that generated the response (e.g., 'claude-opus-4-6')
usage.input_tokens Number of tokens in the prompt
usage.output_tokens Number of tokens in the response
stop_reason Why the model stopped generating ('end_turn', 'max_tokens', etc.)

Field guide

content[0].text

The actual response string you display to users or process downstream

usage.output_tokens

Critical for cost calculations: each output token costs money; track this if billing surprises you

stop_reason

Hidden field: tells you if the model hit max_tokens (response was cut off) vs. naturally stopped. Ignored by many developers but essential for quality assurance

model

Confirms which model version actually processed your request; useful when load-balancing across multiple models

Setup trap

If you import Anthropic before setting the environment variable, the client will still be initialized but with a missing API key, causing a 401 Unauthorized error only when you actually call messages.create(). Set ANTHROPIC_API_KEY in your shell or .env file before running your Python script, not inside Python code after import.

Cost

Each output token costs ~$0.015 per 1M tokens for Claude Opus. The <code>usage.output_tokens</code> field tells you exactly how many tokens the response consumed. Multiply by your model's per-token rate. Missing this field in logging will make cost analysis impossible at scale.

Rate limits

Anthropic rate limits are typically 10,000 requests/minute for most tiers. If you're calling <code>messages.create()</code> in a tight loop on user input, implement exponential backoff on 429 errors.

Common gotcha

Accessing message.text instead of message.content[0].text will fail silently or raise an AttributeError. The Message object doesn't have a .text attribute at the root level: you must index into content first. This is the #1 copy-paste error from old OpenAI SDK patterns.

Error recovery

AuthenticationError
ANTHROPIC_API_KEY is missing, invalid, or expired. Regenerate your API key in the Anthropic console and update your environment variable.
IndexError: list index out of range
This happens if you access <code>response.content[0]</code> when content is empty (extremely rare). Check that your prompt isn't triggering safety filtering; add error handling with a try-except block.
AttributeError: 'Message' object has no attribute 'text'
You're accessing <code>response.text</code> instead of <code>response.content[0].text</code>. This is the OpenAI SDK pattern: Anthropic wraps it differently.

Experienced dev note

Always log message.usage.output_tokens alongside the response text, even in development. Cost analysis is impossible without this data, and by the time you realize you need it, you've already burned budget on unmeasured requests. Also, check stop_reason in your monitoring: if it's frequently 'max_tokens', your responses are getting truncated and you should increase max_tokens or reduce prompt complexity.

Check your understanding

If you set max_tokens=10 and the model's response would normally be 100 tokens, what will response.content[0].text contain, and how would you detect that the response was incomplete?

Show answer hint

The response will contain a truncated string (only ~10 tokens worth), and <code>response.stop_reason</code> will equal 'max_tokens' instead of 'end_turn'. Always check stop_reason to detect truncation.

VERSION In anthropic 0.94.x (current as of April 2026), the Messages API is the only supported approach. The older Completions API (pre-0.1.0) is fully removed. Always use client.messages.create(), never client.completions.create().

Community Notes

No notes yetBe the first to share a version-specific fix or tip.