Your First API Call
The messages format
Claude's API uses a messages array, each with a role ("user" or "assistant") and content. A minimal call looks like:
```js
const msg = await anthropic.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{ role: "user", content: "Explain RAG in one paragraph." }],
});
```
Reading the response
The response object contains a content array (text blocks), usage (token counts for billing), and stop_reason. Always check stop_reason === "max_tokens" to detect a truncated response and increase max_tokens if needed.
Wiring it into a Next.js route
Create src/app/api/ask/route.ts, import the SDK, instantiate the client once, and call .messages.create() inside a POST handler. Return the text with NextResponse.json().
Key Takeaways
- Requests use a `messages` array with roles and content.
- Responses include token usage — track this for cost control.
- Always check `stop_reason` to detect truncation.
- Wrap the SDK call inside a Next.js API route, never in client code.
Build a one-question API route
Create a `/api/ask` POST route that accepts `{ question: string }` and returns Claude's answer as JSON. Test it with `curl` or Postman.