Make Claude API calls with the Messages API

Build a Python Messages API request with conversational context, inspect text and token usage, and handle status errors.

Send the context the next turn needs

The Messages API receives the messages you include with each request. When a follow-up depends on earlier details, provide the relevant history in order. Put overall instructions in the top-level system field. Use role values user and assistant for conversation turns inside messages.

For a first text-only application, keep the submitted request short and retain only the context needed for the next turn. For application workflows that use tool calls or non-text content, preserve the corresponding typed blocks as documented.

Read a follow-up answer and its usage

Install the official Python SDK with python -m pip install anthropic and supply its API key through your approved secret manager. Save this as messages_example.py. It supplies a synthetic first turn, a prior answer, and a follow-up. A successful run should identify Maya as the owner and report the stop reason and token usage.

Code
import os
import anthropic

if not os.environ.get("ANTHROPIC_API_KEY"):
    raise SystemExit("Supply ANTHROPIC_API_KEY through your secret manager.")

client = anthropic.Anthropic()
history = [
    {"role": "user", "content": "Maya owns the release checklist and will send it Friday."},
    {"role": "assistant", "content": "The release checklist is due Friday."},
    {"role": "user", "content": "Who owns the checklist? Reply with the name only."},
]

try:
    result = client.messages.create(
        model=os.environ.get("CLAUDE_MODEL", "claude-sonnet-5-5"),
        system="Answer using the conversation history. Keep replies brief.",
        messages=history,
        max_tokens=256,
    )
except anthropic.APIStatusError as exc:
    raise SystemExit(f"Claude request failed with HTTP {exc.status_code}.") from None
except anthropic.APIConnectionError:
    raise SystemExit("Claude API connection failed.") from None

text = "".join(block.text for block in result.content if block.type == "text")
print(text.strip())
print({"stop_reason": result.stop_reason, "tokens": result.usage.output_tokens})

Handle quality and API errors separately

A successful HTTP request can still return a partial or unsuitable answer. Use the stop reason and application checks to decide what to show the user.

  • On max_tokens, label the answer as truncated or use a larger output budget for that task.
  • For 400, inspect the request body and parameter values before retrying.
  • For 429 or a temporary service error, follow the SDK and service retry guidance, cap retries, and leave the user a clear failure state if retries are exhausted.
  • For a body with several content blocks, render the block types your application supports and retain the metadata that your verification needs.

Test without a conversation database

Run the sample once against your development workspace. In your application’s tests, use stored response fixtures for successful text, truncated text, and temporary errors. Verify that each reaches the intended display state without needing a live model call.

Messages API request and response guide

Related reading

What is Claude?

Setting Up Your Account

Streaming Responses