OpenRouter gives you one API key and one endpoint for 700+ models from OpenAI, Anthropic, Google, NVIDIA and many more. Because it speaks the OpenAI format, your existing Python code needs only a new base_url.
This tutorial goes deep on the code. You will make your first call, pick model ids and variants, control provider routing and fallbacks, stream, call tools, get strict JSON, and read the exact cost of every request.
- Endpoint:
https://openrouter.ai/api/v1with the officialopenaiPython SDK (3.65.0 checked on 5 Dec 2026). - Model ids:
author/model, plus suffixes like:free,:nitro,:floorand:exacto, or~author/family-latestaliases. - Routing: OpenRouter-only options (
provider,models) go inextra_body. - Cost: token prices are passed through with no markup. Buying credits costs a 5.5% fee (min $0.80) on the Standard plan.
- Free models: 20 requests per minute, and 50 per day (1,000 per day once you have bought at least 10 credits).
What the OpenRouter API Is and When to Use It
OpenRouter is a router that sits between your app and the model providers. You send one request, and it picks a healthy provider that serves the model you asked for. If one provider fails, it can retry on another.
If you want the big picture first (plans, the chat app, the model catalog), read my OpenRouter guide to pricing and free models. This post is the developer follow-up.
OpenRouter is a good fit when you want:
- Many models, one bill: test OpenAI, Anthropic, Google and open models without five accounts.
- Uptime: automatic provider failover plus your own model fallback list.
- Free prototyping: 25+ free models on the free plan, per the official pricing page.
- Cost control: every response reports its exact cost in credits.
It is less useful if you only ever call one vendor and need features that exist only in that vendor’s own API. In that case, the native SDK is simpler. See my OpenAI API Python tutorial for that path.
Note: OpenRouter announced on 19 August 2026 that it is joining Stripe. The announcement says your integration does not change, and the API in this guide is the current one.
Prerequisites and Setup
You need Python 3.10 or newer (the minimum for both the openai and openrouter packages on PyPI) and an OpenRouter account.
- Create an account. Sign up at openrouter.ai. The free plan already works for
:freemodels. - Create an API key. Open the Keys page in your account settings and create a key. You can set a credit limit on each key, which is a smart guard for test keys.
- Add credits (optional). Paid models need credits. Buying at least 10 credits also lifts your free-model limit from 50 to 1,000 requests per day.
- Save the key as an environment variable. On macOS or Linux run
export OPENROUTER_API_KEY="sk-or-...". On Windows PowerShell run$env:OPENROUTER_API_KEY="sk-or-...". - Install the SDK. Run
pip install openai. I checked version 3.65.0, released on 5 Dec 2026. - Run the first example below. If it prints a reply, you are ready.
Warning: never paste your key into code you commit. Read it from OPENROUTER_API_KEY, and set a per-key credit limit so a leaked key cannot drain your balance.
OpenRouter also ships its own type-safe Python SDK (pip install openrouter, version 1.3.250 on PyPI today). I use the OpenAI SDK here because most readers already have code built on it.
Your First Request in Python (and curl)
Point the OpenAI client at OpenRouter with base_url. The two attribution headers are optional. They only list your app on OpenRouter’s public rankings.
Example 1: Chat Completions with the OpenAI SDK
import os
from openai import OpenAI
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"],
default_headers={
"HTTP-Referer": "https://example.com", # optional
"X-OpenRouter-Title": "My Demo App", # optional
},
)
resp = client.chat.completions.create(
model="openai/gpt-6.2-sol",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what an API router does in 2 sentences."},
],
)
print(resp.choices[0].message.content)
print("Served by:", resp.model)
The model field in the response tells you which model actually answered. That matters later, when you use aliases or fallbacks.
The Responses API also works
OpenRouter’s own quickstart now leads with the /api/v1/responses endpoint. With the same client, it looks like this:
r = client.responses.create(
model="~openai/gpt-sol-latest",
input="What is the meaning of life?",
)
if r.status != "completed":
raise RuntimeError(r.error.message if r.error else r.status)
print(r.output_text)
Both endpoints are supported. I use Chat Completions for the rest of this post because it is what most existing apps and frameworks send. If you are new to the newer format, see my Responses API tutorial.
The same call with curl
curl https://openrouter.ai/api/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-d '{
"model": "openai/gpt-6.2-sol",
"messages": [{"role": "user", "content": "Say hello in 3 languages."}]
}'
Model IDs, Variants and Latest Aliases
Every model has a slug in the form author/model, for example openai/gpt-6.2-sol. You can copy it from the model page or list all slugs with GET /api/v1/models.

You can add a suffix to change how a request is served. Here is what each one does today, from the official model variants page:
| Suffix or form | What it does | Status |
|---|---|---|
:free |
Free entry with its own endpoints and rate limits | Active (only on models that list a free entry) |
:nitro |
Sorts providers by throughput and allows priority-tier endpoints | Active, works on any model |
:floor |
Sorts providers by price and allows flex-tier endpoints | Active, works on any model |
:exacto |
Sorts providers by tool-calling quality signals | Active, works on any model |
:batch |
Batch-priced version, served through the Batch API | Active |
:online |
Attached web results to the prompt | Deprecated: use the openrouter:web_search server tool |
:thinking |
Reasoning on by default | Deprecated: use the reasoning parameter |
~author/family-latest |
Alias that always points at the newest model in a family | Active, e.g. ~anthropic/claude-sonnet-latest |
Aliases are handy for chat apps, but they change under you. For tests and anything that must stay reproducible, pin a concrete slug. The alias also cannot roll back, so to downgrade you switch to a concrete slug.
Free Models and Their Rate Limits
Free models are real models with a $0 price. In December 2026 the most used ones include NVIDIA Nemotron 3 Ultra, Baidu ERNIE 5.5 Flash Preview and Nemotron 3.5 Super VL. The list changes often, so look it up in code instead of hard-coding it.
| Account state | Requests per minute | Requests per day |
|---|---|---|
| Bought less than 10 credits | 20 | 50 |
| Bought at least 10 credits | 20 | 1,000 |
| Paid models | No platform cap | Provider limits pass through |
This snippet lists free model ids, then calls the Free Models Router. openrouter/free picks a free model at random that supports what your request needs (tools, images, structured output).
import os, requests
from openai import OpenAI
models = requests.get("https://openrouter.ai/api/v1/models", timeout=30).json()["data"]
free_ids = [m["id"] for m in models if m["id"].endswith(":free")]
print(len(free_ids), "free models, e.g.", free_ids[:5])
client = OpenAI(base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"])
resp = client.chat.completions.create(
model="openrouter/free",
messages=[{"role": "user", "content": "Give me 3 names for a cat."}],
)
print(resp.model, "->", resp.choices[0].message.content)
Tip: some free endpoints keep prompts or may use them for training (the model page says so). Do not send private data to free models, and check your privacy settings if a free model returns “no endpoints found”.
Provider Routing and Model Fallbacks
One model is often served by several providers. By default, OpenRouter balances traffic by price, speed, latency, reliability and tool-call quality. It also keeps follow-up requests on the same provider while its prompt cache is warm.
The OpenAI SDK does not know OpenRouter’s extra fields, so you pass them through extra_body. The main provider fields are:
- order: list of provider slugs to try first, in order.
- allow_fallbacks:
trueby default. Setfalseto never leave your list. - only / ignore: allow or skip specific providers.
- sort:
"price","throughput"or"latency". - require_parameters: only use providers that support every parameter you sent.
- data_collection / zdr:
"deny"ortrueto keep traffic on no-collection or Zero Data Retention endpoints. - max_price: a hard price cap. The request fails if no provider meets it.
- quantizations: filter by
fp8,bf16,int8and so on.
Example 2: provider order plus a model fallback list
The models array is your second safety net. If the first model errors (downtime, rate limit, context too long, moderation), OpenRouter tries the next model. You pay the price of whichever model answered.
import os
from openai import OpenAI
client = OpenAI(base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"])
resp = client.chat.completions.create(
model="openai/gpt-6.2-sol",
messages=[{"role": "user", "content": "Summarise the CAP theorem."}],
extra_body={
"models": ["openai/gpt-6.2-sol", "~anthropic/claude-sonnet-latest"],
"provider": {
"sort": "throughput",
"data_collection": "deny",
"allow_fallbacks": True,
},
},
)
print("Answered by:", resp.model)
print(resp.choices[0].message.content)
Warning: if a :free model falls back to a paid one, you pay the paid price. To stay at $0, put only :free models in the list, or use openrouter/free on its own.
Prefer suffixes for quick wins: openai/gpt-6.2-sol:nitro for speed or :floor for the lowest price. OpenRouter rebuilt its default routing on 28 October 2026, and its release note says :floor keeps price-first routing.
Streaming Responses
Set stream=True and print tokens as they arrive. OpenRouter adds three quirks that are worth knowing:
- Keep-alive comments: lines like
: OPENROUTER PROCESSINGarrive while you wait. The SDK skips them for you. - Usage chunk: just before
[DONE], an extra chunk carries theusageobject with an empty delta. - Errors mid-stream: once tokens start, an error arrives as a chunk with
finish_reason: "error", not as an HTTP status. The OpenAI SDK raises it as anAPIError.
Example 3: stream and read the cost at the end
import os
from openai import OpenAI, APIError
client = OpenAI(base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"])
stream = client.chat.completions.create(
model="openai/gpt-6.2-sol",
messages=[{"role": "user", "content": "Write a haiku about routers."}],
stream=True,
)
usage = None
try:
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage:
usage = chunk.usage
except APIError as e:
print("Stream failed:", e)
print()
if usage:
print("tokens:", usage.prompt_tokens, "+", usage.completion_tokens,
"| cost:", getattr(usage, "cost", None))
Closing the connection early stops billing only on providers that support cancellation, such as OpenAI, Azure, Anthropic, Together and DeepSeek. On others, like Groq, Google and Mistral, you pay for the full answer.
Tool Calling
Tools use the standard OpenAI format. The model asks for a call, your code runs it, and you send the result back with role: "tool". One OpenRouter rule trips people up: send the same tools list on every request, including the follow-up.
Example 4: a weather tool with a full round trip
import os, json
from openai import OpenAI
client = OpenAI(base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"])
MODEL = "openai/gpt-6.2-sol:exacto"
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
def get_weather(city):
return {"city": city, "temp_c": 21, "sky": "sunny"} # fake data for the demo
messages = [{"role": "user", "content": "What's the weather in Paris?"}]
first = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)
msg = first.choices[0].message
if msg.tool_calls:
messages.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(get_weather(**args)),
})
final = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)
print(final.choices[0].message.content)
else:
print(msg.content)
The :exacto suffix steers the request to providers with the best tool-calling record. To find models that support tools at all, filter the models page with supported_parameters=tools.
Structured Outputs (Strict JSON)
Pass a JSON Schema in response_format to get output you can parse. Support is set per provider endpoint, not per model, so add require_parameters: true. That stops OpenRouter from routing to an endpoint that would ignore your schema.
Example 5: extract a contact card as JSON
import os, json
from openai import OpenAI
client = OpenAI(base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"])
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
"company": {"type": "string"},
},
"required": ["name", "email", "company"],
"additionalProperties": False,
}
resp = client.chat.completions.create(
model="openai/gpt-6.2-sol",
messages=[{"role": "user",
"content": "Jane Roe from Acme Ltd, reach her at jane@acme.test"}],
response_format={
"type": "json_schema",
"json_schema": {"name": "contact", "strict": True, "schema": schema},
},
extra_body={"provider": {"require_parameters": True}},
)
print(json.loads(resp.choices[0].message.content))
On the Responses API the shape is flatter: text={"format": {"type": "json_schema", "name": ..., "strict": True, "schema": ...}}. The docs warn that some providers treat the schema as a strong hint only, so still validate the result. My structured outputs guide covers validation patterns.
Usage Accounting and Key Limits
You no longer need to ask for usage. OpenRouter now includes it in every response, and the old usage: {include: true} and stream_options flags are deprecated and do nothing. The useful fields on Chat Completions are:
- prompt_tokens / completion_tokens / total_tokens: the token counts.
- cost: the total charged to your account for this call, in credits (1 credit = $1).
- prompt_tokens_details.cached_tokens: tokens read from the prompt cache.
- completion_tokens_details.reasoning_tokens: hidden thinking tokens you also pay for.
- cost_details: the upstream provider cost breakdown.
To check a key’s limits and today’s free-model counter, call GET /api/v1/key:
import os, requests
r = requests.get(
"https://openrouter.ai/api/v1/key",
headers={"Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}"},
timeout=30,
)
data = r.json()["data"]
print("limit remaining:", data.get("limit_remaining"))
print("spent today:", data.get("usage_daily"))
print("free requests today:", data.get("free_model_daily_requests"))
Save the response id if you want to audit later. The generation endpoint returns the full usage for that id.
Fees, Credits and a Worked Cost Example
OpenRouter passes model prices through with no markup. You pay a fee when you buy credits, not on each request.
| Item | Free plan | Standard (pay as you go) | Business |
|---|---|---|---|
| Platform fee | N/A | 5.5% of the credit order (min $0.80); 5% for crypto | 8% |
| Models | 25+ free models | 700+ | 700+ |
| Rate limits | 50 requests/day | Passed through from providers | Passed through from providers |
| BYOK (your own provider keys) | No | $25,000/month of list-price inference free, then 5% fee | Same as Standard |
| Credit expiry | OpenRouter may expire unused credits 1 year after purchase | ||
| Refunds | Unused credits within 24 hours of purchase; fees and crypto payments are not refundable | ||

Worked example: a support bot on GPT-6.2 Sol
GPT-6.2 Sol costs $2 per million input tokens and $10 per million output tokens on OpenRouter. Say each chat turn sends 2,000 input tokens and gets 500 output tokens back.
- Input: 2,000 x $2 / 1,000,000 = $0.004
- Output: 500 x $10 / 1,000,000 = $0.005
- Per turn: $0.009, so 10,000 turns cost about $90 in credits.
- Buying those credits: a $90 order adds a 5.5% fee of $4.95, for $94.95 in total.
Cached input and reasoning tokens change the real number, which is why reading usage.cost beats estimating. For a cross-vendor view, see my AI API pricing comparison.
Troubleshooting: Common Errors and Fixes
Errors come back as JSON with error.code, error.message and sometimes error.metadata. Read metadata.error_type (for example rate_limit_exceeded or provider_unavailable) rather than relying on the status alone.
| Code | What it means | Fix |
|---|---|---|
| 400 | Bad or missing parameter | Check field names; OpenRouter-only fields belong in extra_body |
| 401 | Invalid, disabled or expired key | Check OPENROUTER_API_KEY is set and the key is active |
| 402 | Not enough credits on the account or key | Add credits or raise the key limit. A negative balance blocks free models too |
| 403 | Moderation flag, guardrail or permission block | Read metadata.reasons; change the prompt or the guardrail policy |
| 408 | Request timed out | Retry, stream long answers, or use a faster provider (:nitro) |
| 429 | Rate limited (free daily cap or provider limit) | Back off, honour Retry-After, add a fallback model, or buy 10 credits for the 1,000/day free tier |
| 502 | Model down or returned an invalid response | Add a models fallback list and retry |
| 503 | No provider meets your routing rules | Loosen only, max_price, zdr or require_parameters |
| 200 with an error | Failure after the response started | Check for an error field and finish_reason: "error" even on success codes |
Tip: an empty reply is often a model warming up, or a reasoning model spending its whole max_tokens on thinking. Retrying fixes the first. For the second, raise max_tokens or lower the reasoning effort.
For retry and backoff patterns that work across vendors, see my guide to LLM API rate limits and tiers.
Frequently Asked Questions
Can I use the OpenAI Python SDK with OpenRouter?
Yes. Set base_url="https://openrouter.ai/api/v1" and use your OpenRouter key. Pass OpenRouter-only fields such as provider and models through extra_body.
Is the OpenRouter API free?
Models with a :free variant and the openrouter/free router cost nothing. They are limited to 20 requests per minute and 50 per day, or 1,000 per day after you buy at least 10 credits.
Does OpenRouter charge more than the providers?
No markup is added to token prices. On the Standard plan you pay a 5.5% fee (minimum $0.80) when you buy credits, or 5% with crypto.
What is the difference between :nitro and :floor?
:nitro sorts providers by throughput for speed. :floor sorts by price for the cheapest provider. Both work on any model id.
How do I know which model answered when I use fallbacks?
Read the model field in the response. It shows the concrete model that served the request, even when you sent an alias or a models list.
Do I still need usage: {include: true} to see costs?
No. Usage, including cost in credits, is now included in every response automatically. The old flag is deprecated and ignored.
Why do I get 402 errors on free models?
Your account balance is negative. OpenRouter blocks requests, free ones included, until you add credits to bring it above zero.
Sources
- OpenRouter Quickstart (official docs)
- OpenRouter Pricing
- OpenRouter FAQ
- OpenRouter API rate limits
- OpenRouter provider selection
- OpenRouter model fallbacks
- OpenRouter model variants
- OpenRouter streaming
- OpenRouter tool calling
- OpenRouter structured outputs
- OpenRouter usage accounting
- OpenRouter errors and debugging
- OpenRouter: Simplifying our platform fee
- OpenRouter is joining Stripe
- openai on PyPI




