📘 Developer API reference

API Documentation

Everything you need to integrate SilkGateway: OpenAI and Claude formats, streaming SSE, usage, billing and automatic multi-subscription failover.

Max input
1M
tokens by default
Max output
128K
when max_tokens omitted
Formats
2
OpenAI & Claude, auto-translated
Edge
300+
Cloudflare locations

Quick Start

Sign up at silkgateway.ai/register/, verify your email, and your API key appears in the Dashboard.

Point any OpenAI-compatible client at https://api.silkgateway.ai/v1 and use your key as the API token.

Your first request
bash
curl https://api.silkgateway.ai/v1/chat/completions \
  -H "Authorization: Bearer sk-your-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-chat",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
💡 Add "stream": true to receive tokens in real time — see the streaming examples in Chat Completions below.

Authentication

Every API request requires an API key. Two header styles are accepted:

http
Authorization: Bearer sk-your-api-key
X-Api-Key: sk-your-api-key

The key can also be passed as ?api_key=…, but header authentication is recommended.

⚠️ Keep your API key secret — never expose it in client-side code or public repositories. You can reset it anytime from the Dashboard; the old key stops working immediately.
Base URL
url
https://api.silkgateway.ai/v1

Fully OpenAI-compatible — any OpenAI SDK, LangChain, or plain HTTP client works unchanged.

Account & auth endpoints

Account operations authenticate with the JWT returned by /api/login (valid 24h). /api/user also accepts the API key.

Endpoint Method Description
/api/registerPOSTRegister (email + password, sends a verification email)
/api/verify-emailGETVerify email via token; issues the API key
/api/resend-verificationPOSTResend the verification email
/api/loginPOSTLog in (email + password → JWT, 24h)
/api/logoutPOSTLog out (revokes the JWT)
/api/forgot-passwordPOSTSend a password-reset email
/api/reset-passwordPOSTReset password (token + new password)
/api/reset-api-keyPOSTReset the API key (JWT required; old key fails immediately)
/api/userGETAccount info (JWT or API key)
Register & login
bash
curl -X POST https://api.silkgateway.ai/api/register \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","firstName":"John","lastName":"Doe","password":"SecurePass123"}'

curl -X POST https://api.silkgateway.ai/api/login \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","password":"SecurePass123"}'
# → { "token": "eyJ...", "user": { "email": "...", "tier": "free" } }

Chat Completions

POST /v1/chat/completions

OpenAI-compatible chat completions with streaming SSE, tier rate-limit headers and transparent multi-subscription failover.

Request body
Parameter Type Required Description
modelstringrequiredModel ID (e.g. deepseek-chat) or combo name (e.g. fast-cheap) — see Models & Pricing.
messagesarrayrequiredOpenAI-format message array: {role, content}.
streambooleanoptionalSet true to receive tokens as Server-Sent Events. Default false.
temperaturenumberoptionalSampling temperature, 0–2. Defaults to the upstream default (1).
max_tokensintegeroptionalMax output tokens. Defaults to 128000 when omitted; if the model caps lower, the gateway retries once without the cap.
optionalOther standard OpenAI parameters (top_p, tools, …) pass through to the model.
Example request
bash
curl https://api.silkgateway.ai/v1/chat/completions \
  -H "Authorization: Bearer sk-your-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-chat",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "What is the Silk Road?"}
    ],
    "temperature": 0.7,
    "max_tokens": 500
  }'
Response
json
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "model": "deepseek-chat",
  "choices": [{
    "index": 0,
    "message": { "role": "assistant", "content": "The Silk Road was an ancient trade network..." },
    "finish_reason": "stop"
  }],
  "usage": { "prompt_tokens": 25, "completion_tokens": 150, "total_tokens": 175 }
}

Streaming

Set "stream": true to receive tokens as Server-Sent Events: each line is a JSON chunk and the stream ends with the [DONE] sentinel.

bash
curl https://api.silkgateway.ai/v1/chat/completions \
  -H "Authorization: Bearer sk-your-key" \
  -H "Content-Type: application/json" \
  -d '{"model":"deepseek-chat","messages":[{"role":"user","content":"Hello"}],"stream":true}'
Streaming response (SSE)
sse
data: {"choices":[{"delta":{"content":"Hello"}}]}

data: {"choices":[{"delta":{"content":"!"}}]}

data: {"choices":[{"delta":{},"finish_reason":"stop"}]}

data: [DONE]
💡 Every response carries X-Request-Id and X-RateLimit-* headers — see Errors & Rate Limits below.

Claude Messages

POST /v1/messages

Anthropic Messages API: requests are translated to OpenAI upstream and responses back to Claude format — Claude SDK and Claude Code work out of the box.

Authenticate with x-api-key (or Authorization: Bearer) and send anthropic-version: 2023-06-01.

Example request
bash
curl https://api.silkgateway.ai/v1/messages \
  -H "x-api-key: sk-your-key" \
  -H "Content-Type: application/json" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "deepseek-chat",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
python
import anthropic

client = anthropic.Anthropic(
    api_key="sk-your-key",
    base_url="https://api.silkgateway.ai",
)

msg = client.messages.create(
    model="deepseek-chat",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello!"}],
)
print(msg.content[0].text)
Response
json
{
  "id": "msg_abc123",
  "type": "message",
  "role": "assistant",
  "model": "deepseek-chat",
  "content": [{ "type": "text", "text": "Hello! How can I help?" }],
  "stop_reason": "end_turn",
  "usage": { "input_tokens": 12, "output_tokens": 20 }
}

Streaming

With "stream": true the gateway emits Anthropic-style SSE with event: lines, translated chunk by chunk.

Streaming response (SSE)
sse
event: message_start
data: {"type":"message_start","message":{"id":"msg_abc123","role":"assistant"}}

event: content_block_delta
data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"Hello"}}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}

event: message_stop
data: {"type":"message_stop"}
Claude Code / Claude SDK
bash
export ANTHROPIC_BASE_URL=https://api.silkgateway.ai
export ANTHROPIC_API_KEY=sk-your-key
# the SDK appends /v1/messages automatically

Models & Pricing

Public endpoints — no authentication required. The table below is fetched live from the gateway when the page loads.

GET /v1/models Public

All routable models in OpenAI list format: {id, object, owned_by}.

GET /v1/pricing Public

Per-model prices plus tier quotas and discounts.

GET /v1/combos Public

Combo list with strategy and model chain.

Example
bash
curl https://api.silkgateway.ai/v1/models
curl https://api.silkgateway.ai/v1/pricing
curl https://api.silkgateway.ai/v1/combos
Live pricing
Model Input Output Context Max Out Provider

Prices are per 1M tokens in USD. A combo name (e.g. fast-cheap) can also be used as the model field.

Combos

Combos bundle several models behind one name with automatic fallback / round-robin routing — use the combo name as the model field. Currently configured:

Usage & Billing

Track spend and consumption per key. All endpoints below require the API key.

Endpoint Method Description
/v1/balanceGETCurrent account balance
/v1/usage?month=YYYY-MMGETMonthly usage with per-model breakdown
/v1/usage/daily?days=7GETDaily usage for the last N days (default 7)
/v1/usage/hourlyGETHourly usage for the last 24 hours
/v1/usage/timeseriesGETMulti-dimension time series: granularity=hour|day|week|month, period, group_by=model|provider|combo
/v1/billing?month=YYYY-MMGETBilling detail: usage, costs, tier discount, quota, balance
/v1/billing/statementGETMonthly statement summary
/v1/transactions?type=all&days=30GETTransaction history (type, days)
Example
bash
curl https://api.silkgateway.ai/v1/balance \
  -H "Authorization: Bearer sk-your-key"

curl "https://api.silkgateway.ai/v1/usage?month=2026-09" \
  -H "Authorization: Bearer sk-your-key"

curl "https://api.silkgateway.ai/v1/billing?month=2026-09" \
  -H "Authorization: Bearer sk-your-key"
Response
json
# GET /v1/balance
{ "balance": 10.5, "currency": "USD" }

# GET /v1/billing?month=2026-09
{
  "month": "2026-09",
  "tier": "pro",
  "usage": { "requests": 150, "promptTokens": 30000, "completionTokens": 15000, "totalTokens": 45000 },
  "costs": { "subtotal": 0.0126, "discount": 0.00126, "total": 0.01134 },
  "quota": { "free": 1000000, "used": 45000, "remaining": 955000 },
  "balance": 10.5
}
⚠️ Top-ups are handled by the SilkGateway team — there is no self-service top-up endpoint. Contact [email protected] to add balance.

Errors & Rate Limits

Errors are returned as JSON with an error message. Rate-limit responses include reset information so clients can back off precisely.

Status Meaning
400Bad request — malformed JSON, missing messages, unknown model, or input over the 1M-token limit
401Authentication failed — missing or invalid API key
402Insufficient balance or free quota exhausted
404Unknown endpoint
429Rate limited — your key exceeded its tier limit; respect Retry-After / X-RateLimit-Reset
503All subscription sources unavailable — the gateway could not reach any provider for the model; a Retry-After header is included

Rate limits by tier

Tier Rate limit
Free10 requests / min
Pro200 requests / min
Enterprise2000 requests / min

Response headers

Header Description
X-Request-IdUnique request ID — quote it in support requests
X-RateLimit-LimitRequests per minute allowed for your tier
X-RateLimit-RemainingRequests remaining in the current window
X-RateLimit-ResetUnix timestamp when the window resets
X-RTK-SavedRTK compression stats for this request, e.g. 1234bytes(15%)
Retry-AfterSeconds to wait before retrying (429 / 503)
Error example
json
# HTTP 429
{
  "error": "Rate limit exceeded",
  "limit": 10,
  "reset_at": 1760000000
}
💡 Upstream 429/5xx is absorbed by multi-subscription failover before the first byte reaches you — a 429/503 you receive means your own key was throttled or all sources are down. See Advanced.

Advanced

What the gateway does for you automatically.

Multi-subscription aggregation
One model name can be backed by multiple subscription sources (providers), ordered by priority. On 429, 5xx or credential failure the gateway switches to the next source before the first byte is streamed — your users never notice. Within a source, a key pool rotates API keys with exponential backoff.
Automatic model discovery
Admins pull the upstream /models list into the gateway config with one click; new models become routable instantly and custom prices are preserved. The /v1/models list you see is always current.
1M in · 128K out by default
Inputs up to ~1M tokens are accepted. When max_tokens is omitted the gateway fills 128000; if a model caps output lower, it transparently removes the cap and retries once — no client change needed.
RTK token saver
Tool outputs (git diff, grep, build logs…) are compressed before forwarding — typically 20–40% input token savings. Stats come back in the X-RTK-Saved header; disable per request with X-RTK: off.
Disable RTK for one request
bash
curl https://api.silkgateway.ai/v1/chat/completions \
  -H "Authorization: Bearer sk-your-key" \
  -H "X-RTK: off" \
  -H "Content-Type: application/json" \
  -d '{"model":"deepseek-chat","messages":[{"role":"user","content":"Hello!"}]}'