Learning path: Build Your First LLM App with Claude · Step 2 of 4
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
What you will learn
- Build a Messages API call with model, max_tokens, system and messages
- Read a Message's content blocks, stop_reason and usage
- Keep a conversation going by resending the history on every turn
- Make the same call with the TypeScript SDK
Before you start
- Basic Python (functions, lists and dicts)
A customer on a support desk types one question: Where is my refund? Behind it there's one call to Claude, and that call has four fields. Get those four right and learn to read what comes back, and you know the Messages API.
We'll build that call in a small slice of an app called SupportDesk, then turn it into a two-turn conversation.
One request in, one Message out
Claude knows nothing about your app yet, so the call has to say four things:
- Which model should answer.
- How long the reply may be.
- What the agent's job is.
- What was said so far.
Think of a form at an advice desk with four boxes. Which adviser? That's model. The longest reply, counted in tokens? That's max_tokens. The adviser's brief? That's system. The talk so far? That's messages.
| Field | What it says | Required? |
|---|---|---|
model | Which model answers | Yes |
max_tokens | The longest reply, in tokens | Yes |
system | The agent's brief | No |
messages | The conversation so far | Yes |
One detail matters: the system prompt sits beside messages in the request, never inside it.
first_call.py
Here's the call with the official Python SDK. In the lecture's project, the client is wired to a stand-in (an httpx mock transport that answers like the Messages API), so the code runs with no API key. That's what stand_in and "test-key" are.
"""The first call: one question in, one Message out."""
from anthropic import Anthropic, DefaultHttpxClient
import stand_in
SYSTEM = "You are a polite support agent for SupportDesk."
def make_client():
http = DefaultHttpxClient(transport=stand_in.mock_transport())
return Anthropic(api_key="test-key", http_client=http)
def ask(client, question):
return client.messages.create(
model=stand_in.MODEL,
max_tokens=256,
system=SYSTEM,
messages=[{"role": "user", "content": question}],
)
def reply_text(message):
parts = []
for block in message.content:
if block.type == "text":
parts.append(block.text)
return "".join(parts)
- One client, made once. Create it at start-up and reuse it.
messages.createsends the request, aPOSTto/v1/messages.modelandmax_tokensare required. Leave outmax_tokensand the call fails.systemhas its own argument, beside the messages.messagesis a list. For now it holds one user turn.reply_textreads every text block in the reply.
To call the real API, create the client without the stand-in transport, with your key in the ANTHROPIC_API_KEY environment variable, and pass a current model id from Anthropic's models page. Never put a key in code.
A Message has parts
What comes back is a Message object, not a string. It has an id, a role, a model and a type, and three parts you'll use all the time:
contentis a list of blocks. Here there's one block of typetext, and the reply sits inside it. Other calls can return other block types (you'll meettool_usein the tool use article), so never readcontentas one string. Loop over the blocks and pick the text ones.stop_reasonsays why the model stopped.end_turnmeans it finished its answer.usagetells you how many tokens went in and came out. That's what you're billed on.
The API forgets every call
A customer rarely asks just once. But the Messages API keeps nothing between calls. If you send only the newest question, Claude has no idea what came before. So your code keeps the history and resends it every time:
"""A conversation: the API remembers nothing, so we send the history every time."""
import stand_in
from first_call import SYSTEM, reply_text
class Chat:
def __init__(self, client):
self.client = client
self.history = []
def say(self, text):
self.history.append({"role": "user", "content": text})
message = self.client.messages.create(
model=stand_in.MODEL,
max_tokens=256,
system=SYSTEM,
messages=self.history,
)
answer = reply_text(message)
self.history.append({"role": "assistant", "content": answer})
return answer
The history lives in a plain list. Each new question goes in as a user turn, the whole list is sent, and the reply is saved as an assistant turn, ready for the next question. Turn one sends one message. Turn two sends three: the first question, the answer, and the new question. A longer conversation means a longer messages list, and more input tokens on every call. LLM tokens, context windows and cost shows what that does to the bill.
What the run printed
The project's run_all.py makes the first call, prints what came back and what was sent, then runs a two-turn chat:
import stand_in
from first_call import ask, make_client, reply_text
from conversation import Chat
client = make_client()
print("first call")
message = ask(client, "Where is my refund?")
print("reply:", reply_text(message))
print("content blocks:", len(message.content), "(" + message.content[0].type + ")")
print("stop_reason:", message.stop_reason)
print("usage: input", message.usage.input_tokens, "output", message.usage.output_tokens)
print("request fields:", ", ".join(stand_in.WIRE[0]["fields"]))
print("conversation")
chat = Chat(client)
chat.say("Where is my refund?")
print("turn 1 sent", len(stand_in.WIRE[1]["roles"]), "message")
answer = chat.say("How long does it take?")
print("turn 2 sent", len(stand_in.WIRE[2]["roles"]), "messages")
print("turn 2 reply:", answer)
print("history roles:", ", ".join(m["role"] for m in chat.history))
first call
reply: test model reply: your refund was sent on Monday.
content blocks: 1 (text)
stop_reason: end_turn
usage: input 21 output 9
request fields: max_tokens, messages, model, system
conversation
turn 1 sent 1 message
turn 2 sent 3 messages
turn 2 reply: test model reply: it usually takes three to five working days.
history roles: user, assistant, user, assistant
The reply text and token numbers come from the stand-in and are made up for the demo. The shape is the real one: one text block, end_turn, a usage count, four request fields, and three messages sent on turn two.
The same call in TypeScript
The TypeScript SDK, @anthropic-ai/sdk, makes the same call with the same fields. Only the syntax changes:
import Anthropic from "@anthropic-ai/sdk";
import { MODEL, standInFetch } from "./stand_in.ts";
const client = new Anthropic({ apiKey: "test-key", fetch: standInFetch });
const message = await client.messages.create({
model: MODEL,
max_tokens: 256,
system: "You are a polite support agent for SupportDesk.",
messages: [{ role: "user", content: "Where is my refund?" }],
});
for (const block of message.content) {
if (block.type === "text") console.log("reply:", block.text);
}
console.log("stop_reason:", message.stop_reason);
console.log("usage: input", message.usage.input_tokens, "output", message.usage.output_tokens);
reply: test model reply: your refund was sent on Monday.
stop_reason: end_turn
usage: input 21 output 9
Common mistakes (and how the exam tests them)
Certification scenarios often describe a chat that forgets earlier turns, a call that fails, or a reply that can't be read. Each has a tempting wrong answer:
| Symptom | Wrong fix | Why it fails | Right fix |
|---|---|---|---|
| Chat forgets earlier turns | Send only the newest question | The API keeps nothing between calls | Resend the history every turn |
| Call is rejected | Leave out max_tokens | It's required | Always send max_tokens |
| Reply can't be read | Treat content as a string | It's a list of blocks | Loop over the blocks, keep the text ones |
Quick recap
| Send | Read back |
|---|---|
model: which model answers | content: a list of blocks |
max_tokens: required reply budget | stop_reason: why it stopped |
system: optional brief, beside the messages | usage: tokens in and out |
messages: the whole history, every turn |
Try it yourself
Remove system=SYSTEM from ask() and run run_all.py again. Which request fields does it print now, and does the call still work? Then remove max_tokens=256 instead and see what happens.
Next: let Claude look up real data with tool use in the Messages API.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →LLM Tokens, Context Windows and Cost: What One Question Really Costs
Next →Claude Tool Use: How tool_use and tool_result Work in the Messages API
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (opens in a new tab)