AI Agent 2026.07.24

OpenRouter API Tutorial: Step-by-Step Guide to GPT, Claude & Gemini (2026 Complete Guide)

TL;DR: If you need GPT-4o, Claude 3.5, Gemini, DeepSeek, and Qwen in the same agent stack but do not want five vendor accounts, five SDKs, and five billing dashboards, OpenRouter is the fastest path: one API key, one OpenAI-compatible endpoint, and access to 70+ providers and 400+ models.

This guide is for developers and tech leads shipping production agents. You will get: ① how OpenRouter's dual-layer routing works and how it differs from calling OpenAI or Anthropic directly; ② a six-step integration checklist with curl, Python, Node, OpenAI SDK, streaming, and fallback code; ③ pricing, BYOK, and free-tier hard numbers; ④ an honest "when NOT to use it" section; ⑤ an English traffic diagnosis checklist, bilingual SEO strategy, and hreflang/sitemap/schema guidance. For earlier ranking context, see our June 2026 OpenRouter rankings breakdown.

01 What Is OpenRouter? Unified Endpoint and Dual-Layer Routing

OpenRouter is a unified LLM API aggregation layer. You use one API key and one OpenAI-compatible endpoint to reach models from OpenAI, Anthropic, Google, Meta, DeepSeek, and dozens of other vendors—without maintaining separate SDK integrations for each.

  • Unified endpoint: https://openrouter.ai/api/v1/chat/completions
  • Authentication: Authorization: Bearer $OPENROUTER_API_KEY
  • Protocol: OpenAI Chat Completions format—existing OpenAI SDK code typically needs only a base_url and api_key swap
  • Model naming: provider/model slugs such as openai/gpt-4o, anthropic/claude-3.5-sonnet, google/gemini-2.5-pro, deepseek/deepseek-chat

OpenRouter makes two independent routing decisions internally. Understanding both is key to predicting availability and cost:

OpenRouter dual-layer routing decisions
Layer What it decides Control field
Model routing Which model answers the request model or openrouter/auto
Provider routing Which datacenter handles the same model slug provider object; default weighted by inverse price squared
  • Automatic failover: When the primary provider rate-limits or errors, OpenRouter can switch to the next available provider or fallback model via the models array—no custom circuit breaker required on your side.
  • Free models: 25+ free models; roughly 50 requests/day without a top-up, about 1,000 requests/day (20/min) after adding at least $10 in credits.
  • Pricing model: Token rates pass through at provider list price with no markup; credit purchases incur a 5.5% fee (minimum $0.80); crypto adds another 5%. BYOK mode is free for the first 1 million requests/month, then 5% on the overage equivalent.

OpenRouter does not replace official SDKs. It sits between multi-model convenience and direct vendor access—the comparison tables below clarify when each path wins.

02 OpenRouter vs Direct OpenAI / Anthropic API: What's the Difference?

  • Pain point one: vendor account sprawl. Direct integration means separate sign-ups, API keys, billing, and audit trails for OpenAI, Anthropic, Google, and others.
  • Pain point two: switching models means switching integration layers. Message formats, streaming protocols, and error codes differ across vendors—agent frameworks cannot swap models with a single string change.
  • Pain point three: single-provider rate limits take down production. A 429 or 5xx from one vendor becomes a user-facing failure unless you built retry and routing logic yourself.
  • Pain point four: cost visibility is fragmented. Usage spread across five dashboards makes unified TTFT, throughput, and spend analysis nearly impossible.
OpenRouter vs direct vendor APIs
Dimension OpenRouter Direct vendor API
Integration cost Change base_url + api_key; one codebase for all models Separate SDK, key, and billing per vendor
Failover Built-in provider and model fallback Custom retry logic, key pools, routing layer
Latency Gateway adds roughly 10–80 ms per hop Lower; direct to provider datacenter
Exclusive features Common Chat Completions subset Batch API, Assistants, Prompt Caching, Vertex toolchain, etc.
Compliance Traffic passes through a US third-party gateway Regional residency and enterprise contracts available
Fee structure Provider token rate + 5.5% credit fee or 5% BYOK overage No middle-layer fee; enterprise discounts at scale

Preview: choose OpenRouter for multi-model A/B, moderate volume, and built-in fallback. Choose direct APIs for single flagship models at very high volume, minimum latency, or strict data residency—details in the next section.

03 Five Core Advantages of OpenRouter (Including When NOT to Use It)

  • Advantage one: one key unlocks every model. Switch models by changing the model string—no vendor adapter layer rewrite.
  • Advantage two: cross-provider automatic failover. Configure models: ["anthropic/claude-3.5-sonnet", "openai/gpt-4o", "google/gemini-2.5-pro"] and OpenRouter tries each in order when the primary fails.
  • Advantage three: unified billing and usage analytics. One dashboard for token counts, cost, TTFT, and throughput across all models.
  • Advantage four: no token markup. OpenRouter's FAQ confirms list-price pass-through; the real cost is the 5.5% credit fee. BYOK reduces that for higher volume.
  • Advantage five: clear use-case boundary. Ideal for rapid prototyping, model comparison, monthly spend under a few thousand dollars, and running the same prompt framework across the market.

When NOT to use OpenRouter (an honest E-E-A-T balance):

  • Single model, monthly spend above tens of thousands of dollars—the 5.5% credit fee justifies building direct integrations
  • You need Anthropic Prompt Caching, OpenAI Batch/Assistants, or Google Vertex-specific tooling
  • Latency-sensitive workloads where an extra 10–80 ms gateway hop is unacceptable
  • Data compliance or residency rules that forbid routing through a US third-party middle layer

Documenting when NOT to use it is not discouragement—it captures high-intent queries like OpenRouter vs direct API and is OpenRouter worth it, and signals credibility to AI search summaries.

04 Step-by-Step: Integrate OpenRouter API in Six Steps

  1. Create an account: Visit openrouter.ai and sign up with GitHub or email.
  2. Generate an API key: Create keys on the Keys page; split keys by project in production and set spend limits.
  3. Set environment variables: export OPENROUTER_API_KEY="sk-or-..."—never commit keys to Git.
  4. Send your first request: Use the curl or OpenAI SDK examples below and confirm a 200 response with the expected model ID.
  5. List available models: curl https://openrouter.ai/api/v1/models -H "Authorization: Bearer $OPENROUTER_API_KEY" and verify your target slug exists.
  6. Deploy to production: Configure fallback chains, enable streaming, add HTTP-Referer and X-Title headers (OpenRouter recommends these for leaderboard attribution), and inject keys into a 24/7 agent host—not a personal laptop.

05 Code Examples: curl, Python, Node.js, OpenAI SDK, Streaming, and Fallback

These examples cover both "how to" and "code example" search intent. Each runs as-is after you swap in your key.

cURL direct request

curl-openrouter.sh
curl https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-3.5-sonnet",
    "messages": [{"role": "user", "content": "Explain quantum computing in one sentence"}]
  }'

Python (requests, native)

openrouter_requests.py
import requests, os
r = requests.post(
  "https://openrouter.ai/api/v1/chat/completions",
  headers={"Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}"},
  json={"model": "google/gemini-2.5-pro",
        "messages": [{"role": "user", "content": "Write a quicksort in Python"}]}
)
print(r.json()["choices"][0]["message"]["content"])

Python (OpenAI SDK zero-cost migration)

openrouter_openai_sdk.py
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": "Hello!"}],
  extra_headers={"HTTP-Referer": "https://jexcloud.com", "X-Title": "JEXCLOUD Demo"},
)

Node.js (OpenAI SDK)

openrouter.mjs
import OpenAI from "openai";
const openai = new OpenAI({
  baseURL: "https://openrouter.ai/api/v1",
  apiKey: process.env.OPENROUTER_API_KEY,
});
const completion = await openai.chat.completions.create({
  model: "deepseek/deepseek-chat",
  messages: [{ role: "user", content: "Explain OpenRouter in one sentence" }],
});

Streaming response

stream.mjs
const stream = await openai.chat.completions.create({
  model: "anthropic/claude-3.5-sonnet", stream: true,
  messages: [{ role: "user", content: "Write a short poem about autumn" }],
});
for await (const chunk of stream) {
  const c = chunk.choices[0]?.delta?.content;
  if (c) process.stdout.write(c);
}

Multi-model fallback JSON body

fallback-body.json
{
  "model": "anthropic/claude-3.5-sonnet",
  "models": ["anthropic/claude-3.5-sonnet", "openai/gpt-4o", "google/gemini-2.5-pro"],
  "route": "fallback",
  "messages": [{"role": "user", "content": "Hello"}]
}

06 Pricing, Free Tier, and Citeable Hard Data

  • Provider scale: 70+ providers, 400+ models (per official docs—verify slugs via /models before routing).
  • Free tier: 25+ free models; roughly 50 requests/day without a top-up, about 1,000 requests/day and 20 requests/min after adding at least $10.
  • Fees: 5.5% on credit purchases (minimum $0.80); crypto adds 5%; BYOK free for the first 1 million requests/month.
  • Latency cost: Gateway layer typically adds 10–80 ms—benchmark TTFT-sensitive paths before committing.
  • Cost control: Default routing to Flash or low-cost models; escalate to Opus only for high-risk steps; enable project-level spend limits and weekly export.

OpenRouter does not mark up token list prices—that is the key difference from most aggregators. The real math is credit fees + gateway latency + compliance boundaries, not "model price times a mystery multiplier."

07 Frequently Asked Questions

Is OpenRouter free? Yes, partially—25+ free models with daily limits. Paid models charge provider token rates; credit top-ups incur 5.5%.

What models does OpenRouter support? 400+ models across 70+ providers using vendor/model slugs. Pull the full list from /api/v1/models.

OpenRouter vs Claude direct API — which is better? OpenRouter for multi-model workloads and failover; direct Anthropic for exclusive features and very high single-model volume.

How much does OpenRouter cost per month? Entirely usage-dependent—Flash-tier agents may run tens of dollars; an all-Opus pipeline can reach thousands. Check the dashboard for estimates.

Is OpenRouter safe? Does it leak data? Traffic routes through OpenRouter's gateway. Evaluate BYOK, direct APIs, or private deployment for sensitive data.

How do I call OpenRouter from Python? See Section 05 for requests and OpenAI SDK examples—both work out of the box.

08 Why Your English Pages Get Zero Traffic: Diagnosis Checklist

Crawl and index layer (P0, most often overlooked):

  • CDN/WAF blocking Googlebot—test with Google Search Console URL Inspection, not just a browser visit
  • Missing or incorrect hreflang tags causing Google to canonicalize only the Chinese version
  • robots.txt or noindex accidentally blocking /en/ paths
  • sitemap.xml not listing language variants or missing alternate annotations
  • Pure CSR shell HTML where crawlers cannot read body content

Content layer:

  • English pages are literal translations that miss native queries like OpenRouter vs OpenAI API and is OpenRouter worth it
  • No independent English keyword research; weak E-E-A-T signals (no author attribution, no measured data)

Authority and backlink layer:

  • Chinese distribution on Juejin, Zhihu, and V2EX while English pages have zero exposure on Reddit, Hacker News, or dev.to
  • New domains need time, backlinks, and consistent publishing before crawl frequency improves

Recommended fix order (highest ROI first):

  1. GSC: confirm English URLs are crawled and indexed
  2. Audit CDN/WAF rules for Googlebot blocks
  3. Add hreflang, canonical, and language-specific sitemaps
  4. Rewrite 3–5 priority English articles (not translate) aligned to native keywords
  5. First English distribution push on dev.to, Reddit, and Hacker News

09 Chinese SEO vs English SEO: Keyword Matrix and Localization

Chinese core terms: OpenRouter, OpenRouter API, OpenRouter tutorial; mid-tail: how to use OpenRouter, difference from OpenAI, free models, pricing; long-tail FAQ: how to get API key, availability in China, Python integration.

Chinese title signals: complete guide, step-by-step tutorial, from zero to one, 2026 latest—core terms must appear verbatim in title, intro, and H2 headings for Baidu literal matching plus AI search semantic clusters.

English core terms: OpenRouter API, tutorial, integration; comparison: OpenRouter vs OpenAI API, is OpenRouter worth it; how-to: OpenRouter Python example, fallback routing, streaming response.

English title signals: The Complete Guide, Step-by-Step, For Beginners, Honest Review—avoid stacking Ultimate + Complete + Beginner; English readers tolerate clickbait less.

Localization principle: Chinese and English versions should not be simple translations. Share code examples, but rewrite titles, intros, H2 headings, and FAQ questions for each language's search intent. English intros lead with a TL;DR block; include a "when NOT to use it" section for balance. Meta descriptions: 150–160 characters in English with step-by-step and honest trust signals.

10 Bilingual Site Architecture, Schema, and Distribution Channels

Recommended URL structure (subdirectory, shared domain authority):

url-pattern.txt
https://jexcloud.com/zh/blog/2026-0724-openrouter-api-tutorial-gpt-claude-gemini-guide.html
https://jexcloud.com/en/blog/2026-0724-openrouter-api-tutorial-gpt-claude-gemini-guide.html

hreflang example (cross-reference in each language page head + x-default):

hreflang.html
<link rel="alternate" hreflang="zh-Hans" href="https://jexcloud.com/zh/blog/..." />
<link rel="alternate" hreflang="en" href="https://jexcloud.com/en/blog/..." />
<link rel="alternate" hreflang="x-default" href="https://jexcloud.com/en/blog/..." />

Each language page canonicalizes to itself. Sitemaps list separate <url> entries per language with xhtml:link alternate declarations.

Schema: This article includes BlogPosting and FAQPage JSON-LD in the head. Chinese FAQ questions use Chinese long-tail phrasing; English FAQ questions use native English phrasing.

Distribution channels: Chinese: Juejin, Zhihu, V2EX, CSDN, Baidu Search Console. English: dev.to (with canonical backlink), Hacker News, Reddit (r/LocalLLaMA and similar), Indie Hackers. X/Twitter works for bilingual thread summaries.

11 Action Checklist, Metrics Tracking, and JEXCLOUD Close

P0 (stop the bleeding this week): GSC crawl/index check for English URLs, audit CDN/WAF blocks, add hreflang/canonical/sitemap.

P1 (write and publish): Complete Chinese and English drafts (English as localized rewrite), embed target keywords, add Article and FAQPage schema.

P2 (distribute and track): Publish on Juejin/Zhihu plus dev.to/Reddit, submit language-specific sitemaps to GSC and Baidu, monitor impressions/CTR/rankings per path.

Metrics tracking: GSC filtered by /en/ vs /zh/—zero impressions means index problems, high impressions with low CTR means title problems. Umami or GA4 segmented by language for organic search and bounce rate. Monthly incognito spot-checks on 3–5 core terms.

Running OpenRouter agents on a personal Mac means the pipeline stops when the lid closes. Oversubscribed VPS hosts often lack official macOS; SSH jitter interrupts multi-step tool loops. Shared team machines make key rotation and CLI version drift a constant headache—these issues are unrelated to "how to call the API" but determine whether production agents actually stay up.

For teams that need 24/7 Cursor Agent, OpenClaw Gateway, and OpenRouter routing, JEXCLOUD multi-region bare-metal Mac hosts are the more stable layer: dedicated Apple Silicon, real macOS, 120-second provisioning, monthly elasticity. Model billing goes through OpenRouter; compute goes through bare metal—a clean separation. See the pricing page for specs and the help center for onboarding.