Claude API Fundamentals Basics
9 examples to get you started with Claude API Fundamentals - 6 basic and 3 intermediate.
Prerequisites
- Install the official SDK:
pip install anthropic. - Set your API key as an environment variable:
export ANTHROPIC_API_KEY="sk-ant-...". - Python 3.8 or newer.
Basic Examples
1. Your First Message
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)modelandmax_tokensare the only two required parameters on every call.messagesis a list of turns; a single user turn is enough for a one-off prompt.- The response text lives at
response.content[0].text, not directly onresponse.
Related: Installing and Configuring the Anthropic Python SDK - full setup walkthrough.
2. Reading the Full Response Object
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_reasontells you why generation stopped, commonly"end_turn"or"max_tokens".usage.input_tokensandusage.output_tokensare what you're billed on.- A
stop_reasonof"max_tokens"means the reply was cut off, raisemax_tokensif you need more.
3. Controlling max_tokens
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 off- Generation stops the moment
max_tokensis reached, mid-sentence if necessary. - Set
max_tokensgenerously for tasks with unpredictable output length, like summaries or code. - A too-low
max_tokensis a common source of truncated, unusable responses.
4. Adjusting temperature for Randomness
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)- Lower
temperature(near 0) gives consistent, repeatable answers, best for facts, classification, and code. - Higher
temperature(closer to 1) gives more varied, creative phrasing, better for brainstorming. temperatureandtop_pboth affect randomness; most calls only need one of them adjusted.
5. Using a System Prompt
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)systemis a top-level parameter, separate from themessageslist.- It shapes tone, role, and constraints without consuming a "turn" in the conversation.
- Keep system prompts focused; long, vague system prompts weaken instruction-following.
6. Handling a Basic Error
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.AuthenticationErrorcovers401-style key problems specifically.anthropic.APIStatusErroris the base class for other non-2xx responses, useful as a catch-all.- Catching specific exception types beats catching bare
Exception, it tells you what actually went wrong.
Related: Claude API Error Codes and Troubleshooting Reference - full error catalog.
Intermediate Examples
7. A Multi-Turn Conversation
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)- Each call resends the full history; there is no server-side session to reference.
- Roles alternate
"user"and"assistant"; the list must start with a"user"turn. - Longer histories mean more input tokens billed per call, this is a real cost, not just a formality.
8. Combining System Prompt, temperature, and top_p
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)- A low
temperaturepaired with a focusedsystemprompt suits precise, low-variance writing tasks. top_pfurther narrows the sampling pool; adjusttemperatureortop_p, not usually both aggressively at once.- Choosing
claude-opus-4-8here 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.
9. Basic Retry on Rate Limits
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_retriesis a client-level constructor option, not a per-call parameter.- The SDK only retries genuinely transient errors (
429,5xx); it does not retry400-class validation errors. - Choosing a cheap, fast model like
claude-haiku-4-5for 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.