[metadata]
apple-mobile-web-app-status-bar-style: default
description: Practical patterns and examples for using the Messages API effectively
mobile-web-app-capable: yes
og:description: Practical patterns and examples for using the Messages API effectively
og:image: https://platform.claude.com/docs/og?locale=en&path=build-with-claude/working-with-messages&design-rev=1
og:image:alt: Using the Messages API
og:image:height: 630
og:image:type: image/png
og:image:width: 1200
og:locale: en
og:site_name: Claude Platform Docs
og:title: Using the Messages API
og:type: article
og:url: https://platform.claude.com/docs/en/build-with-claude/working-with-messages
twitter:card: summary_large_image
twitter:description: Practical patterns and examples for using the Messages API effectively
twitter:image: https://platform.claude.com/docs/og?locale=en&path=build-with-claude/working-with-messages&design-rev=1
twitter:title: Using the Messages API
viewport: width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover

[canonical-links]
https://platform.claude.com/docs/en/build-with-claude/working-with-messages

[document-links]
AI agents: https://claude.com/solutions/agents
API and data retention: /docs/en/manage-claude/api-and-data-retention
Admin: /docs/en/manage-claude/admin-api
Advisor tool: /docs/en/agents-and-tools/tool-use/advisor-tool
Amazon Bedrock (Opus 4.6 and earlier): /docs/en/build-with-claude/claude-on-amazon-bedrock-legacy
Amazon Bedrock (Opus 4.7 and later): /docs/en/build-with-claude/claude-in-amazon-bedrock
Anthropic: https://www.anthropic.com/company
Authentication: /docs/en/manage-claude/authentication
Availability: https://www.anthropic.com/supported-countries
Bash tool: /docs/en/agents-and-tools/tool-use/bash-tool
Batch processing: /docs/en/build-with-claude/batch-processing
Best practices: /docs/en/about-claude/use-case-guides/overview
Best practices: /docs/en/agents-and-tools/agent-skills/best-practices
Blog: https://claude.com/blog
Build an orchestration mode: /docs/en/build-with-claude/mid-conversation-effort-example
CLI, SDKs, and libraries: /docs/en/cli-sdks-libraries/overview
Cache diagnostics (beta): /docs/en/build-with-claude/cache-diagnostics
Careers: https://www.anthropic.com/careers
Citations: /docs/en/build-with-claude/citations
Claude API skill: /docs/en/agents-and-tools/agent-skills/claude-api-skill
Claude Managed Agents overview: /docs/en/managed-agents/overview
Claude Mythos 5: https://anthropic.com/glasswing
Claude Mythos Preview: https://anthropic.com/glasswing
Claude Platform Docs: /docs
Claude Platform Docs: /docs/en/home
Claude Platform on AWS: /docs/en/build-with-claude/claude-platform-on-aws
Claude on AWS: https://claude.com/partners/amazon-bedrock
Claude on Google Cloud: https://claude.com/partners/google-cloud-vertex-ai
Code execution tool: /docs/en/agents-and-tools/tool-use/code-execution-tool
Code modernization: https://claude.com/solutions/code-modernization
Coding: https://claude.com/solutions/coding
Compaction: /docs/en/build-with-claude/compaction
Computer use tool: /docs/en/agents-and-tools/tool-use/computer-use-tool
Connectors: https://claude.com/partners/mcp
Context editing: /docs/en/build-with-claude/context-editing
Context windows: /docs/en/build-with-claude/context-windows
Courses: https://claude.com/resources/courses
Customer stories: https://claude.com/customers
Customer support: https://claude.com/solutions/customer-support
Define tools: /docs/en/agents-and-tools/tool-use/define-tools
Discord: https://www.anthropic.com/discord
Economic Futures: https://www.anthropic.com/economic-futures
Effort: /docs/en/build-with-claude/effort
Embeddings: /docs/en/build-with-claude/embeddings
Engineering at Anthropic: https://www.anthropic.com/engineering
Events: https://www.anthropic.com/events
Fallback credit: /docs/en/build-with-claude/fallback-credit
Fast mode (research preview): /docs/en/build-with-claude/fast-mode
Features overview: /docs/en/build-with-claude/overview
Files API: /docs/en/build-with-claude/files
Financial services: https://claude.com/solutions/financial-services
Fine-grained tool streaming: /docs/en/agents-and-tools/tool-use/fine-grained-tool-streaming
Get your API key: /docs/en/get-api-key
Google Cloud: /docs/en/build-with-claude/claude-on-vertex-ai
Government: https://claude.com/solutions/government
Handle tool calls: /docs/en/agents-and-tools/tool-use/handle-tool-calls
Handling stop reasons: /docs/en/build-with-claude/refusals-and-fallback#refusal-response
Higher education: https://claude.com/solutions/education
How tool use works: /docs/en/agents-and-tools/tool-use/how-tool-use-works
Intro to Claude: /docs/en/intro
K-12 teachers: https://claude.com/solutions/teachers
Life sciences: https://claude.com/solutions/life-sciences
Log in: /login?returnTo=%2Fdocs%2Fen%2Fbuild-with-claude%2Fworking-with-messages
MCP connector: /docs/en/agents-and-tools/mcp-connector
Manage tool context: /docs/en/agents-and-tools/tool-use/manage-tool-context
Managed Agents: /docs/en/managed-agents/overview
Memory tool: /docs/en/agents-and-tools/tool-use/memory-tool
Messages API reference: /docs/en/api/messages/create
Messages: /docs/en/intro
Microsoft Foundry: /docs/en/build-with-claude/claude-in-microsoft-foundry
Mid-conversation system messages and tool changes: /docs/en/build-with-claude/mid-conversation-system-messages
Mid-conversation system messages: /docs/en/build-with-claude/mid-conversation-system-messages
Models & pricing: /docs/en/about-claude/models/overview
Multilingual support: /docs/en/build-with-claude/multilingual-support
News: https://www.anthropic.com/news
Overview: /docs/en/agents-and-tools/agent-skills/overview
Overview: /docs/en/agents-and-tools/tool-use/overview
PDF support: /docs/en/build-with-claude/pdf-support
Parallel tool use: /docs/en/agents-and-tools/tool-use/parallel-tool-use
Powered by Claude: https://claude.com/partners/powered-by-claude
Privacy policy: https://www.anthropic.com/legal/privacy
Programmatic tool calling: /docs/en/agents-and-tools/tool-use/programmatic-tool-calling
Prompt caching: /docs/en/build-with-claude/prompt-caching
Quickstart: /docs/en/agents-and-tools/agent-skills/quickstart
Quickstart: /docs/en/get-started
Refusals and fallback: /docs/en/build-with-claude/refusals-and-fallback
Release notes: /docs/en/release-notes/overview
Remote MCP servers: /docs/en/agents-and-tools/remote-mcp-servers
Research: https://www.anthropic.com/research
Responsible Scaling Policy: https://www.anthropic.com/news/announcing-our-updated-responsible-scaling-policy
Responsible disclosure policy: https://www.anthropic.com/responsible-disclosure-policy
Search results: /docs/en/build-with-claude/search-results
Security and compliance: https://trust.anthropic.com
Server tools: /docs/en/agents-and-tools/tool-use/server-tools
Service partners: https://claude.com/partners/services
Skills for enterprise: /docs/en/agents-and-tools/agent-skills/enterprise
Skills in the API: /docs/en/build-with-claude/skills-guide
Startups program: https://claude.com/programs/startups
Status: https://status.claude.com/
Stop reasons and fallback: /docs/en/build-with-claude/handling-stop-reasons
Streaming Messages: /docs/en/build-with-claude/streaming
Streaming refusals: /docs/en/test-and-evaluate/strengthen-guardrails/handle-streaming-refusals
Strict tool use: /docs/en/agents-and-tools/tool-use/strict-tool-use
Structured outputs: /docs/en/build-with-claude/structured-outputs
Support: https://support.claude.com/
Task budgets (beta): /docs/en/build-with-claude/task-budgets
Task budgets: /docs/en/build-with-claude/task-budgets
Terms of service: Commercial: https://www.anthropic.com/legal/commercial-terms
Terms of service: Consumer: https://www.anthropic.com/legal/consumer-terms
Text editor tool: /docs/en/agents-and-tools/tool-use/text-editor-tool
Token counting: /docs/en/build-with-claude/token-counting
Tool Runner (SDK): /docs/en/agents-and-tools/tool-use/tool-runner
Tool combinations: /docs/en/agents-and-tools/tool-use/tool-combinations
Tool reference: /docs/en/agents-and-tools/tool-use/tool-reference
Tool search tool: /docs/en/agents-and-tools/tool-use/tool-search-tool
Tool use with Claude: /docs/en/agents-and-tools/tool-use/overview
Tool use with prompt caching: /docs/en/agents-and-tools/tool-use/tool-use-with-prompt-caching
Transparency: https://www.anthropic.com/transparency
Troubleshooting: /docs/en/agents-and-tools/tool-use/troubleshooting-tool-use
Tutorial: Build a tool-using agent: /docs/en/agents-and-tools/tool-use/build-a-tool-using-agent
Usage policy: https://www.anthropic.com/legal/aup
Use cases: https://claude.com/resources/use-cases
Using the Messages API: /docs/en/build-with-claude/working-with-messages
Web fetch tool: /docs/en/agents-and-tools/tool-use/web-fetch-tool
Web search tool: /docs/en/agents-and-tools/tool-use/web-search-tool
https://instagram.com/claudeai
https://www.linkedin.com/showcase/claude
https://www.threads.com/@claudeai
https://www.youtube.com/@anthropic-ai
https://x.com/claudeai
migration guide: /docs/en/about-claude/models/migration-guide
migration guide: /docs/en/about-claude/models/migration-guide#migrating-from-claude-opus-47
placement rules: /docs/en/build-with-claude/mid-conversation-system-messages#limitations
prompt caching: /docs/en/build-with-claude/prompt-caching
structured outputs: /docs/en/build-with-claude/structured-outputs
vision guide: /docs/en/build-with-claude/vision
 API reference: /docs/en/api/overview
 Console: /

[content]
Using the Messages API - Claude Platform Docs
Claude Platform Docs
Messages
Managed Agents
Admin
Resources

Best practices
Models & pricing
CLI, SDKs, and libraries
Claude API skill
Release notes

API reference

English


Console
Log in


Search
Ctrl
K
First steps
Intro to Claude
Get your API key
Quickstart
Authentication
Building with Claude
Features overview
Using the Messages API
Stop reasons and fallback
Refusals and fallback
Fallback credit
Model capabilities
Effort
Task budgets (beta)
Fast mode (research preview)
Structured outputs
Citations
Streaming Messages
Batch processing
Search results
Streaming refusals
Multilingual support
Embeddings
Thinking

Tools
Overview
How tool use works
Tutorial: Build a tool-using agent
Define tools
Handle tool calls
Parallel tool use
Tool Runner (SDK)
Strict tool use
Server tools
Web search tool
Web fetch tool
Code execution tool
Advisor tool
Tool search tool
Memory tool
Bash tool
Text editor tool
Computer use tool
Troubleshooting
Tool infrastructure
Tool reference
Manage tool context
Tool combinations
Tool use with prompt caching
Programmatic tool calling
Fine-grained tool streaming
Context management
Context windows
Compaction
Context editing
Prompt caching
Mid-conversation system messages and tool changes
Build an orchestration mode
Cache diagnostics (beta)
Token counting
Working with files
Files API
PDF support
Images and vision

Skills
Overview
Quickstart
Best practices
Skills for enterprise
Skills in the API
MCP
Remote MCP servers
MCP connector
MCP tunnels

Claude on cloud platforms
Amazon Bedrock (Opus 4.7 and later)
Amazon Bedrock (Opus 4.6 and earlier)
Claude Platform on AWS
Google Cloud
Microsoft Foundry

Console
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Loading
Claude Platform Docs


Solutions
AI agents
Code modernization
Coding
Customer support
Financial services
Government
Higher education
K-12 teachers
Life sciences
Partners
Claude on AWS
Claude on Google Cloud
Learn
Blog
Courses
Use cases
Connectors
Customer stories
Engineering at Anthropic
Events
Powered by Claude
Service partners
Startups program
Company
Anthropic
Careers
Economic Futures
Research
News
Responsible Scaling Policy
Security and compliance
Transparency
Learn
Blog
Courses
Use cases
Connectors
Customer stories
Engineering at Anthropic
Events
Powered by Claude
Service partners
Startups program
Help and security
Availability
Status
Support
Discord
Terms and policies
Privacy policy
Responsible disclosure policy
Terms of service: Commercial
Terms of service: Consumer
Usage policy
Messages

Building with Claude
Using the Messages API

Copy page

Practical patterns and examples for using the Messages API effectively

Copy page

Anthropic offers two ways to build with Claude, each suited to different use cases:
Messages API
Claude Managed Agents
What it is
Direct model prompting access
Pre-built, configurable agent harness that runs in managed infrastructure
Best for
Custom agent loops and fine-grained control
Long-running tasks and asynchronous work
This guide covers common patterns for working with the Messages API, including basic requests, multi-turn conversations, prefill techniques, and vision capabilities. For complete API specifications, see the
Messages API reference
. For the managed agent harness instead, see the
Claude Managed Agents overview
.

For how zero data retention (ZDR) applies to this feature, see
API and data retention
.

Basic request and response

The
temperature
,
top_p
, and
top_k
sampling parameters are not supported on Claude 4.7 and later models and Claude Mythos Preview. Setting them to a non-default value returns a 400 error. Omit them from request payloads and use prompting to guide the model's behavior instead. See the
migration guide
.
cURL
CLI
Python
TypeScript
C#
Go
Java
PHP
Ruby

message
=
anthropic.Anthropic().messages.create(
model
=
"claude-opus-5"
,
max_tokens
=
1024
,
messages
=
[{
"role"
:
"user"
,
"content"
:
"Hello, Claude"
}],
)
print
(message)
Output

{
"id"
:
"msg_01XFDUDYJgAACzvnptvVoYEL"
,
"type"
:
"message"
,
"role"
:
"assistant"
,
"content"
: [
{
"type"
:
"text"
,
"text"
:
"Hello!"
}
],
"model"
:
"claude-opus-5"
,
"stop_reason"
:
"end_turn"
,
"stop_sequence"
:
null
,
"usage"
: {
"input_tokens"
:
12
,
"output_tokens"
:
6
}
}
Refusal responses (
stop_reason: "refusal"
) also include a
stop_details
object identifying the policy category that triggered the refusal, on every model. See
Handling stop reasons
for the field reference and example handling code.

Multiple conversational turns
The Messages API is stateless, which means that you always send the full conversational history to the API. You can use this pattern to build up a conversation over time. Earlier conversational turns don't necessarily need to actually originate from Claude. You can use synthetic
assistant
messages.
cURL
CLI
Python
TypeScript
C#
Go
Java
PHP
Ruby

message
=
anthropic.Anthropic().messages.create(
model
=
"claude-opus-5"
,
max_tokens
=
1024
,
messages
=
[
{
"role"
:
"user"
,
"content"
:
"Hello, Claude"
},
{
"role"
:
"assistant"
,
"content"
:
"Hello!"
},
{
"role"
:
"user"
,
"content"
:
"Can you describe LLMs to me?"
},
],
)
print
(message)
Output

{
"id"
:
"msg_018gCsTGsXkYJVqYPxTgDHBU"
,
"type"
:
"message"
,
"role"
:
"assistant"
,
"content"
: [
{
"type"
:
"text"
,
"text"
:
"Sure, I'd be happy to provide..."
}
],
"model"
:
"claude-opus-5"
,
"stop_reason"
:
"end_turn"
,
"stop_sequence"
:
null
,
"usage"
: {
"input_tokens"
:
30
,
"output_tokens"
:
309
}
}

System role in messages
On Claude Fable 5,
Claude Mythos 5
, Claude Opus 4.8, and Claude Opus 5, you can include messages with
"role": "system"
after a user turn (subject to
placement rules
) to add a new system instruction partway through a conversation. A
system
message cannot be the first entry in
messages
; use the top-level
system
field for instructions that apply from the start.
A mid-conversation system message has the same authority as the top-level
system
field, but because it is appended to the end of the message history, it does not invalidate any cached prefix that came before it. Use the top-level
system
field for instructions that should apply from the very first turn, and a mid-conversation system message for instructions that only become relevant later.
See
Mid-conversation system messages
for the complete guide, including how to combine it with
prompt caching
.

Prefilling Claude's response
You can pre-fill part of Claude's response in the last position of the input messages list. Use this technique to shape Claude's response. The following example uses
"max_tokens": 1
to get a single multiple choice answer from Claude.

Prefilling is not supported on Claude 4.6 and later models and
Claude Mythos Preview
. Requests using prefill with these models return a 400 error. Use
structured outputs
on models that support it, or system prompt instructions, instead. See the
migration guide
for migration patterns.
cURL
CLI
Python
TypeScript
C#
Go
Java
PHP
Ruby

message
=
anthropic.Anthropic().messages.create(
model
=
"claude-sonnet-4-5"
,
max_tokens
=
1
,
messages
=
[
{
"role"
:
"user"
,
"content"
:
"What is latin for Ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"
,
},
{
"role"
:
"assistant"
,
"content"
:
"The answer is ("
},
],
)
print
(message)
Output

{
"id"
:
"msg_01Q8Faay6S7QPTvEUUQARt7h"
,
"type"
:
"message"
,
"role"
:
"assistant"
,
"content"
: [
{
"type"
:
"text"
,
"text"
:
"C"
}
],
"model"
:
"claude-sonnet-4-5"
,
"stop_reason"
:
"max_tokens"
,
"stop_sequence"
:
null
,
"usage"
: {
"input_tokens"
:
42
,
"output_tokens"
:
1
}
}

Vision
Claude can read both text and images in requests. You can supply images using the
base64
,
url
, or
file
source types. The
file
source type references an image uploaded through the
Files API
. Supported media types are
image/jpeg
,
image/png
,
image/gif
, and
image/webp
. See the
vision guide
for more details.
cURL
CLI
Python
TypeScript
C#
Go
Java
PHP
Ruby

import
base64
import
httpx
# Option 1: Base64-encoded image
image_url
=
"https://platform.claude.com/docs/images/vision-example.jpg"
image_media_type
=
"image/jpeg"
image_data
=
base64.standard_b64encode(httpx.get(image_url).content).decode(
"utf-8"
)
message
=
anthropic.Anthropic().messages.create(
model
=
"claude-opus-5"
,
max_tokens
=
1024
,
messages
=
[
{
"role"
:
"user"
,
"content"
: [
{
"type"
:
"image"
,
"source"
: {
"type"
:
"base64"
,
"media_type"
: image_media_type,
"data"
: image_data,
},
},
{
"type"
:
"text"
,
"text"
:
"What is in the above image?"
},
],
}
],
)
print
(message)
# Option 2: URL-referenced image
message_from_url
=
anthropic.Anthropic().messages.create(
model
=
"claude-opus-5"
,
max_tokens
=
1024
,
messages
=
[
{
"role"
:
"user"
,
"content"
: [
{
"type"
:
"image"
,
"source"
: {
"type"
:
"url"
,
"url"
:
"https://platform.claude.com/docs/images/vision-example.jpg"
,
},
},
{
"type"
:
"text"
,
"text"
:
"What is in the above image?"
},
],
}
],
)
print
(message_from_url)
Output

{
"id"
:
"msg_011CdKmWtV3oFx1C5yUbf5CY"
,
"type"
:
"message"
,
"role"
:
"assistant"
,
"content"
: [
{
"type"
:
"text"
,
"text"
:
"This image is a beautiful minimalist/flat-design illustration of a sunset landscape. Here's what it contains:
\n\n
**Sky & Sun:**
\n
- A warm gradient sky transitioning from golden-yellow at the top to deep orange toward the horizon
\n
- A large pale yellow sun positioned in the upper-right area
\n\n
**Birds:**
\n
- Three small silhouetted birds flying in the upper-left portion of the sky, depicted as simple
\"
M
\"
or
\"
v
\"
shapes
\n\n
**Mountains:**
\n
- Multiple layered mountain peaks in purple and maroon tones
\n
- The mountains overlap to create depth, with varying shades of dusty purple and deep burgundy
\n\n
**Water:**
\n
- A dark purple body of water at the bottom of the image
\n
- A reflection of the sun shown as horizontal cream/peach colored lines in the center-bottom area
\n\n
The overall style is clean, geometric, and uses a warm sunset color palette (oranges, yellows, purples, and maroons), giving it a peaceful, serene aesthetic typical of modern vector/flat design artwork."
}
],
"model"
:
"claude-opus-5"
,
"stop_reason"
:
"end_turn"
,
"stop_sequence"
:
null
,
"usage"
: {
"input_tokens"
:
1030
,
"output_tokens"
:
350
}
}

Next steps

Stop reasons and fallback
Handle each
stop_reason
value and decide what to do when a response ends.

Tool use with Claude
Give Claude tools to call external services and APIs from within the Messages API.

Computer use tool
Control desktop computer environments with the Messages API.

Structured outputs
Get guaranteed, schema-validated JSON output from Claude.

Task budgets
Set an advisory token budget across a full agentic loop with
output_config.task_budget
.
Was this page helpful?


Basic request and response
Multiple conversational turns
System role in messages
Prefilling Claude's response
Vision
Next steps
