OPENROUTER API
ONE KEY
400+ MODELS.

OpenRouter unified API gateway connecting GPT Claude Gemini and 400 LLM models

Lead: If you are juggling separate API keys for OpenAI, Anthropic, Google, and DeepSeek, you already know the pain: different SDKs, billing dashboards, rate limits, and failover logic scattered across five repos. OpenRouter solves that with one OpenAI-compatible endpoint and 400+ models behind a single key. This guide covers what OpenRouter is, a direct-API comparison table, five reasons developers switch, when to skip the gateway, a three-step key setup, production code in curl/Python/Node/OpenAI SDK, streaming and fallback config, pricing (free tier, 5.5% fee, BYOK), an English traffic diagnostic checklist, bilingual hreflang SEO architecture, distribution channels, P0/P1/P2 action items, metrics to track, and FAQ.

30-Second Read

What it isUnified LLM gateway: 70+ providers, 400+ models, OpenAI-compatible /v1 endpoint
Endpointhttps://openrouter.ai/api/v1/chat/completions
PricingNo token markup; 5.5% fee on credit top-ups; 25+ free models
Free tier50 req/day uncharged; 1,000/day after $10 credit purchase
Latency cost10-80ms routing overhead vs direct vendor API

1. What Is OpenRouter?

OpenRouter is a unified LLM API gateway. Instead of registering with OpenAI, Anthropic, Google, Meta, Mistral, and DeepSeek separately, you send all requests to a single OpenAI-compatible endpoint. OpenRouter handles authentication, provider selection, failover, and billing.

Core concepts:

  • Endpoint: https://openrouter.ai/api/v1 — drop-in replacement for OpenAI's base URL
  • Auth: One API key in the Authorization: Bearer header
  • Model naming: provider/model-id format — e.g. openai/gpt-4o, anthropic/claude-sonnet-4, google/gemini-2.5-pro
  • Compatibility: Works with curl, Python requests, Node fetch, and the official OpenAI SDK by changing only base_url and model

Routing Mechanism

LayerWhat it doesExample
Model routingYou specify the model ID; OpenRouter picks the best available providerdeepseek/deepseek-chat
Provider routingSame model may run on multiple hosts; OpenRouter routes by price, latency, uptimeDeepSeek via Fireworks vs DeepSeek direct
FallbackAutomatic retry on a backup model if primary returns 429/5xxPrimary Claude, fallback GPT-4o
Free models25+ models at $0; rate-limited by account tiermeta-llama/llama-3.3-70b-instruct:free

2. OpenRouter vs Direct API: Comparison Table

DimensionOpenRouterDirect vendor API
API keysOne key for all providersSeparate key per vendor
SDK changesChange base_url onlyVendor-specific SDKs or endpoints
Model switchingChange model string in one lineNew account, billing, rate limits per vendor
FailoverBuilt-in fallback models/providersCustom retry logic required
Token pricingProvider list price (no markup)Provider list price
Platform fee5.5% on credit purchasesNone
Latency+10-80ms routing overheadLowest possible (direct to vendor)
Vendor featuresSubset (no Assistants API, limited caching)Full feature set per vendor
ComplianceThird-party data routingDirect vendor DPA/BAA available
Free models25+ models, tiered daily limitsVendor-specific free tiers only

3. Five Reasons Developers Switch to OpenRouter

  1. One key, 400+ models. Prototype with GPT-4o, ship with DeepSeek V4 Flash, escalate to Claude Opus — all from the same integration. No re-auth, no new billing accounts.
  2. OpenAI SDK drop-in. Existing codebases that call openai.chat.completions.create() work by swapping two lines: base_url and model.
  3. Built-in failover. Agent loops hit 429s constantly. OpenRouter's provider routing and model fallback cut custom retry code from hundreds of lines to a JSON config block.
  4. Real usage data for model selection. OpenRouter publishes weekly token and dollar rankings — production ground truth, not benchmark leaderboard noise. See our June 2026 rankings breakdown for how developers actually route.
  5. Free tier for prototyping. 25+ free models with 50 requests/day (1,000/day after a $10 credit purchase) let you validate agent workflows before committing to paid inference.

4. When NOT to Use OpenRouter

OpenRouter is not always the right choice. Skip the gateway when:

  • Latency-sensitive real-time apps: The 10-80ms routing overhead matters for voice, live coding completions, or sub-100ms TTFT requirements.
  • Very high token volume: At millions of tokens per day, the 5.5% credit fee adds up. Direct vendor contracts or reserved capacity may be cheaper.
  • Strict compliance: HIPAA, SOC 2 Type II with vendor-specific DPAs, or data residency rules that prohibit third-party routing require direct API relationships.
  • Vendor-specific features: OpenAI Assistants, Anthropic prompt caching with guaranteed hit rates, Google Vertex grounding — these need the native SDK, not a gateway abstraction.

5. Step-by-Step: Get Your OpenRouter API Key

Step 1 — Register

Go to openrouter.ai and sign in with Google, GitHub, or email. No credit card required for free-tier models.

Step 2 — Create an API key

Navigate to Keys in the dashboard. Click Create Key, name it (e.g. prod-agent), and copy the key immediately. Store it in an environment variable — never commit to Git.

export OPENROUTER_API_KEY="sk-or-v1-xxxxxxxx"

Step 3 — Send your first request

Verify the key with a minimal curl call. You should receive a JSON response with choices[0].message.content.

6. Code Examples

6.1 curl

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

6.2 Python (requests)

import os, requests resp = requests.post( "https://openrouter.ai/api/v1/chat/completions", headers={ "Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}", "Content-Type": "application/json", }, json={ "model": "google/gemini-2.5-flash", "messages": [{"role": "user", "content": "Hello from Python"}], }, ) print(resp.json()["choices"][0]["message"]["content"])

6.3 Python (OpenAI SDK drop-in)

from openai import OpenAI client = OpenAI( base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"], ) completion = client.chat.completions.create( model="openai/gpt-4o", messages=[{"role": "user", "content": "Drop-in SDK test"}], ) print(completion.choices[0].message.content)

6.4 Node.js (OpenAI SDK)

import OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://openrouter.ai/api/v1", apiKey: process.env.OPENROUTER_API_KEY, }); const res = await client.chat.completions.create({ model: "deepseek/deepseek-chat", messages: [{ role: "user", content: "Node.js via OpenRouter" }], }); console.log(res.choices[0].message.content);

6.5 Streaming

from openai import OpenAI client = OpenAI( base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"], ) stream = client.chat.completions.create( model="anthropic/claude-sonnet-4", messages=[{"role": "user", "content": "Stream this response."}], stream=True, ) for chunk in stream: delta = chunk.choices[0].delta.content or "" print(delta, end="", flush=True)

6.6 Fallback configuration

{ "model": "anthropic/claude-sonnet-4", "models": [ "anthropic/claude-sonnet-4", "openai/gpt-4o", "google/gemini-2.5-flash" ], "messages": [{"role": "user", "content": "Agent task with failover"}] }

The models array tells OpenRouter to try each model in order if the previous returns an error or rate limit. This is the simplest production-grade failover pattern for agent loops.

6.7 List available models

curl -s https://openrouter.ai/api/v1/models \ -H "Authorization: Bearer $OPENROUTER_API_KEY" \ | python3 -m json.tool | head -80

7. Streaming, Fallback, and Cost Control

Streaming: Set "stream": true in the request body. OpenRouter passes SSE chunks identically to the OpenAI format. Use streaming for chat UIs and agent tool-call loops where time-to-first-token matters.

Fallback: Use the models array for model-level failover. For provider-level routing, OpenRouter auto-selects the cheapest/fastest provider unless you pin one via provider preferences in the dashboard.

Cost control: Set spend limits in the OpenRouter dashboard. Use cheaper models (DeepSeek V4 Flash, Gemini Flash) for drafts and reserve Claude Opus/GPT-4o for escalation. Monitor weekly spend in the Activity tab.

8. Pricing: Free Tier, 5.5% Fee, and BYOK

TierDetails
Free models25+ models at $0/token; 50 requests/day without purchase; 1,000/day after $10 credit top-up
Paid modelsProvider list price, no per-token markup
Platform fee5.5% on credit purchases (not on token usage itself)
BYOKBring Your Own Key from vendor; 1M free routed requests/month, then small overage fee

Example: $100 credit purchase costs $105.50 total. That $100 buys tokens at provider rates. At 10M tokens/day, the 5.5% fee becomes material — evaluate direct contracts.

9. English Page Traffic Diagnostic Checklist

If your English OpenRouter content gets low traffic while Chinese pages rank, run this diagnostic in order:

CategoryCheckFix
Crawl/indexURL in sitemap.xml?Submit via Search Console; verify robots.txt allows /en/blog/
Crawl/indexCanonical self-referencing?Each lang page canonicals to itself, not to zh
Crawl/indexhreflang reciprocal?All 8 lang versions link to each other bidirectionally
ContentTitle matches search intent?Use "OpenRouter API guide" not translated Chinese title
ContentMeta description 150-160 chars?Write native English summary, not machine translation
ContentH1 includes primary keyword?"OpenRouter API" visible in H1 and first 100 words
ContentCode blocks present?Google favors how-to pages with runnable examples
BacklinksInternal links from related posts?Link from rankings, Cursor, and agent routing articles
BacklinksExternal mentions?Share on HN, Reddit r/LocalLLaMA, Dev.to, X threads

10. English SEO Strategy

Keyword matrix

IntentPrimary keywordSupporting keywords
How-toOpenRouter API guidehow to use OpenRouter, OpenRouter tutorial 2026
ComparisonOpenRouter vs OpenAI APIOpenRouter vs direct API, OpenRouter alternative
CodeOpenRouter Python exampleOpenRouter Node.js, OpenRouter curl, OpenAI SDK OpenRouter
PricingOpenRouter pricingIs OpenRouter free, OpenRouter cost, OpenRouter BYOK
FeatureOpenRouter fallbackOpenRouter streaming, OpenRouter free models

Title and meta template

Title: [Primary keyword] + [year] + [scope] | MACGPU Blog

Meta: 150-160 chars; include primary keyword, one specific number, and a differentiator (fallback, free tier, or model count).

Localization vs translation

English pages must be independently written for English search intent. A literal translation of Chinese SEO copy misses queries like "OpenRouter vs OpenAI API" and "OpenRouter Python SDK." Write separate outlines per language; share only factual data (pricing, endpoints), not prose.

11. Bilingual Site Architecture: hreflang and Canonical

MACGPU runs 8 language directories under /frontend/{lang}/blog/. Each article gets a localized slug — not a shared filename across languages.

<link rel="canonical" href="https://macgpu.com/en/blog/2026-0724-openrouter-api-guide-gpt-claude-gemini.html" /> <link rel="alternate" hreflang="en" href="https://macgpu.com/en/blog/2026-0724-openrouter-api-guide-gpt-claude-gemini.html" /> <link rel="alternate" hreflang="zh-Hans" href="https://macgpu.com/zh/blog/2026-0724-openrouter-baomu-api-jiaocheng.html" /> <link rel="alternate" hreflang="x-default" href="https://macgpu.com/en/blog/2026-0724-openrouter-api-guide-gpt-claude-gemini.html" />

Rules: every language version links to all others; x-default points to English; each page canonicals to itself; sitemap.xml lists all 8 URLs with matching lastmod.

12. Distribution Channels

ChannelAudienceAction
Hacker NewsEnglish devsSubmit as "OpenRouter API Guide 2026" with code examples
Reddit r/LocalLLaMAMulti-model usersPost comparison table + free tier details
Dev.to / HashnodeHow-to searchersCross-post with canonical back to macgpu.com
X (Twitter)AI dev communityThread: 5 reasons + curl one-liner
Internal blog linksExisting MACGPU readersLink from rankings, Cursor, and agent routing posts
IndexNowBing/YandexPush URL after publish via index-now-push.js

13. Action Checklist: P0 / P1 / P2

PriorityTaskOwner
P0Publish all 8 language versions with hreflangContent
P0Add entry to blog-data.js in each lang directoryDev
P0Update sitemap.xml and push IndexNowDev
P0Validate BlogPosting + FAQPage JSON-LD in Rich Results TestSEO
P1Submit English URL to Google Search ConsoleSEO
P1Add internal links from 3+ related OpenRouter postsContent
P1Share on HN and r/LocalLLaMA within 48 hoursMarketing
P2Monitor GSC impressions for "OpenRouter API" queriesSEO
P2A/B test meta descriptions if CTR below 3%SEO
P2Refresh code examples when OpenRouter changes model IDsContent

14. Metrics to Track

  • Organic impressions: GSC queries containing "OpenRouter" — target 1,000/month within 90 days
  • CTR: Meta description click-through; benchmark 3-5% for how-to content
  • Avg position: Track "OpenRouter API guide," "OpenRouter Python," "OpenRouter pricing"
  • Internal link clicks: Matomo events on links to rankings and agent routing posts
  • Time on page: Target 4+ minutes for 30-min readTime articles
  • Lang split: Compare en vs zh traffic ratio; healthy bilingual site runs 40-60% en for dev topics

15. FAQ

Q: Is OpenRouter free?
A: 25+ free models with 50 requests/day at no charge. After a $10 credit purchase, free-model limits rise to 1,000/day. Paid models bill at provider list price.

Q: Does OpenRouter markup token prices?
A: No per-token markup. A 5.5% fee applies only to credit top-ups. BYOK users get 1M free routed requests/month.

Q: Is OpenRouter safe for production?
A: Widely used in agent stacks. Store keys server-side, set spend caps, and use BYOK or direct APIs for compliance-sensitive workloads.

Q: How is OpenRouter different from the OpenAI API?
A: OpenRouter is a multi-provider gateway. One endpoint, 400+ models. OpenAI API gives you only OpenAI models with native feature access.

Q: Can I use the OpenAI Python SDK?
A: Yes. Set base_url="https://openrouter.ai/api/v1" and pass your OpenRouter key. No other code changes needed.

Q: When should I skip OpenRouter?
A: Sub-10ms latency requirements, very high volume (5.5% fee adds up), strict compliance, or vendor-specific features like Assistants API.

16. Closing: OpenRouter Dev on Mac — Offload Agent Stress Tests to a Remote Node

OpenRouter integration works on any OS. But if you are running Cursor + Claude Code + OpenClaw with multi-model fallback chains, your primary Mac becomes the bottleneck: Docker sandboxes, agent loops, and long-context batch jobs compete for unified memory.

Practical split: keep Cursor review and light API calls on your laptop; offload agent stress tests, OpenRouter routing probes, and 24/7 Gateway cron jobs to a MACGPU remote Mac mini M4 node. SSH isolation, on-demand rental, Metal-native MLX validation on the side.