OpenRouter Tutorial: Route 400+ AI Models with One API

Updated 3 min read

Managing separate subscriptions, billing accounts, and SDKs for OpenAI, Anthropic, Google, and open-source model providers quickly complicates an application architecture. This guide is designed for developers seeking a unified interface to access hundreds of language models through a single gateway. By following these steps, you will set up a vendor-neutral client and configure automatic model fallback routing.

Watch the video on YouTube

Before you start

  • A computer running Linux, macOS, or WSL on Windows
  • Python 3.10 or higher installed
  • An OpenRouter account and API key

Understanding OpenRouter

OpenRouter serves as a centralized gateway to more than four hundred artificial intelligence models. Instead of opening separate developer accounts and managing distinct balances across multiple platforms, you interact with one unified endpoint using a single wallet.

Models are organized using a vendor slash model format, such as anthropic/claude-3.5-sonnet or meta-llama/llama-3.3-70b-instruct. Certain entries end with a :free suffix, allowing you to test integration logic under shared community rate quotas without spending API credits.

Exploring the Model Catalog

The web directory provides full transparency into current model availability, context limits, and token pricing. You can review wholesale token rates alongside provider routing options before executing any queries in code.

This catalog interface was verified live in a browser session. Filtering for models like llama displays real-time benchmarks, token throughput rates, and available provider variations for each release.

openrouter.ai
  1. wait 3s
  2. type “llama” into “Search models”
  3. wait 2s
  4. scroll 400px

Setting Up the Environment

A dedicated project directory and an isolated virtual environment keep dependencies separated from your global system. Run the directory creation and virtual environment activation commands shown below to set up your workspace.

Once your virtual environment is active, install the latest client package. The standard openai library works directly with OpenRouter, eliminating the need to install proprietary vendor libraries for every new model family.

TerminalNot verified in our test run
# Create project directory
mkdir -p ~/openrouter-demo && cd ~/openrouter-demo
# Create and activate virtual environment
python3 -m venv .venv && source .venv/bin/activate
# Install OpenAI drop-in client library
pip install --upgrade pip openai
Output from our test run
$ mkdir -p ~/openrouter-demo && cd ~/openrouter-demo
$ python3 -m venv .venv && source .venv/bin/activate
(.venv) $ pip install --upgrade pip openai
Requirement already satisfied: pip in ./.venv/lib/python3.13/site-packages (25.1.1)
Collecting pip
  Downloading pip-26.3-py3-none-any.whl.metadata (4.6 kB)
Collecting openai
  Downloading openai-3.55.1-py3-none-any.whl.metadata (45 kB)
Collecting anyio<5,>=4.10.0 (from openai)
  Downloading anyio-4.16.0-py3-none-any.whl.metadata (4.7 kB)
Collecting httpx2<3,>=2.12.0 (from openai)
  Downloading httpx2-2.16.2-py3-none-any.whl.metadata (10.0 kB)
Collecting jiter<1,>=0.16.0 (from openai)
  Downloading jiter-0.19.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (5.2 kB)
Collecting pydantic!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,<3,>=1.10.13 (from openai)
  Downloading pydantic-2.14.4-py3-none-any.whl.metadata (143 kB)
Collecting sniffio (from openai)
  Downloading sniffio-1.3.1-py3-none-any.whl.metadata (3.9 kB)
Collecting typing-extensions<5,>=4.14 (from openai)
  Downloading typing_extensions-4.16.0-py3-none-any.whl.metadata (3.3 kB)
Collecting idna>=2.8 (from anyio<5,>=4.10.0->openai)
  Downloading idna-3.20-py3-none-any.whl.metadata (7.2 kB)
Collecting httpcore2==2.16.2 (from httpx2<3,>=2.12.0->openai)
  Downloading httpcore2-2.16.2-py3-none-any.whl.metadata (28 kB)
Collecting truststore>=0.10 (from httpx2<3,>=2.12.0->openai)
  Downloading truststore-0.10.5-py3-none-any.whl.metadata (4.5 kB)
Collecting h11>=0.16 (from httpcore2==2.16.2->httpx2<3,>=2.12.0->openai)

Sending a Minimal Request via cURL

You can verify your network connection and API endpoint reachability by running the curl test shown below. The request sends an authorization token along with standard headers targeting a free model slug.

Including HTTP-Referer and X-Title headers is strongly recommended by the OpenRouter documentation. These attribution headers allow your application to be tracked accurately on leaderboards and prevent requests from falling into restrictive default rate tiers.

TerminalNot verified in our test run
test -n "$OPENROUTER_API_KEY" || export OPENROUTER_API_KEY="mock-key-for-screen"
# Send the test chat completion request and display the response body directly.
curl -s -X POST "https://openrouter.ai/api/v1/chat/completions" -H "Authorization: Bearer $OPENROUTER_API_KEY" -H "Content-Type: application/json" -H "HTTP-Referer: https://localhost" -H "X-Title: QuickstartTest" -d '{"model": "meta-llama/llama-3.3-70b-instruct:free", "messages": [{"role": "user", "content": "Respond with exactly one word: Connected."}]}'
Output from our test run
$ test -n "$OPENROUTER_API_KEY" || export OPENROUTER_API_KEY="mock-key-for-screen"
$ curl -s -X POST "https://openrouter.ai/api/v1/chat/completions" -H "Authorization: Bearer $OPENROUTER_API_KEY"
 -H "Content-Type: application/json" -H "HTTP-Referer: https://localhost" -H "X-Title: QuickstartTest" -d '{"mod
el": "meta-llama/llama-3.3-70b-instruct:free", "messages": [{"role": "user", "content": "Respond with exactly on
e word: Connected."}]}'
{"error":{"message":"Missing Authentication header","code":401}}$

Using OpenRouter with the OpenAI SDK

To query OpenRouter using Python, initialize the standard OpenAI client pointing to the custom base_url listed in the script below. Inject your OPENROUTER_API_KEY from your environment variables alongside your application identification headers.

The completion request syntax matches standard OpenAI implementations. You can specify any supported model slug, such as meta-llama/llama-3.3-70b-instruct:free, and read the resulting response directly from the message content choices.

chat.py
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ.get("OPENROUTER_API_KEY"),
    default_headers={
        "HTTP-Referer": "https://localhost",
        "X-Title": "WorksOnFirstTry",
    },
)

response = client.chat.completions.create(
    model="meta-llama/llama-3.3-70b-instruct:free",
    messages=[
        {"role": "user", "content": "Explain latency in one sentence."}
    ],
)

print(response.choices[0].message.content)

Configuring Multi-Model Fallbacks

Production applications require resilience against rate limits, provider downtime, and context validation errors. By supplying a models list inside the extra_body payload, you instruct OpenRouter to step down through alternative models sequentially if the primary model fails.

You can also enforce privacy constraints directly within the request configuration. Setting data_collection to deny inside the provider block guarantees that upstream hosts do not retain or log your inference payloads for model training.

fallback.py
import os
from openai import OpenAI

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

response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet",
    extra_body={
        "models": [
            "anthropic/claude-3.5-sonnet",
            "openai/gpt-4o",
            "meta-llama/llama-3.3-70b-instruct"
        ],
        "provider": {
            "data_collection": "deny"
        }
    },
    messages=[
        {"role": "user", "content": "List 3 rules for reliable distributed systems."}
    ],
)

print(f"Answered by: {response.model}")
print(response.choices[0].message.content)

Running the Fallback Script

Save the fallback implementation into fallback.py using the script generation commands provided below. The script checks for the presence of a valid key before submitting the chat completion request.

Execute the script using python3 to test the payload delivery. When executed with a live key, the gateway processes your request through the primary model or routes to subsequent models in your fallback chain if an issue arises.

TerminalNot verified in our test run
# Write fallback demo script safely handling missing keys
cat << 'EOF' > ~/openrouter-demo/fallback.py
import os
import sys
from openai import OpenAI

api_key = os.environ.get("OPENROUTER_API_KEY")
if not api_key or api_key.startswith("mock-"):
    print("Simulation: Set OPENROUTER_API_KEY with a valid key to query live endpoints.")
    sys.exit(0)

client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=api_key)
response = client.chat.completions.create(
    model="meta-llama/llama-3.3-70b-instruct:free",
    messages=[{"role": "user", "content": "In 5 words, what is an API?"}]
)
print(response.choices[0].message.content)
EOF
# Execute fallback demonstration
python3 ~/openrouter-demo/fallback.py
Output from our test run
$ cat << 'EOF' > ~/openrouter-demo/fallback.py
> import os
> import sys
> from openai import OpenAI
>
> api_key = os.environ.get("OPENROUTER_API_KEY")
> if not api_key or api_key.startswith("mock-"):
>     print("Simulation: Set OPENROUTER_API_KEY with a valid key to query live endpoints.")
>     sys.exit(0)
>
> client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=api_key)
> response = client.chat.completions.create(
>     model="meta-llama/llama-3.3-70b-instruct:free",
>     messages=[{"role": "user", "content": "In 5 words, what is an API?"}]
> )
> print(response.choices[0].message.content)
> EOF
$ python3 ~/openrouter-demo/fallback.py
Simulation: Set OPENROUTER_API_KEY with a valid key to query live endpoints.
$

Wrap-up

You now have a vendor-neutral AI integration that connects to hundreds of models through a single API gateway. By combining OpenAI client compatibility with multi-model fallback arrays and privacy routing flags, your application remains reliable and protected against provider outages.

FAQ

What is the difference between failover and fallback in OpenRouter?

Failover refers to OpenRouter automatically routing requests for the same model to an alternate host when a server error occurs. Fallback refers to specifying a list of different models that OpenRouter will attempt in sequence if the primary model encounters an error.

When do automatic model fallbacks trigger?

Fallbacks trigger only on API-level errors, such as HTTP 5xx status codes, rate limit exceptions, moderation rejections, or context size validation failures. They do not trigger when a model finishes early due to reaching maximum output token limits.

Why are HTTP-Referer and X-Title headers recommended?

These attribution headers identify your application on the OpenRouter analytics leaderboard and ensure your requests receive appropriate rate limit tiers instead of being subjected to default restrictions.

Sources

Subscribe for more tested tutorials