API Overview

Base URL, API key families, common headers, error codes and rate-limit headers for the AnyRouter API.

Call any AnyRouter model by overriding the base URL and API key in OpenAI-compatible tooling, or use Messages for Anthropic-compatible tooling. The full OpenAPI spec, with a try-it runner, is at /docs/api.

Base URL

https://anyrouter.dev/api/v1

OpenAI-compatible clients that set the base URL to https://anyrouter.dev (and append /v1/... themselves) also work: /v1/models and /v1/chat/completions are the same API as /api/v1/....

Endpoints are versioned under /v1. Breaking changes land on /v2; /v1 stays available for a 12-month deprecation window, announced with a Deprecation response header. New fields and endpoints ship without notice.

Authentication: which key for which endpoint

AnyRouter has two API key families.

Key familyPrefixUse forGet one at
LLM API keysk-ar-v1-Inference: /chat/completions, /messages, /responses, /embeddings, /rerank, /moderations, /decisions (/systemone is the same handler). Also reads /models, /generation/:id, /auth/key./dashboard/keys
Management API keyak_Account administration: /keys (LLM-key CRUD), /presets, /auth/byok, /credits, /management-keys./dashboard/managed-access

The families do not cross over. An ak_ key on /chat/completions returns 401; an sk-ar-v1- key on /api/v1/keys returns 401 with a hint pointing here.

See Management API Keys for scopes and lifecycle.

Common headers

HeaderRequiredDescription
Authorization: Bearer <key>YesLLM key (sk-ar-…) on inference routes; management key (ak_…) on account routes.
Content-Type: application/jsonPOSTRequired on POST endpoints.
x-api-keyMessagesAnthropic-compatible auth header for /messages (accepts sk-ar-…).
anthropic-versionMessagesRequired by Anthropic-compatible Messages clients.
X-AnyRouter-ProviderNoForce routing to a specific upstream provider.
X-AnyRouter-Balance-After-Debit: trueNoAsk for this request's charge and the workspace balance after it. The response waits up to 500 ms for the charge, so leave it off unless you read the values.
X-AnyRouter-Trace-IdResponseCanonical trace id on every inference response. Paste it into the dashboard logs "Request ID" filter.
X-Request-IDResponseLegacy alias of X-AnyRouter-Trace-Id, same value.
X-AnyRouter-ModelResponsePublic catalog model id that served the request (including the resolved model for a virtual preset).
X-AnyRouter-Upstream-ModelResponseWire model name sent to the selected upstream.
X-AnyRouter-Provider-ChainResponseOrdered backend ids tried, joined with ->; contains route ids only, never credentials.
X-AnyRouter-Credential-SourceResponseplatform, own_byok, or pool for the winning attempt. This is a class label, not key material.
X-AnyRouter-Requested-Model / X-AnyRouter-Fallback-ReasonResponse, on model fallbackSent on /chat/completions when a different model served the request (for example through models[]). The reason is one of rate_limited, timeout, model_unavailable, credential_error, upstream_error, or not_attempted. The body carries the same facts as requested_model plus fallback: { used, reason, attempts[] }, on the non-streaming response and, for streams, on the last chunk, next to anyrouter_metadata (and usage, when you set stream_options.include_usage). The headers are authoritative. requested_model is the resolved canonical id, not the raw @preset/... string (for a preset, the first branch's model). anyrouter/* routers never get these.
X-AnyRouter-Credits-Balance-At-AdmissionResponse, when readWorkspace balance observed during paid-inference admission, before the asynchronous debit. It is omitted when the balance gate is skipped (free/BYOK-only).
X-AnyRouter-Credits-Balance-After-DebitResponse, non-streaming, on requestWorkspace balance right after this request's own charge was applied, on /chat/completions, /messages, and /responses. Sent only when the request included X-AnyRouter-Balance-After-Debit: true. Streaming responses carry it as anyrouter_metadata.balanceAfterDebit in the final metadata event. Omitted for free and BYOK requests, for a retried request already charged, and when the charge has not settled by the time the response is written (use GET /credits then). Concurrent requests can lower the balance further.
X-AnyRouter-Credits-ChargedResponse, non-streaming, on requestCredits this request was charged, from the billing ledger (includes retries, fallbacks and cache pricing). Sent on /chat/completions, /messages, and /responses only when the request included X-AnyRouter-Balance-After-Debit: true. 0 for free and BYOK requests. Streaming responses carry it as anyrouter_metadata.creditsCharged in the final metadata event. It is omitted for a retried request that was already charged and whenever the charge has not settled by the time the response is written.
X-AnyRouter-Credits-BalanceGET /credits responseCurrent authoritative workspace balance returned by the credits read endpoint.
X-RateLimit-* / RateLimit-*ResponseThe per-minute limit and policy for the tier the request hit (free models are capped per account by plan: 150 per minute on Go, 60 on Go from a donated key, 60 on Free after a $5 top-up, 400 on Pro, Pro+ and Max, reported as free-go, free-go-donation, free-topup or free-pro; see Rate Limits). No remaining count or reset is sent.
Server-TimingResponseLatency split in ms on /chat/completions, /messages and /responses: gw is AnyRouter's work before the first upstream call (auth, routing, admission), upstream is time inside upstream attempts (repeated per attempt with a desc naming the backend), post is AnyRouter's work after the upstream call, total is the sum. For a stream the header leaves with the first byte, so post covers only what happened before it; the full split arrives as anyrouter_metadata.timings in the final metadata frame.

Endpoint summary

MethodPathDescription
POST/chat/completionsChat completions (OpenAI-compatible)
POST/ocr/extractOCR — extract text as Markdown
POST/messagesAnthropic Messages passthrough
POST/responsesResponses for structured output and tool workflows
POST/embeddingsEmbeddings for search and clustering
POST/rerankRerank documents by relevance to a query
POST/documents/parseDocument parse — file to Markdown, your own Nace key
POST/moderationsModerations — classify text for harmful content
POST/decisionsDecisions TypeSafe decisions (not chat). Preferred path.
POST/systemoneSame handler as /decisions
GET/modelsList models
GET/models/:idModel metadata
GET/models/countTotal model count
GET/generation/:idPer-request stats (tokens, cost, latency)
GET/providersList upstream providers
GET/creditsRemaining credit balance
GET/auth/keyCurrent API key info
GET/healthGateway + provider status

Error shape

All errors follow a consistent JSON envelope:

{
  "error": {
    "code": "payment_required",
    "message": "Upstream provider \"cloudflare\" returned 402 — insufficient quota",
    "metadata": {
      "type": "upstream_error",
      "upstream_backend": "cloudflare",
      "upstream_status": 402,
      "upstream_message": "You exceeded your current quota, please check your plan and billing details."
    }
  }
}

error.code is a stable machine-readable slug. The canonical set:

HTTPerror.codeNotes
400bad_request / max_tokens_too_smallMalformed body or invalid parameters. max_tokens_too_small: a reasoning model spent the whole output budget on reasoning and produced no content — raise max_tokens (max_output_tokens on /responses) to 256 or more, or set stream: true.
401unauthorizedMissing or invalid API key.
402insufficient_balanceOut of credits on a paid model. Top up at Credits. Upstream BYOK billing failures may also surface as 402 with metadata.type: "upstream_error" — read metadata.upstream_message.
403forbiddenKey lacks permission for the resource.
404not_foundUnknown model or missing resource.
408request_timeoutUpstream did not respond in time.
413content_too_largeRequest body exceeds the configured limit.
422unprocessable_entityValidation failed semantically.
429rate_limit_exceeded / ip_rate_limit_exceededRate limit hit. Honor Retry-After. No X-RateLimit-Remaining / X-RateLimit-Reset is sent.
500internal_server_errorUnexpected AnyRouter failure.
502bad_gateway / upstream_exhaustedUpstream 5xx or every fallback failed; see metadata.upstream_attempts.
503service_unavailableUpstream temporarily unavailable.

When a BYOK call is rejected, error.metadata.upstream_message holds the provider's verbatim message and is the authoritative reason. See Errors for retry recipes.

Rate limits

Rate limits are enforced per-key. Every response carries at least:

X-RateLimit-Limit:     <requests per minute>
X-RateLimit-Window:    60
X-RateLimit-Tier:      <tier name>
RateLimit-Limit:       <same as X-RateLimit-Limit>
RateLimit-Policy:      <limit>;w=60

The per-minute tier does not emit X-RateLimit-Remaining or X-RateLimit-Reset — the edge limiter only reports the cap. See Rate Limits.

Tracing

POST /chat/completions and POST /responses also accept an optional request-body trace object:

{
  "trace": {
    "trace_id": "4f8c2b9670b44b49a2e71e7fd5c0b1d3",
    "trace_name": "checkout-flow",
    "span_name": "summarize-order"
  }
}

AnyRouter uses it to correlate request steps. Without a trace object you still get an X-Request-ID header for support.

AnyRouter routes requests to third-party models. Models and outputs are provided as is, with no warranty; you use them at your own risk. Disclaimer