recent
🔥 𝐇𝐨𝐭

OpenRouter API Tutorial: Key, Free Models & First Request

Home

OpenRouter API Guide for Beginners: How to Use Free AI Models in 2026

text OpenRouter API guide for beginners showing how to get an API key, choose a model, send a request, receive an AI response, and use free OpenRouter models in 2026.

To use the OpenRouter API, create an API key, choose a current model ID, and send a POST request to https://openrouter.ai/api/v1/chat/completions. The response is JSON, and for a standard Chat Completions request the generated text is typically available at choices[0].message.content.

This beginner OpenRouter API guide walks through that workflow with cURL, Python, and server-side Node.js. It also explains free routes, current limits, common errors, fallbacks, and API-key security without turning the tutorial into a model ranking or benchmark roundup.

Technical details verified: August, 2026. OpenRouter changes quickly, so recheck volatile limits and routing behavior before production use.

Quick Start: How to Use the OpenRouter API in 5 Steps

AccountAPI KeyModel IDRequestResponse
  1. Create an OpenRouter API key and store it as an environment variable.
  2. Open the live model catalog and copy the exact model ID you want to use.
  3. Send a request to /api/v1/chat/completions with your key, the model ID, and a message.
  4. Read the generated text from choices[0].message.content in the JSON response.
  5. Swap in a :free route or openrouter/free once the basic call works.

What Is OpenRouter?

OpenRouter is a single API that sits in front of models from many different providers — OpenAI, Anthropic, Google, Meta, and others — so you don't need a separate key, SDK, and billing setup for each one. You send a standard HTTP request, name the model you want by its ID, and OpenRouter routes it to the right provider. OpenRouter's quickstart covers the full workflow if you want the primary source.

Because the request format closely follows the OpenAI Chat Completions shape, existing OpenAI SDK code can often be adapted by changing the base URL, API key, and model ID. OpenRouter also supports provider failover and optional model fallbacks, which are separate concepts covered later in this guide.

Step 1: Create an OpenRouter API Key

Sign in to OpenRouter, open the API Keys area, and create a new key. Give it a clear name and, if useful, set the optional credit limit documented for API keys. Copy the key securely and treat it like a password.

Don't paste the raw key into your code. Store it as an environment variable instead:

export OPENROUTER_API_KEY="YOUR_OPENROUTER_API_KEY"
Before you continue: keep the key server-side, store it in an environment variable or secrets manager, and never commit it to source control. If it is exposed, revoke it and create a replacement. A fuller security checklist appears later in this guide.

OpenRouter's authentication documentation covers Bearer-token use and key-level limits in more detail than we need here.

Step 2: Choose a Model and Copy Its ID

Model IDs generally follow a provider/model-name pattern. Because routes and versions change, copy the current requestable ID from the live OpenRouter model catalog rather than trusting an old tutorial or static list.

  1. Open the live model catalog and find a model that fits your task.
  2. Search or filter for the task you need, or filter for free pricing.
  3. Copy the exact model ID shown on the page.
  4. Check the price per token, unless you're using a free route.
  5. Check the context length against how much text you're sending.
  6. Check which parameters the model supports — tool calling, structured outputs, and so on.
  7. Paste that exact ID into your request.

If you're specifically weighing coding models against each other, that's its own decision with its own tradeoffs. We're keeping this guide to setup and first requests rather than turning it into a ranking.

Step 3: Send Your First OpenRouter API Request

For the Chat Completions requests in this beginner guide, free and paid model routes use the same endpoint:

POST https://openrouter.ai/api/v1/chat/completions

Here's a minimal cURL example. Swap YOUR_CURRENT_MODEL_ID for the model ID you copied from the catalog:

curl https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "YOUR_CURRENT_MODEL_ID",
    "messages": [
      {
        "role": "user",
        "content": "Summarize this text in one sentence."
      }
    ]
  }'

A few things worth knowing about this call:

  • The Authorization header carries your key as a Bearer token — this is required.
  • Content-Type: application/json is required.
  • model is the exact ID you copied from the catalog.
  • messages is an array of role/content objects, the same shape OpenAI's API uses.
  • The response comes back as JSON, and the generated text lives at choices[0].message.content.

OpenRouter also documents two optional headers, HTTP-Referer and X-OpenRouter-Title, which let your app appear on OpenRouter's public leaderboards. They're not part of authentication — don't treat them as required.

Using OpenRouter With Python

pip install requests
import os
import requests

response = requests.post(
    "https://openrouter.ai/api/v1/chat/completions",
    headers={
        "Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "model": "YOUR_CURRENT_MODEL_ID",
        "messages": [
            {
                "role": "user",
                "content": "Summarize this text in one sentence.",
            }
        ],
    },
)

response.raise_for_status()
data = response.json()
print(data["choices"][0]["message"]["content"])

raise_for_status() stops the success path on a non-2xx HTTP response, so the code does not immediately try to read choices[0] from an error response. The key is loaded from the environment at runtime instead of being hard-coded.

Using OpenRouter With JavaScript / Node.js

const response = await fetch(
  "https://openrouter.ai/api/v1/chat/completions",
  {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "YOUR_CURRENT_MODEL_ID",
      messages: [
        {
          role: "user",
          content: "Summarize this text in one sentence.",
        },
      ],
    }),
  }
);

if (!response.ok) {
  const errorBody = await response.text();
  throw new Error(`OpenRouter request failed (${response.status}): ${errorBody}`);
}

const data = await response.json();
console.log(data.choices[0].message.content);

This runs server-side — in a Node script, an API route, or a backend service — never in code shipped to a browser. process.env.OPENROUTER_API_KEY keeps the key out of your source. The response.ok check also surfaces the error body before the code assumes a successful Chat Completions response.

Using OpenRouter With the OpenAI SDK

If you already have code built on the OpenAI SDK, point it at OpenRouter by changing the base URL and the key:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
)

From there, the familiar client.chat.completions.create() call works the same way, just with an OpenRouter model ID in the model field. Not every model supports every OpenAI-style parameter, so check the model's supported parameters in the catalog before assuming something like structured outputs or tool calling will work on it.

OpenRouter also documents native client SDKs — @openrouter/sdk for TypeScript and openrouter for Python. For current package syntax and examples, use the official OpenRouter Quickstart. If you are migrating existing OpenAI code, the OpenAI SDK integration guide shows the current compatibility setup.

How to Use Free OpenRouter Models

OpenRouter offers two common zero-token-price paths for inference: a fixed :free variant of a specific model, or the openrouter/free router that selects from the current free pool.

A :free suffix marks a free variant of a named model, written as provider/model-name:free. It costs nothing per token, but it's still governed by the free-model rate limits below, and provider-side availability can change. See OpenRouter's free variant documentation for specifics.

openrouter/free isn't a model at all — it's a router. It looks at what your request needs (such as tool calling, structured output, or image understanding), filters the current free pool to eligible models, and then selects from that eligible pool. The model that actually answers can differ from one call to the next, so check the model field in the response if that matters to you. More detail lives in OpenRouter's Free Models Router documentation.

One thing worth saying plainly: a model's weights being open to the public doesn't mean it's free to call through OpenRouter. Pricing and availability on the platform are separate from whether the weights happen to be open.

model:free vs openrouter/free

Comparing a fixed free variant against the dynamic free router
Factor Specific model:free openrouter/free
Model identity Fixed — one named model Can change between calls
Reproducibility Better, since the same model answers each time Lower, since the router decides
Availability Can disappear if that provider pulls the free variant Selects from whatever's currently eligible
Best use Repeatable tests or demos where consistency matters Quick experimentation
Main limitation Tied to that model's current free endpoints and capacity Not a single model you can rank or benchmark

How to Check Models and Pricing

Beyond the web catalog, OpenRouter exposes model metadata through an API:

GET https://openrouter.ai/api/v1/models

That's useful when you want to check a model's exact ID, price, context length, or supported parameters programmatically instead of clicking through the site every time. It's not something you need for a first request — the live catalog covers most beginner needs. OpenRouter's models documentation explains the metadata and pricing fields.

OpenRouter Free Rate Limits

Official figures below verified against OpenRouter's documentation on August 10, 2026.

Free-model request limits by account credit status
Purchased credits, all time Requests per minute Free-model requests per day
Fewer than 10 credits 20 50
At least 10 credits 20 1,000

A few things that trip people up here:

  • These limits are account-wide — they apply across every free model you use, not per model.
  • Switching which free model you call doesn't reset the daily count.
  • Creating additional accounts or API keys does not increase the rate-limit capacity OpenRouter governs globally.
  • Free means zero per-token price on that route, not unlimited requests.

Exact limits may vary by account, region, usage, and current product changes. Check the official limits documentation before relying on these numbers in production.

Avoiding accidental paid usage: stick to a specific :free route or openrouter/free, confirm pricing in the live catalog before sending anything, and don't assume an open-weight model is free. Watch the model field in your responses, set key-level limits if your account supports them, and be careful about pairing a free model with a paid one in a fallback list — the fallback might not be free.

Common OpenRouter API Errors

OpenRouter uses HTTP status codes for failed requests and normalizes upstream provider failures into typed categories such as rate_limit_exceeded, provider_overloaded, provider_unavailable, invalid_request, and not_found. For provider errors, the current documentation recommends using the typed error_type rather than relying on the HTTP status alone. See the official errors and debugging guide.

Common errors and how to fix them
Error or symptom Likely cause What to check Fix
401 Unauthorized Missing, invalid, or revoked key Environment variable is set, Bearer prefix present, key not revoked Create or replace the key
402 Payment Required Insufficient credits or a key-level spending limit Account balance and any per-key limit Add credits for paid routes, or raise the limit
Model not found / not_found Stale or mistyped model ID Live model catalog for the current ID Copy the ID again rather than reusing an old one
429 Too Many Requests OpenRouter rate limit, free-tier limit, or upstream provider throttling Account/key usage, error response headers, provider status Back off, retry with delay, or use a fallback
Context-length error Input plus expected output exceeds the model's context window The model's context length vs. your prompt size Shorten the request or choose a model with more context
Unsupported parameter The model doesn't support a field you sent The model's supported parameters in the catalog Remove or replace that parameter
Provider unavailable No eligible provider can currently serve the model Provider/model status Retry shortly, or add a fallback model

OpenRouter API troubleshooting flowchart showing how to fix authentication errors, rate limits, model-not-found errors, credit issues, and provider failures with retries and fallback models.

It's tempting to read every 429 as "you hit your daily free-model quota," but that's not always what's happening. A 429 can come from OpenRouter's own rate limiting, the free-tier caps above, or an upstream provider throttling or protecting itself under load — and those call for different responses.

When OpenRouter itself returns the 429, check the error body and, when present, the error.metadata.error_type field, along with any X-RateLimit-* headers on that specific error response — honor Retry-After if it's there. Successful responses don't normally carry those rate-limit headers, so don't expect to see them on a call that worked. You can also check current usage with GET /api/v1/key. Beyond that: use exponential backoff, avoid hammering the endpoint with immediate retries, and fall back to another model if the request is time-sensitive.

How to Add a Fallback Model

Instead of a single model string, you can send an ordered list. If the first model errors out or isn't available, OpenRouter tries the next one:

{
  "models": [
    "PRIMARY_MODEL_ID",
    "BACKUP_MODEL_ID"
  ],
  "messages": [
    {
      "role": "user",
      "content": "Summarize this text."
    }
  ]
}

Order matters — it's a priority list, not a random pool. Whichever model actually answers gets reported back in the response, and it may not be the one you listed first, so check it if model identity matters to you. A fallback can also change your cost, your latency, and even how the output reads, since you're not guaranteed the same model's writing style every time. That's fine for resilience, but worth knowing before you assume every response came from your primary pick. OpenRouter's fallback documentation covers the error conditions that trigger a switch.

One more layer sits underneath all this: a single model can be served by more than one provider, and OpenRouter routes between them based on availability and latency. If one provider is briefly down or overloaded, that doesn't necessarily mean the model itself is unavailable — it might just mean OpenRouter needs a different provider serving the same model.

How to Keep Your OpenRouter API Key Safe

  • Keep keys out of frontend JavaScript, period — anything shipped to a browser is visible to anyone who opens dev tools.
  • Never commit a key to source control; keep secrets outside the repository.
  • Use environment variables locally and a proper secrets manager in production.
  • Don't include a live key in a screenshot, even a cropped one.
  • If a key leaks, revoke it immediately and generate a new one — don't plan to rotate it "eventually."
  • Set a key-level spending limit if your account supports it, so a leaked key has a ceiling.
  • If you're exporting an n8n workflow to share or version-control, make sure the key isn't baked into the export.

Free Models, Providers, and Privacy

Free describes price, not privacy. Provider data policies aren't identical just because two models both show a $0 token cost on OpenRouter. Before sending anything sensitive — proprietary code, customer data, passwords, confidential client material — check the actual data policy of the provider behind the model you're calling.

OpenRouter currently offers privacy controls that let you restrict routing to providers that may use your prompts for training, along with Zero Data Retention routing options for accounts that need them. It's worth knowing these exist; configuring them goes beyond what a beginner guide needs to cover. See OpenRouter's provider logging and privacy documentation for details.

When Free Models Are Not Enough

Free routes are useful for learning, prototypes, and low-volume projects, but they are not designed around production-grade capacity. Consider paid routes when you need higher request volume, more predictable availability, a specific model route instead of the dynamic free router, or stricter provider and privacy requirements. Paid access can expand your options, but you should still choose routing and fallback settings that match the reliability your application needs.

How We Verified This OpenRouter API Guide

We prioritized current OpenRouter documentation for the Quickstart, authentication, limits, free variants, the Free Models Router, error handling, fallbacks, model metadata, and privacy controls. Volatile details in this article were checked on August 10, 2026. Because endpoints, limits, SDK behavior, and free-route availability can change, recheck the official documentation before using these values in a production workflow.

Frequently Asked Questions

How do I use the OpenRouter API?

Create an API key, store it as an environment variable, copy a model's exact ID from the live catalog, send a POST request to /api/v1/chat/completions with your key and a messages array, then read the generated text from choices[0].message.content in the JSON response.

How do I create an OpenRouter API key?

Sign in to OpenRouter, open the API Keys area, and create a new key. Give it a clear name, set an optional credit limit if useful, then copy it securely. Store it as an environment variable or secret rather than pasting it directly into your source code.

Is the OpenRouter API free?

OpenRouter has free routes, but the API is not universally free. Some models offer a :free variant with zero token pricing, and openrouter/free routes requests to eligible free models. Paid routes consume credits according to current catalog pricing, and free routes still have request limits.

What is the OpenRouter API base URL?

https://openrouter.ai/api/v1. The main endpoint beginners use is POST https://openrouter.ai/api/v1/chat/completions.

Can I use the OpenAI SDK with OpenRouter?

Yes. Point the OpenAI SDK's base_url at https://openrouter.ai/api/v1, use your OpenRouter API key instead of an OpenAI key, and pass an OpenRouter model ID. The familiar chat completions call works the same way, though not every model supports every OpenAI-style parameter.

What does :free mean in OpenRouter?

A :free suffix marks a free variant of one specific model, written as provider/model-name:free. It has no per-token cost, but it's still governed by the free-model rate limits and can become unavailable if that provider changes what it offers for free.

What is openrouter/free?

It's a router, not a model. openrouter/free looks at what your request needs, filters the current pool of free models down to ones that support that, and picks one to answer. Which model actually responds can vary between calls, so check the response's model field if that matters to you.

How many free OpenRouter requests can I make?

As of August 10, 2026: 20 requests per minute either way, 50 free-model requests per day if you've purchased fewer than 10 credits total, and 1,000 per day once you've purchased at least 10 credits. These limits are account-wide and can change, so check OpenRouter's official limits page for the current numbers.

Why am I getting an OpenRouter 429 error?

A 429 can mean you hit OpenRouter's own rate or free-tier limit, or that an upstream provider is throttling or protecting itself under load — it's not always the daily quota. Check the error body and any rate-limit headers, honor Retry-After if present, back off with exponential delay, and consider a fallback model.

How do I keep my OpenRouter API key secure?

Never put it in frontend JavaScript or commit it to a repo. Use environment variables locally and a secrets manager in production, avoid screenshots that show it, and revoke and replace it immediately if it's ever exposed. Set a key-level spending limit if your account supports one.

Final OpenRouter API Checklist

  • API key created and stored as an environment variable, not hard-coded
  • Endpoint set to https://openrouter.ai/api/v1/chat/completions
  • Model ID copied fresh from the live catalog
  • Pricing checked before sending a paid request
  • Free route (:free or openrouter/free) confirmed if that's what you intended
  • Rate limits and account-wide quota understood
  • Error handling covers 401, 402, 429, and model-not-found
  • Fallback model list considered for resilience
  • No key or secret exposed in code, screenshots, or workflow exports
google-playkhamsatmostaqltradentX