Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathBuild Your First LLM App with Claude
  1. 1
    LLM Tokens, Context Windows and Cost: What One Question Really Costs
  2. 2
    The Claude Messages API: Your First Call, Field by Field
  3. 3
    Claude Tool Use: How tool_use and tool_result Work in the Messages API
  4. 4
    The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

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.

Chaand Sheikh

·27 November 2026Building with the Claude API

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:

  1. Which model should answer.
  2. How long the reply may be.
  3. What the agent's job is.
  4. 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.

FieldWhat it saysRequired?
modelWhich model answersYes
max_tokensThe longest reply, in tokensYes
systemThe agent's briefNo
messagesThe conversation so farYes

One detail matters: the system prompt sits beside messages in the request, never inside it.

One request in, one Message out Request model max_tokens: 256 system: the brief messages: [user turn] 3 required, system optional Claude POST /v1/messages Message content: [blocks] type "text", the reply stop_reason: end_turn usage: input, output plus id, role, model, type
Four fields go out. A Message comes back with content blocks, a stop reason and usage.

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.create sends the request, a POST to /v1/messages.
  • model and max_tokens are required. Leave out max_tokens and the call fails.
  • system has its own argument, beside the messages.
  • messages is a list. For now it holds one user turn.
  • reply_text reads 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:

  • content is a list of blocks. Here there's one block of type text, and the reply sits inside it. Other calls can return other block types (you'll meet tool_use in the tool use article), so never read content as one string. Loop over the blocks and pick the text ones.
  • stop_reason says why the model stopped. end_turn means it finished its answer.
  • usage tells 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:

SymptomWrong fixWhy it failsRight fix
Chat forgets earlier turnsSend only the newest questionThe API keeps nothing between callsResend the history every turn
Call is rejectedLeave out max_tokensIt's requiredAlways send max_tokens
Reply can't be readTreat content as a stringIt's a list of blocksLoop over the blocks, keep the text ones

Quick recap

SendRead back
model: which model answerscontent: a list of blocks
max_tokens: required reply budgetstop_reason: why it stopped
system: optional brief, beside the messagesusage: 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 →
← Previous
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
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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)

Related articles
Claude Tool Use: How tool_use and tool_result Work in the Messages API

Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.

On this page
  • One request in, one Message out
  • first_call.py
  • A Message has parts
  • The API forgets every call
  • What the run printed
  • The same call in TypeScript
  • Common mistakes (and how the exam tests them)
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.