Understanding the Messages API
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
The Messages API is the single endpoint behind almost everything you will build with Claude. This lesson goes through its parts one by one: roles, content blocks, multi-turn conversations, limits and the parameters you should and should not set on current models.
Learning objectives
- Describe every field of a Messages API request and response.
- Build a multi-turn conversation by resending history, with trimming.
- Send images as well as text.
- Avoid the request options that current models reject.
Prerequisites
The endpoint and its required fields
There is one endpoint: POST /v1/messages. Three fields are required:
| Field | Meaning |
model | The model ID, for example claude-sonnet-5-5. |
max_tokens | The most tokens the model may generate for this request. |
messages | The conversation: alternating user and assistant turns. |
Common optional fields are system (lesson 2.5), stream (2.6), tools and tool_choice (module 4), stop_sequences, thinking, metadata and output_config (2.8).
Roles and content
Each message has a role and content. content is either a plain string, or a list of content blocks. The two forms are equivalent for text:
{"role": "user", "content": "Hello"}
{"role": "user", "content": [{"type": "text", "text": "Hello"}]}
Use the list form when a message mixes types, such as an image and a question. Images can be sent as base64, as a URL, or as a reference to an uploaded file; supported media types are JPEG, PNG, GIF and WebP:
import base64
import anthropic
client = anthropic.Anthropic()
with open("invoice.png", "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
message = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=500,
messages=[{
"role": "user",
"content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": image_data}},
{"type": "text", "text": "What is the invoice total? Reply with the number only."},
],
}],
)
print(message.content[0].text)
Statelessness and multi-turn conversations
The API remembers nothing. To continue a chat you send the full history, including earlier assistant replies, each time. Earlier assistant turns do not even have to come from Claude: you may supply your own, which is useful for seeding examples or restoring a saved conversation.
That makes your application the memory. The class below keeps the list, stores each assistant reply, and drops the oldest user and assistant pair once the history gets long, so the list always starts with a user message and alternates roles:
import anthropic
class Conversation:
"""Keeps the message list for one chat. The API is stateless, so this object is the memory."""
def __init__(self, client: anthropic.Anthropic, model: str, system: str | None = None, max_turns: int = 10):
self.client, self.model, self.system, self.max_turns = client, model, system, max_turns
self.messages: list[dict] = []
def say(self, text: str, max_tokens: int = 500) -> str:
self.messages.append({"role": "user", "content": text})
kwargs = {"model": self.model, "max_tokens": max_tokens, "messages": self.messages}
if self.system:
kwargs["system"] = self.system
reply = self.client.messages.create(**kwargs)
answer = "".join(b.text for b in reply.content if b.type == "text")
# Store the assistant turn so the next request carries the whole history.
self.messages.append({"role": "assistant", "content": answer})
self._trim()
return answer
def _trim(self) -> None:
"""Drop the oldest user+assistant pair while the history is longer than max_turns pairs.
Removing whole pairs keeps the list starting with a user message and alternating roles."""
while len(self.messages) > self.max_turns * 2:
del self.messages[:2]
Dropping old turns is the simplest strategy. Better ones summarise old turns, or keep only the turns that matter; lessons 1.5 and 2.9 return to this. Whatever you choose, remember each turn you resend is billed again as input.
Mid-conversation system messages
Anthropic's documentation describes a way to add a new system instruction part-way through a chat: include a message with "role": "system" right after a user turn. It cannot be the first entry in messages, and it works on the current models listed in the docs. Use the top-level system field for instructions that apply from the start (lesson 2.5), and a mid-conversation message for instructions that only become relevant later.
Things current models reject
- Sampling parameters.
temperature, top_p and top_k are not supported on Claude 4.7 and later, and from API version 2026-10-21 any value returns a 400 error. Leave them out and guide behaviour with the prompt.
- Prefill. A final assistant message used to force how a reply starts is not supported on Claude 4.6 and later. The conversation must end with a user message.
- Old thinking settings.
thinking: {"type": "enabled", ...} is rejected on Claude 4.7 and later (use adaptive thinking), and thinking: {"type": "disabled"} is rejected on models where thinking is always on.
Many tutorials written for older models set exactly these fields. If you copy one and get a 400, this list is the first place to look.
Request limits
The Messages API accepts requests up to 128 MB, and up to 100,000 messages in a single request (per the API reference). A larger body returns 413 request_too_large. In practice the context window, not these limits, is what you hit first.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A documentation chatbot stores every message in a messages table with the conversation ID. On each user question it loads the last ten turns, appends the new question and calls the API. When a user returns a week later, the same rows restore the conversation. The model never "remembered" anything; the database did.
Common errors and solutions
| Symptom | Cause | Fix |
| 400 about roles or ordering | History does not alternate, or starts with an assistant turn. | Trim in whole user+assistant pairs; start with a user message. |
| 400 "does not support assistant message prefill" | Last message is from the assistant on Claude 4.6 or later. | End with a user message; use structured outputs or system instructions. |
400 mentioning temperature | Sampling parameter set on a current model. | Remove it. |
| Costs climb during a long chat | The whole history is resent and billed each turn. | Trim or summarise history. |
Security considerations
Everything you put in messages is data the model will read, including stored history. If users can edit or inject past turns, they can influence later answers. Store history server-side, never trust a client that sends its own history, and treat user text as untrusted input (module 8 covers prompt injection).
Performance and cost considerations
- Cost grows with every resent turn; a 20-turn chat bills turn 1 twenty times.
- Images add input tokens; count them before sending large batches (lesson 2.9).
- Keep
max_tokens realistic for the feature rather than the model's maximum.
Key takeaways
- Required fields are
model, max_tokens and messages.
content is a string or a list of blocks; images use the list form.
- The API is stateless, so your application stores and resends the conversation.
- Do not send
temperature/top_p/top_k, prefill or old thinking settings to current models.
Lesson recap: three required fields, a stateless conversation you resend, and options current models reject.
Knowledge check
- Which three request fields are required?
- When must you use the list form of
content?
- Why does the conversation helper drop messages two at a time?
- A request with
temperature: 0.2 returns a 400 on Claude Sonnet 5.5. Why?
- Your chatbot's cost per message doubles over a long conversation. What is the likely cause?
Answers and explanations
model, max_tokens and messages.
- When a message contains more than plain text, for example an image plus a question.
- Removing a user+assistant pair keeps the list starting with a user turn and keeps the roles alternating, which the API requires.
- Sampling parameters are not supported on Claude 4.7 and later models; any non-default value is rejected.
- The full history is resent and billed as input on every turn, so cost rises with conversation length.
Official references and further reading
Related tutorials