Claude API Basics
The Messages API
Master the Messages API: conversations, roles, content blocks, and managing multi-turn dialogs.
The Messages API
The Messages API is the core interface for interacting with Claude. It's a simple request/response interface where you send a list of messages and receive a response.
Message Roles
- user — Human messages / input
- assistant — Claude's responses
Messages alternate between user and assistant, starting with a user message.
Content Blocks
Messages can contain multiple content blocks:
- text — Plain text content
- image — Base64 or URL images (vision)
- tool_use — Tool call results
- tool_result — Result of a tool execution
API Response Structure
The response contains:
id— Unique message IDtype— "message"role— "assistant"content— Array of content blocksmodel— Model usedstop_reason— Why generation stoppedusage— Input/output token counts
Example
typescript
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
// Single message
const response = await client.messages.create({
model: "claude-opus-4-5",
max_tokens: 2048,
system: "You are a helpful Python tutor. Explain concepts clearly with examples.",
messages: [
{ role: "user", content: "What is a Python decorator?" }
],
});
console.log(response.content[0].text);
console.log("Tokens used:", response.usage);
// Multi-turn conversation
const conversation = await client.messages.create({
model: "claude-opus-4-5",
max_tokens: 1024,
messages: [
{ role: "user", content: "What is a closure in JavaScript?" },
{ role: "assistant", content: "A closure is a function that has access to variables from its outer scope even after the outer function has returned..." },
{ role: "user", content: "Can you give me a practical example?" }
],
});
// Image input (vision)
const imageResponse = await client.messages.create({
model: "claude-opus-4-5",
max_tokens: 1024,
messages: [{
role: "user",
content: [
{
type: "image",
source: {
type: "base64",
media_type: "image/png",
data: imageBase64,
},
},
{ type: "text", text: "What's in this image?" }
],
}],
});Try it yourself — TYPESCRIPT