How to Use the OpenRouter API to Access GPT, Claude, Gemini & More (2026 Guide)

One key · 400+ models · routing layers · six-step setup · curl/Python/Node · streaming & fallback · BYOK pricing

OpenRouter API guide: unified access to GPT, Claude, and Gemini

If you are juggling separate API keys for OpenAI, Anthropic, and Google, each with different SDKs, rate limits, and billing dashboards, OpenRouter collapses that sprawl into a single OpenAI-compatible endpoint. This 2026 guide explains what OpenRouter actually does under the hood, walks through a six-step API key setup, ships copy-paste examples in curl, Python, Node.js, and the OpenAI SDK (including streaming and fallback), compares OpenRouter vs direct vendor APIs, covers pricing, BYOK, and free-tier models, and closes with an English SEO checklist for low-traffic locales plus why long-running Agents still belong on a 24/7 Mac Mini M4 rental.

01

What OpenRouter is and how its three routing layers work

OpenRouter is a unified LLM gateway: one API key, one base URL, and access to 400+ models from OpenAI, Anthropic, Google, Meta, DeepSeek, Mistral, xAI, and dozens of open-weight providers. It speaks the OpenAI Chat Completions API format, so most existing code works by changing two lines — base_url and model.

Think of OpenRouter as a smart proxy sitting between your application and upstream inference providers. When you send a request, three routing layers decide where it lands and what happens if something fails.

Layer 1: Model selection (what you ask for)

You specify a model ID in the request body — for example anthropic/claude-sonnet-4, openai/gpt-5, or google/gemini-2.5-pro-preview. OpenRouter maintains a live catalog at openrouter.ai/models with per-model pricing, context limits, and modality support (text, vision, tools).

Layer 2: Provider routing (who serves it)

Many models have multiple upstream providers — the same meta-llama/llama-3.3-70b-instruct might be served by Together, Fireworks, or DeepInfra. OpenRouter picks the best available provider based on latency, price tier, and current capacity. You can override this with the provider field or route through BYOK (Bring Your Own Key) to bill directly with your vendor account.

Layer 3: Fallback and load balancing (what happens on failure)

When a provider returns a 429, 502, or timeout, OpenRouter can automatically retry on an alternate provider or fall back to a secondary model you define. This is the feature that turns a brittle single-vendor integration into production-grade infrastructure — especially for Agent workloads that cannot afford a hard stop mid-task.

OpenRouter does not train on your API traffic by default. For regulated workloads, pair BYOK routing with spend caps and key rotation — the same hygiene you would apply to any direct vendor key.

OpenRouter also publishes live usage rankings at openrouter.ai/rankings, showing which models developers actually run in production. That data complements this API guide — see our June 2026 rankings breakdown for volume vs quality analysis.

02

Five reasons to use OpenRouter — and when to skip it

Five reasons developers switch to OpenRouter in 2026

  • One key for every vendor: Stop managing five billing dashboards. OpenRouter consolidates GPT, Claude, Gemini, DeepSeek, and open models behind a single API key and invoice.
  • Drop-in OpenAI SDK compatibility: Change base_url to https://openrouter.ai/api/v1 and swap the model string. Existing LangChain, Cursor, and OpenClaw configs often need zero refactor.
  • Automatic fallback: Define a primary model and a backup chain. When Claude is rate-limited, route to Sonnet, then DeepSeek V4 Flash, without custom retry logic in your app.
  • Price transparency: OpenRouter lists per-token rates for every model side by side. Flash-tier Chinese models run at roughly 1/8 the cost of Claude Opus — a gap that matters at Agent scale.
  • Model agility: The 2026 leaderboard reshuffles every quarter. With OpenRouter, promoting DeepSeek V4 Flash from experiment to production default is a one-line config change, not a vendor migration project.

When OpenRouter is not the right fit

  • Single-vendor enterprise contract: If you have negotiated Azure OpenAI or Google Vertex pricing with dedicated capacity, adding a proxy layer adds latency and may violate contract terms.
  • Provider-native features: OpenAI Assistants, Anthropic prompt caching at native endpoints, or Google context caching require direct API access.
  • Strict data residency: Some regulated industries require inference within a specific cloud region. Verify OpenRouter provider routing or use BYOK with a compliant upstream.
  • Ultra-low-latency HFT-style workloads: Every proxy hop adds milliseconds. Direct vendor APIs with dedicated endpoints win when latency is the primary metric.

OpenRouter vs direct vendor API

DimensionOpenRouterDirect vendor API
API keys neededOne OpenRouter key (or BYOK per vendor)One key per vendor (OpenAI, Anthropic, Google, etc.)
SDK compatibilityOpenAI Chat Completions format (universal)Vendor-specific SDKs and endpoint shapes
Model switchingChange model field in one requestNew SDK init, new billing account, new rate limits
Fallback on 429/502Built-in provider retry and model fallback chainsCustom retry logic per vendor
PricingListed per-model rates; BYOK avoids markupVendor list price; enterprise discounts via sales
Free modelsOwl Alpha, Nemotron 3 Super, and others at $0Limited free tiers per vendor (Gemini free, Claude trial)
Latency overhead~20–80 ms proxy hop (varies by region)Direct to vendor edge; lowest possible
ObservabilityUnified dashboard: spend, tokens, model mixSeparate dashboards per vendor
Best forMulti-model Agents, startups, cost optimizationSingle-vendor enterprise, native feature needs
03

Six-step runbook: from zero to your first API call

This runbook gets you from account creation to a verified production call in under fifteen minutes. Follow every step before wiring OpenRouter into an Agent daemon or CI pipeline.

  1. 01

    Create an account: Go to openrouter.ai and sign up with email or GitHub. New accounts receive a small credit for testing — enough for dozens of Sonnet calls or thousands of Flash-tier tokens.

  2. 02

    Generate an API key: Navigate to Keys in the dashboard. Create a key with a descriptive name (e.g. prod-agent-v1). Copy it immediately — OpenRouter shows the full key only once.

  3. 03

    Set a spend limit: Under Settings, configure a monthly budget cap and email alerts at 50%, 80%, and 100%. For Agent workloads, start with $50/month and scale after measuring token burn on your prompt set.

  4. 04

    Store the key securely: Never commit keys to git. Use environment variables (OPENROUTER_API_KEY), macOS Keychain, or your CI secret store. Rotate keys monthly in production.

  5. 05

    Verify with curl: Run the curl example in Section 04 below. A 200 response with a choices[0].message.content field confirms your key, routing, and model ID are correct.

  6. 06

    Wire into your stack: Point your OpenAI SDK, LangChain, or Agent framework at https://openrouter.ai/api/v1. Add HTTP-Referer and X-Title headers so your app appears in OpenRouter analytics. Deploy the daemon on a host that stays awake — see Section 06 for Mac Mini guidance.

!

Security note: Treat OpenRouter keys like production database credentials. If a key leaks, revoke it in the dashboard immediately and audit recent spend. OpenRouter supports per-key rate limits — use them for public-facing endpoints.

04

Code examples: curl, Python, Node.js, OpenAI SDK, streaming, fallback, and model listing

All examples use the same endpoint: https://openrouter.ai/api/v1/chat/completions. Replace YOUR_KEY with your API key and pick any model from the catalog.

curl — minimal chat completion

bash · curl
curl https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -H "HTTP-Referer: https://your-app.com" \
  -H "X-Title: Your App Name" \
  -d '{
    "model": "anthropic/claude-sonnet-4",
    "messages": [{"role": "user", "content": "Explain OpenRouter in one sentence."}]
  }'

Python — using the OpenAI SDK

python · openai sdk
from openai import OpenAI

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="YOUR_KEY",
)

response = client.chat.completions.create(
    model="deepseek/deepseek-chat-v3-0324",
    messages=[{"role": "user", "content": "Write a Python hello world."}],
    extra_headers={
        "HTTP-Referer": "https://your-app.com",
        "X-Title": "Your App Name",
    },
)
print(response.choices[0].message.content)

Node.js — fetch API

javascript · node fetch
const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,
    "Content-Type": "application/json",
    "HTTP-Referer": "https://your-app.com",
    "X-Title": "Your App Name",
  },
  body: JSON.stringify({
    model: "google/gemini-2.5-pro-preview",
    messages: [{ role: "user", content: "Summarize REST vs GraphQL." }],
  }),
});
const data = await res.json();
console.log(data.choices[0].message.content);

OpenAI SDK — drop-in migration from direct OpenAI

python · openai sdk migration
from openai import OpenAI

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="YOUR_KEY",
)

response = client.chat.completions.create(
    model="openai/gpt-5",
    messages=[{"role": "user", "content": "Compare GPT-5 and Claude Sonnet 4."}],
    tools=[{
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get weather for a city",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
            },
        },
    }],
)
print(response.choices[0].message)

Streaming responses

python · streaming
from openai import OpenAI

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="YOUR_KEY",
)

stream = client.chat.completions.create(
    model="anthropic/claude-sonnet-4",
    messages=[{"role": "user", "content": "Stream this response token by token."}],
    stream=True,
)

for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)

Fallback routing with model arrays

json · fallback models
{
  "model": "anthropic/claude-sonnet-4",
  "models": [
    "anthropic/claude-sonnet-4",
    "deepseek/deepseek-chat-v3-0324",
    "google/gemini-2.5-flash-preview"
  ],
  "messages": [{"role": "user", "content": "Handle this with automatic fallback."}],
  "route": "fallback"
}

When you pass a models array with "route": "fallback", OpenRouter tries each model in order until one succeeds. This is the simplest production pattern for Agent pipelines that cannot tolerate a single point of failure. For gateway-level routing with budget caps, see our OpenClaw multi-model routing guide.

Listing available models programmatically

bash · list models
curl https://openrouter.ai/api/v1/models \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" | jq '.data[] | {id, pricing}'

The models endpoint returns every available model with pricing, context length, and supported modalities. Cache this response in your app and refresh daily — new models appear weekly in mid-2026.

05

Pricing, BYOK, free tier, hard data, and English SEO for low-traffic locales

How OpenRouter pricing works

OpenRouter charges per token at the rate listed for each model. There is no monthly platform fee. Standard routes pass through upstream list pricing — OpenRouter does not add a hidden markup on top of vendor rates. You pay only for tokens consumed.

Model (July 2026)Input $/MOutput $/MContextNotes
DeepSeek V4 Flash~0.10~0.401MBest price-performance for high-frequency coding
Claude Sonnet 43.0015.00200KBalanced production default
Claude Opus 415.0075.00200KLong-horizon agents, hardest reasoning
GPT-55.0015.00128KStrong tool calling and ecosystem
Gemini 2.5 Pro1.2510.001M+Multimodal, long context
Owl Alpha0.000.001.05MFree tier; do not send secrets

BYOK (Bring Your Own Key)

BYOK lets you connect your existing OpenAI, Anthropic, or Google API keys to OpenRouter. Requests route through OpenRouter infrastructure but bill directly to your vendor account. OpenRouter charges a small platform fee (typically 5% of upstream cost) for routing, observability, and fallback. BYOK is ideal when you already have enterprise pricing with a vendor but want unified routing and fallback across multiple providers.

Free-tier models and credits

OpenRouter hosts several models at $0 list price — including Owl Alpha and Nemotron 3 Super. New accounts also receive starter credits. Free models are excellent for prototyping and draft-tier Agent tasks, but they may log prompts for model improvement. Never route regulated data, customer PII, or production secrets through free-tier models.

Hard data you can cite in architecture reviews

  • Model count: 400+ models across 60+ providers on OpenRouter as of July 2026
  • Price gap: DeepSeek V4 Flash at ~$0.10/M input vs Claude Opus 4 at $15/M — roughly 150x difference on input tokens
  • Traffic signal: DeepSeek holds ~17.6% of OpenRouter weekly token share; Chinese open models collectively exceed 60%
  • Latency overhead: OpenRouter proxy adds ~20–80 ms depending on region; negligible for Agent tasks, measurable for real-time chat
  • Fallback value: Teams report 40–60% fewer hard failures after enabling model fallback chains vs single-vendor routing
  • Agent call mix: Anthropic's 2026 State of AI Agents report shows ~44% of Claude API calls are math and computer-use tasks — the workloads that benefit most from cost-tier routing

English SEO checklist when EN traffic is low

VpsMesh publishes in eight languages. English pages often underperform Chinese counterparts on raw traffic — but they matter for global discoverability, backlink equity, and developer trust. If your English blog posts sit at low impressions in Google Search Console, run through this checklist before blaming content quality.

  1. 01

    Google Search Console: Verify the /en/ property separately. Check Coverage for crawl errors, inspect URL for canonical mismatches, and review Performance filtered to /en/blog/ paths. Low impressions with zero clicks often mean indexing lag, not bad content.

  2. 02

    hreflang tags: Every English article needs reciprocal hreflang links to zh, ja, ko, de, fr, ru, and zh-Hant versions. Missing or one-way hreflang is the most common reason Google serves the Chinese URL to English queries.

  3. 03

    CDN and WAF tuning: Ensure Cloudflare or your CDN does not geo-block or challenge-captcha US/EU crawlers. Bot Fight Mode set to aggressive can silently drop Googlebot on new /en/ paths.

  4. 04

    Localization, not translation: English pages must be native rewrites with English search intent — "OpenRouter API tutorial" not a literal translation of Chinese keyword clusters. Title tags, H2s, and FAQ questions should match how English developers actually search.

  5. 05

    Internal linking from EN hub: Link new English posts from /en/blog/index.html and at least two related EN articles. Orphan pages in a low-traffic locale rarely rank.

  6. 06

    Structured data: Ship BlogPosting and FAQPage JSON-LD on every article. FAQ schema drives rich results for long-tail queries like "Is OpenRouter free" and "OpenRouter vs direct API."

i

Practical tip: After publishing, submit the English URL via GSC URL Inspection and request indexing. Pair with one contextual backlink from a related EN post — internal link equity matters more than keyword density for new /en/ paths.

06

After API routing works: host your Agent 24/7 on a Mac Mini

OpenRouter solves the inference vendor problem — one key, fallback chains, unified billing. It does not solve the host uptime problem. Agent daemons that call OpenRouter every few minutes need a machine that never sleeps, holds secrets in Keychain, and runs macOS-native tools like Claude Code, Xcode, and OpenClaw without Linux compatibility hacks.

The pattern we see in production: developers wire OpenRouter in an afternoon, then lose overnight Agent runs when a laptop closes or a free-tier cloud VM gets preempted. Linux VPS works for pure API scripts with no macOS dependency. Stacks mixing Claude Code + OpenClaw + iOS CI pay double integration tax on Linux — Metal gaps, Keychain workarounds, and Xcode absence add weeks of glue code.

VpsMesh Mac Mini M4 cloud rental bundles 24/7 uptime, remote KVM, launchd daemon supervision, and native macOS paths into predictable monthly OpEx. Point your OpenRouter config at the rental, store keys in Keychain, and let Agents run while you review diffs locally. One month is enough to validate routing, measure token burn, and confirm daemon stability before committing to a longer term.

See Mac Mini M4 rental pricing for plan comparison and help center for deployment steps, SSH setup, and daemon hardening. For multi-model gateway patterns on the same host, read our OpenClaw routing guide and persistent Agent setup walkthrough.

FAQ

Six questions developers ask before switching to OpenRouter

OpenRouter has no monthly platform fee. You pay per token at listed model rates, or $0 on free-tier models like Owl Alpha. New accounts receive starter credits for testing. Production Agent workloads should use paid routes with budget caps configured in the dashboard.

On standard routes, OpenRouter passes through upstream list pricing with no hidden markup. BYOK routes bill you directly by the vendor; OpenRouter charges a small platform fee (typically ~5%) for routing and observability. Compare rates side by side at openrouter.ai/models.

Worth it when you need multi-vendor access, automatic fallback, unified billing, or OpenAI SDK drop-in. Skip it when you have a single-vendor enterprise contract, need provider-native features (Assistants, prompt caching), or require inference in a specific cloud region without proxy hops.

400+ models from OpenAI, Anthropic, Google, Meta, DeepSeek, Mistral, xAI, and others. Use GET /api/v1/models or browse at openrouter.ai/models. Model IDs follow vendor/model-name format — e.g. anthropic/claude-sonnet-4, openai/gpt-5, google/gemini-2.5-pro-preview.

OpenRouter is SOC 2 Type II certified and does not train on API traffic by default. Route regulated data through BYOK or self-hosted open models. Rotate keys monthly, set per-key rate limits, and never commit secrets to git. Free-tier models may log prompts — keep production secrets on paid routes only.

Install the openai Python package, set base_url="https://openrouter.ai/api/v1" and api_key to your OpenRouter key. Pass any supported model ID in the model field. Add HTTP-Referer and X-Title headers via extra_headers. Full example in Section 04 above.