Claude API Fundamentals Basics
9 examples to get you started with Claude API Fundamentals - 6 basic and 3 intermediate.
Search across all documentation pages
9 examples to get you started with Claude API Fundamentals - 6 basic and 3 intermediate.
pip install anthropic.export ANTHROPIC_API_KEY="sk-ant-...".The smallest possible call to the Messages API: one model, one prompt, one response.
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
response = client.messages.create(
model="claude-sonnet-5-20260630",
max_tokens=1024,
messages=[{"role": "user", "content": "Say hello in one sentence."}],
)
print(response.content[0].text)model and max_tokens are the only two required parameters on every call.messages is a list of turns; a single user turn is enough for a one-off prompt.response.content[0].text, not directly on response.Related: Installing and Configuring the Anthropic Python SDK - full setup walkthrough.
The response carries more than just text, it also reports how the generation ended and how many tokens were used.
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-5-20260630",
max_tokens=256,
messages=[{"role": "user", "content": "Name three prime numbers."}],
)
print("Text:", response.content[0].text)
print("Stop reason:", response.stop_reason)
print("Input tokens:", response.usage.input_tokens)
print("Output tokens:", response.usage.output_tokens)stop_reason tells you why generation stopped, commonly "end_turn" or "max_tokens".usage.input_tokens and usage.output_tokens are what you're billed on.stop_reason of "max_tokens" means the reply was cut off, raise max_tokens if you need more.max_tokens is a hard ceiling on how much Claude can generate, not a target length.
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-haiku-4-5-20260601",
max_tokens=50,
messages=[{"role": "user", "content": "Explain photosynthesis."}],
)
print(response.content[0].text)
print(response.stop_reason) # likely "max_tokens" - the explanation was cut offmax_tokens is reached, mid-sentence if necessary.max_tokens generously for tasks with unpredictable output length, like summaries or code.max_tokens is a common source of truncated, unusable responses.temperature controls how deterministic or varied the output is.
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-5-20260630",
max_tokens=100,
temperature=0.0, # near-deterministic, good for factual/structured tasks
messages=[{"role": "user", "content": "What is the capital of Japan?"}],
)
print(response.content[0].text)temperature (near 0) gives consistent, repeatable answers, best for facts, classification, and code.temperature (closer to 1) gives more varied, creative phrasing, better for brainstorming.temperature and top_p both affect randomness; most calls only need one of them adjusted.A system parameter sets persistent instructions that apply across the whole conversation.
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-5-20260630",
max_tokens=200,
system="You are a terse code reviewer. Reply in bullet points only.",
messages=[{"role": "user", "content": "Review this function: def add(a,b): return a+b"}],
)
print(response.content[0].text)system is a top-level parameter, separate from the messages list.Wrap calls in a try/except to handle invalid requests or authentication problems gracefully.
import anthropic
client = anthropic.Anthropic()
try:
response = client.messages.create(
model="claude-sonnet-5-20260630",
max_tokens=100,
messages=[{"role": "user", "content": "Hello!"}],
)
print(response.content[0].text)
except anthropic.AuthenticationError:
print("Check that ANTHROPIC_API_KEY is set correctly.")
except anthropic.APIStatusError as e:
print(f"API returned an error: {e.status_code} - {e.message}")anthropic.AuthenticationError covers 401-style key problems specifically.anthropic.APIStatusError is the base class for other non-2xx responses, useful as a catch-all.Exception, it tells you what actually went wrong.Related: Claude API Error Codes and Troubleshooting Reference - full error catalog.
Since the API is stateless, you resend prior turns yourself to maintain context.
import anthropic
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "My favorite color is teal."}]
first = client.messages.create(
model="claude-sonnet-5-20260630",
max_tokens=100,
messages=messages,
)
print("Claude:", first.content[0].text)
# Append Claude's reply, then the next user turn, before calling again.
messages.append({"role": "assistant", "content": first.content[0].text})
messages.append({"role": "user", "content": "What's my favorite color?"})
second = client.messages.create(
model="claude-sonnet-5-20260630",
max_tokens=100,
messages=messages,
)
print("Claude:", second.content[0].text)"user" and "assistant"; the list must start with a "user" turn.Real applications usually tune several parameters together for a specific task.
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-8-20260415",
max_tokens=500,
system="You are a precise technical writer. Avoid speculation.",
temperature=0.2,
top_p=0.9,
messages=[{"role": "user", "content": "Draft a one-paragraph changelog entry for a new retry option."}],
)
print(response.content[0].text)temperature paired with a focused system prompt suits precise, low-variance writing tasks.top_p further narrows the sampling pool; adjust temperature or top_p, not usually both aggressively at once.claude-opus-4-8 here reflects a task that benefits from stronger reasoning than a lighter model.Related: Selecting a Model: Claude Fable 5, Opus 4.8, Sonnet 5, and Haiku 4.5 - how to choose between models.
max_retries on the client handles transient 429/5xx errors automatically with backoff.
import anthropic
client = anthropic.Anthropic(max_retries=3) # retries 429s and 5xxs with exponential backoff
response = client.messages.create(
model="claude-haiku-4-5-20260601",
max_tokens=200,
messages=[{"role": "user", "content": "Summarize this in one sentence: the sky is blue due to Rayleigh scattering."}],
)
print(response.content[0].text)max_retries is a client-level constructor option, not a per-call parameter.429, 5xx); it does not retry 400-class validation errors.claude-haiku-4-5 for simple summarization keeps cost and latency low.Related: Handling Rate Limits with Exponential Backoff - retry strategy in depth.
Stack versions: Written against the Claude model lineup current as of ~June 2026 - Claude Fable 5, Claude Opus 4.8, Claude Sonnet 5 (the default), and Claude Haiku 4.5 - and the official
anthropicPython SDK (latest 0.x release). Model names, SDK versions, and pricing move quickly - verify current specifics at platform.claude.com/docs before relying on them.
Reviewed by Chris St. John·Last updated Jul 18, 2026