Browse documentation

Messages

Create conversational turns using the native Anthropic Messages API wire format across Claude and cloud providers with prompt caching and cost tracking.

The /v1/messages endpoint provides direct compatibility with the native Anthropic Messages API wire format across Claude and cloud providers. Send existing Claude SDK payloads to the Claude models nRouter serves, with configurable fallback chains, prompt caching telemetry, and exact list pricing. See the Anthropic Messages API documentation.

Preflight evaluates key ACLs, rate limits (RPM/TPM), content inspection, and token reservations (x-nr-guardrails: blocked returns HTTP 400 with $0 spent and $0 held). Native Anthropic SSE streaming, caching metrics, and thinking blocks are preserved; fallbacks trigger only when configured (Router Settings or nrouter_fallbacks).

POST https://api.nrouter.ai/v1/messages

Request Parameters

ParameterTypeRequiredDefaultDescription
modelstringYes—Target Claude model (e.g. claude-sonnet-4-5-20250929).
messagesarrayYes—Input messages containing role (user or assistant) and content.
max_tokensintegerYes—Maximum number of tokens to generate.
systemstring or arrayNo—System prompt string or array of text blocks supporting cache controls.
metadataobjectNo—Request metadata object (e.g. user_id).
stop_sequencesstring[]No—Custom sequences halting token generation.
streambooleanNofalseWhen true, streams chunks via Server-Sent Events (SSE).
temperaturenumberNo1.0Sampling randomness between 0.0 and 1.0.
top_pnumberNo—Nucleus sampling cutoff threshold.
top_kintegerNo—Sample from top K options for each token.
toolsarrayNo—Tool definitions available to the model.
tool_choiceobjectNo{"type": "auto"}Tool use configuration (auto, any, tool).
thinkingobjectNo—Extended thinking mode configuration.
nrouter_fallbacksstring[]No—1–4 fallback models if primary provider admission fails.
nrouter_guardrailsstring[]No—1–8 organization guardrail policy IDs.
nrouter_cachebooleanNotrueWhen false, bypasses the response cache.

Examples

import { nRouter } from "@nrouter_ai/sdk";
const client = new nRouter({ apiKey: process.env.NROUTER_API_KEY });
const res = await client.messages.create({
  model: "claude-sonnet-4-5-20250929", max_tokens: 1024, messages: [{ role: "user", content: "Hello!" }],
});
console.log(res.content[0].text, client.lastResponse?.cost);

Headers & Errors

Inbound: Authorization: Bearer sk-nrouter-..., Content-Type: application/json, optional anthropic-version: 2023-06-01, x-nr-tags. Telemetry: x-nr-request-id, x-nr-latency-ms, x-nr-request-cost, x-nr-model, x-nr-routing, x-nr-attempts, x-nr-guardrails, x-nr-cache-read-tokens, x-nr-cache-write-tokens. See Chat Completions.

HTTP StatusError CodeReason
400 Bad Requestinvalid_requestMissing required max_tokens or messages field.
400 Bad Requestguardrail_blockedPreflight inspection detected prompt injection or safety policy violation.
401 Unauthorizedinvalid_api_keyVirtual key missing, expired, or invalid.
402 Payment Requiredinsufficient_creditsOrganization balance insufficient to reserve token hold.
404 Not Foundmodel_not_foundModel identifier not found or unauthorized for tenant.
429 Too Many Requestsrate_limit_exceededRPM or TPM ceiling crossed; check x-nr-limit-source.
500 / 503 Provider Errorservice_unavailableUpstream outage. 503 triggers fallback only if configured (nrouter_fallbacks).
POST
/v1/messages

Authorization

NRouterApiKey
AuthorizationBearer <token>

Your nRouter virtual key (sk-nrouter-…). Sent as Authorization: Bearer sk-nrouter-….

In: header

Header Parameters

x-nr-compress?string

Request prompt compression: on to compress eligible prompts, off to skip

Value in

  • "on"
  • "off"
x-nr-tags?string

Custom spend and attribution tags (comma-separated key=value pairs)

x-nr-mcp-server?string

Target MCP server ID when routing MCP tool calls or prompts through the gateway

x-nr-client-language?string

Caller SDK runtime language identification (e.g. typescript, python, rust, go)

x-nr-session-id?string

Caller session identifier allowed at edge for grouping related client turns

x-nr-trace?string

Inbound trace detail level override for request lifecycle spans

Value in

  • "off"
  • "stages"
  • "verbose"
x-nr-trace-stages?string

Inbound stage-level trace emission override

Value in

  • "off"
  • "stages"
  • "verbose"
x-nr-trace-id?string

Accepted so a client sending it is not refused; the value is not recorded and not propagated. Every response carries the gateway's own trace ID in this header, never the one sent.

Request Body

application/json

TypeScript Definitions

Use the request body type in TypeScript.

Response Body

application/json

application/json

application/json

application/json

application/json

application/json

application/json

application/json

application/json

curl -X POST "https://example.com/v1/messages" \  -H "Content-Type: application/json" \  -d '{    "model": "claude-sonnet-4-5-20250929",    "max_tokens": 1024,    "messages": [      {        "role": "user",        "content": "Explain multi-tenant credit reservation."      }    ]  }'
{  "id": "msg_01",  "type": "message",  "role": "assistant",  "content": [    {      "type": "text",      "text": "Hello!"    }  ],  "usage": {    "input_tokens": 9,    "output_tokens": 3  }}
Was this page helpful?