Claude · The messages API: your first real calls
The chat window is where you learned Claude. The Messages APIAPIApplication Programming Interface: a standardised interface that lets applications communicate and exchange data without knowing each other's internal workings.View full definition → is where you put it to work: the same model with no UI. You send a structured request, you get back structured output, and you do it from your own code, on your own schedule, inside your own product.
You have made a generic "first API call" before, so this lesson skips the ceremony and covers what is specific to Claude: how the request is shaped, why the system prompt sits where it does, how to get reliable formats, and how to stream long answers so your users are not staring at a blank screen.
The shape of a Claude request
Every call to the Messages API is built from a few parts:
model: which Claude you want (a Sonnet, Opus, or Haiku variant). Sonnet is the everyday workhorse, Opus is the most capable for hard reasoning, and Haiku is the fast, cheap one.max_tokens: the ceiling on how many tokenstokensA token is the basic unit of text that language models process, often a word fragment, whole word, or punctuation mark rather than a single character.View full definition → Claude may generate in its reply. This is an upper bound, not a target. It does not pad the response, it only caps it.messages: the conversation, as a list of turns. Each turn has arole(userorassistant) andcontent.system(optional but important): a top-level parameter, separate from the messages list. Role, tone, and rules go here.
That last point trips up people coming from other APIs. In the Messages API, the system promptsystem promptThe hidden set of instructions that defines how an AI assistant behaves before any user types a question: its role, tone, limits and rules.View full definition → is not a message with role: "system". It is its own field on the request. Anthropic models are trained around this structure, and keeping standing instructions in system rather than stuffing them into a user turn makes Claude follow them more reliably.
A token, as a reminder, is the chunk of text the model reads and writes in (roughly a few characters). You pay per token in and per token out, so max_tokens is also a cost control.
Your first real call
Here is a complete, runnable call. Install the SDK with pip install anthropic and set your key as the ANTHROPIC_API_KEY environment variable first.
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
system="You are a precise release-notes editor. Reply in tight bullet points.",
messages=[
{
"role": "user",
"content": "Summarize: we shipped SSO, fixed a billing bug, and removed the legacy export.",
}
],
)
print(response.content[0].text)Now look at what comes back. The response is an object, not a raw string. Its content is a list of content blocks, because a single reply can contain more than one kind of block (text, and later, tool-use requests). For a plain text answer you read response.content[0].text. You also get response.usage with input and output token counts, and response.stop_reason, which tells you *why* Claude stopped. end_turn means it finished naturally. max_tokens means it hit your ceiling and got cut off. Always check stop_reason in production, because a truncated answer that you treated as complete is a silent bug.
Model IDs roll forward over time, so check the current names and parameters in the official Messages API reference before you ship.
The conversation is yours to carry
The API is stateless. Claude does not remember your last call. *You* hold the conversation by appending each turn to the messages list and sending the whole thing back.
A multi-turn exchange is just a list:
messages = [
{"role": "user", "content": "What's a good index for a time-series table?"},
{"role": "assistant", "content": "Start with a composite index on (device_id, ts)."},
{"role": "user", "content": "Why that order and not (ts, device_id)?"},
]Keep turns alternating between user and assistant. If you send two user turns in a row, the API merges them into one, which works but makes your history harder to reason about. Treat the list as the real transcript and append Claude's reply after every call.
Getting a reliable format
Older guides teach prefilling: ending the messages list on a partial assistant turn (say, {) so Claude continues from there. Do not build on it. The newest Claude models reject a prefilled final assistant turn with an error, and the technique was always a workaround.
You have better options now:
- For guaranteed JSON, use structured outputs: you pass a JSON schemaschemaA schema is the formal blueprint that defines how data is structured, named, typed, and related within a database, file, or message.View full definition → with the request and the response is constrained to match it. See the structured outputs guide for the exact parameter.
- For lighter format control, state the format in
system("Reply with exactly three bullets, no preamble") and show one short example. - Tool use with a defined input schema is another solid way to get typed fields back, covered later in this module.
Streaming for long replies
When Claude is writing a long answer, you do not want to wait for the entire thing before showing anything. Streaming sends the response back in pieces as they are generated, so text appears word by word, the way it does in the Claude app.
Swap one method and iterate:
with client.messages.stream(
model="claude-sonnet-4-6",
max_tokens=2048,
system="You are a technical writer. Be concrete.",
messages=[{"role": "user", "content": "Explain database connection pooling."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final = stream.get_final_message()
print("\n\nTokens used:", final.usage.output_tokens)The stream() method returns a context manager (the with block), which closes the connection cleanly even if something fails mid-stream. The text_stream helper hands you only the text deltas, which is what you usually want for a UI. When the loop ends, get_final_message() reassembles the complete response so you still get usage and stop_reason.
Stream whenever a reply might be long or a human is watching it arrive. For short background jobs where nothing is waiting on the output, the plain create() call is simpler and just as fast overall.
Anthropic API Crash Course
What makes this Claude
A few behaviors are worth knowing before you build on them.
System prompts carry real weight. Persistent instructions in system are followed more consistently than the same text buried in a user message. Put the durable stuff (role, output format, hard constraints) in system, and the per-request task in the user turn.
Long context is usable in practice. Claude models support large context windows, big enough for whole documents, long transcripts, or a sizable chunk of a codebase, so you can often pass source material directly instead of building retrieval for it. Prices and window sizes shift, so confirm current figures in the docs rather than memorizing them.
The same API powers tools and agents. Tool use, the connectors that the Claude apps expose, MCP servers, and the Claude Agent SDK all sit on top of this messages.create call. Tool use is additional content block types flowing through the request and response shape you already know.
Knowledge check
1. In the Messages API, how should standing instructions about role, tone, and rules be provided?
2. What does the max_tokens parameter actually control?
3. According to the lesson, which Claude variant is described as the everyday workhorse?
4. Select ALL statements that are true about the required/important parts of a Claude Messages API request.
Select all the correct answers.
5. Select ALL correct statements about tokens and cost in the Messages API.
Select all the correct answers.
Reading errors and being a good client
Real calls fail sometimes. The ones you will meet first:
401(authentication): yourANTHROPIC_API_KEYis missing, wrong, or not loaded into the environment. Check that the variable is set (without printing the key itself).429(rate limit) and529(overloaded): you are sending too fast, or the service is briefly saturated. The fix is the same for both. Back off and retry.
The SDK already retries certain failures with exponential backoff, but you should still wrap calls and handle the cases the SDK gives up on:
import anthropic
client = anthropic.Anthropic()
try:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=512,
messages=[{"role": "user", "content": "One sentence on idempotency."}],
)
print(response.content[0].text)
except anthropic.RateLimitError:
print("Rate limited. Slow down and retry with backoff.")
except anthropic.APIStatusError as exc:
print(f"API error {exc.status_code}: {exc.message}")Catch RateLimitError specifically when you want custom backoff, and fall back to APIStatusError for any other non-success status. That is the difference between a script that dies on the first hiccup and a service that survives a busy afternoon.
Where to keep your keys
This one bites people on day one. Your API key is a secret with billing attached. Never hardcode it in source, never commit it, and never ship it inside a browser app where users can read it. Keep it in an environment variable or a secrets manager. The anthropic.Anthropic() constructor picks up ANTHROPIC_API_KEY with no argument, which is why every snippet above leaves it implicit. If you need browser-side calls, route them through a small backend that holds the key.
You can generate and rotate keys in the Claude Console, and the SDK source lives at github.com/anthropics if you want to read how retries and streaming are implemented.
Key Takeaways
- Put standing instructions in the top-level
systemparameter, not a user message. Reserve user turns for the actual task. - Always check
stop_reasonandusage. A reply cut off atmax_tokenslooks complete but isn't, and token counts are your cost signal. - The API is stateless, so carry the conversation yourself and keep turns alternating.
- Skip prefilling on current models. Use structured outputs when you need guaranteed JSON.
- Use
messages.stream()withtext_streamwhen a human is waiting, andcreate()for silent background jobs. - Tool use, connectors, MCPMCPAn open standard that lets AI assistants connect to your company's tools and data in a consistent, governed way, instead of one custom integration at a time.View full definition →, and the Agent SDK all flow through this same request and response shape.
What to do, from this lesson
These actions are compiled in the role's Playbook.
- Put standing instructions in the API top-level system parameter
- Always check stop_reason and usage on every API reply
- Stream replies whenever a human is waiting on output