Provider workflows

Anthropic Messages API Request Workflow

Send a bounded Claude Messages API request with environment-based credentials, explicit configuration, response inspection, and recoverable failure handling.

Anthropic
CurrentNext review due 2026-08-24Content version 0.30.0
Format
Playbook
Level
Beginner
Audience
Developer, Operator
Owner
Project42 Editorial
Review cadence
Every 30 days
Prerequisites
Node.js 20 or later; An Anthropic API key stored outside source control; An approved Claude model ID
01

Prepare the request boundary

Set ANTHROPIC_API_KEY in the process environment or an approved secret manager and set PROJECT42_ANTHROPIC_MODEL to a reviewed model ID. Do not print, commit, paste into source, or send the key as model input. Decide the request purpose, permitted input, maximum output, timeout, retention, and expected response before calling the API.

The Messages API is stateless: your application owns conversation history and must send the intended turns on every request. Minimize retained content, separate trusted instructions from user data, and treat model text as untrusted until application checks pass.

02

Send a minimal request

This dependency-free Node.js example uses the required API version header and environment-only credentials. Replace the bracketed input at runtime; do not replace it with a secret.

messages-request.mjs
javascript
const apiKey = process.env.ANTHROPIC_API_KEY;
const model = process.env.PROJECT42_ANTHROPIC_MODEL;
if (!apiKey || !model) throw new Error("Missing ANTHROPIC_API_KEY or PROJECT42_ANTHROPIC_MODEL");

const response = await fetch("https://api.anthropic.com/v1/messages", {
  method: "POST",
  headers: {
    "content-type": "application/json",
    "x-api-key": apiKey,
    "anthropic-version": "2023-06-01",
  },
  body: JSON.stringify({
    model,
    max_tokens: 300,
    messages: [{ role: "user", content: "[INPUT_TEXT]" }],
  }),
  signal: AbortSignal.timeout(30_000),
});
const requestId = response.headers.get("request-id");
const body = await response.json();
if (!response.ok) throw new Error(`Anthropic request failed (${response.status}, request ${requestId ?? "unknown"})`);
const text = body.content?.find((block) => block.type === "text")?.text;
if (body.stop_reason !== "end_turn" || typeof text !== "string") throw new Error("Unexpected completion shape");
console.log({ requestId, text });
03

Expected evidence and verification

Expected output is an HTTP success containing a message object, a text content block, usage, an acceptable stop_reason, and a request-id header. Verify the status, content block types, stop reason, length, and application-specific rules before displaying or storing output. Log the request ID, model, latency, token counts, and redacted outcome—not the key or sensitive prompt content.

On authentication or validation errors, correct configuration rather than retrying. Retry only classified transient failures with bounded exponential backoff and jitter; honor rate limits and keep the original operation identifier. Because this read-only example has no external side effect, rollback means discarding the unaccepted response and restoring the last verified application state. If downstream side effects were added, require idempotency and explicit compensation before enabling them.