Authentication overview

OpenRouter uses a token-based authentication system, primarily relying on API keys to secure access to its unified API for large language models (LLMs). This method is common for web services requiring client authentication without maintaining session state. When a request is made to the OpenRouter API, an API key is included in the HTTP Authorization header. This key serves as a credential that identifies the calling application or user and authorizes access to the requested resources, such as specific LLM invocations or account-related information.

The API key functions as a secret token; its presence and validity grant access. OpenRouter's system verifies the provided key against its registered keys, and if it matches an active key, the request is processed. This approach allows for granular control over API access, enabling users to generate multiple keys for different applications or revoke compromised keys without affecting others. The integration of various LLMs through a single API necessitates a consistent and secure authentication mechanism, which API keys provide by acting as a central point of identity verification for all model interactions OpenRouter API reference.

The use of API keys aligns with standard practices for securing RESTful APIs, where statelessness is a key design principle. Unlike session-based authentication, which relies on cookies and server-side session management, API key authentication requires the key to be sent with every request, making each request self-contained. This simplifies scaling and reduces the overhead associated with session management, which is particularly beneficial for high-volume API usage scenarios typical of LLM applications.

Supported authentication methods

OpenRouter exclusively supports API key authentication, implemented as a Bearer Token within the HTTP Authorization header. This method is widely adopted for its simplicity and effectiveness in securing API access.

Method When to Use Security Level
API Key (Bearer Token) Accessing the OpenRouter API from server-side applications, scripts, or client-side applications where the key can be securely managed (e.g., proxied through a backend). Suitable for all standard API interactions with OpenRouter models. Moderate to High (depends heavily on key management and storage practices)

The Bearer Token scheme is specified in RFC 6750 for OAuth 2.0 Bearer Token Usage, though OpenRouter uses it with static API keys rather than dynamically issued OAuth tokens. The core principle remains the same: the client sends a token in the Authorization header with the prefix Bearer, followed by the API key. For example: Authorization: Bearer YOUR_API_KEY.

Getting your credentials

To obtain your OpenRouter API key, follow these steps:

  1. Log in to OpenRouter: Navigate to the OpenRouter homepage and log in to your account. If you do not have an account, you will need to create one.
  2. Access API Keys Section: Once logged in, go to your account dashboard. There should be a dedicated section for managing API keys, typically labeled "API Keys" or "Settings" where API key management is available.
  3. Generate a New Key: Within the API Keys section, you will find an option to generate a new API key. It's common practice for platforms to allow users to generate multiple keys, each with specific permissions or for different projects.
  4. Copy the Key: After generation, OpenRouter will display your new API key. It is crucial to copy this key immediately and store it securely, as it may not be displayed again for security reasons. If lost, you will likely need to generate a new one.
  5. Store Securely: Store your API key in a secure location. For development, using environment variables is highly recommended to prevent accidental exposure of the key in source code repositories.

OpenRouter's developer experience notes highlight the clear visibility of pricing and model options, which extends to the straightforward process of obtaining an API key. This ease of access is designed to facilitate rapid prototyping and integration with their unified LLM API.

Authenticated request example

Here's how to make an authenticated request to the OpenRouter API using your API key. This example demonstrates a common interaction: sending a chat completion request using the cURL command-line tool.

curl \
  https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer YOUR_OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -X POST \
  -d '{"model": "mistralai/mistral-7b-instruct", "messages": [{"role": "user", "content": "What is the capital of France?"}]}'

In this example:

  • YOUR_OPENROUTER_API_KEY must be replaced with the actual API key you generated from your OpenRouter dashboard.
  • The -H "Authorization: Bearer YOUR_OPENROUTER_API_KEY" header explicitly passes the API key as a Bearer token.
  • The Content-Type: application/json header indicates that the request body is in JSON format.
  • The -X POST specifies that this is an HTTP POST request.
  • The -d flag provides the JSON payload containing the model identifier and the chat messages.

Similar authentication patterns apply when using OpenRouter's official SDKs for Python or JavaScript, where the API key is typically passed as an argument during client initialization or set as an environment variable that the SDK automatically picks up.

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="mistralai/mistral-7b-instruct",
    messages=[{"role": "user", "content": "Hello, world!"}]
)

print(response.choices[0].message.content)
import OpenAI from 'openai';

const openai = new OpenAI({
  baseURL: "https://openrouter.ai/api/v1",
  apiKey: process.env.OPENROUTER_API_KEY,
});

async function main() {
  const chatCompletion = await openai.chat.completions.create({
    model: "mistralai/mistral-7b-instruct",
    messages: [{ role: "user", content: "Hello, world!" }],
  });

  console.log(chatCompletion.choices[0].message.content);
}

main();

Security best practices

Securing your OpenRouter API keys is critical to prevent unauthorized access to your account and potential misuse, which could incur unexpected costs or expose sensitive data. Adhering to these best practices enhances the overall security posture of your integrations:

  1. Use Environment Variables: Never hardcode API keys directly into your source code. Instead, store them as environment variables. This practice ensures that keys are not committed to version control systems like Git, where they could be inadvertently exposed. Most programming languages and frameworks provide straightforward ways to access environment variables.

  2. Restrict Key Permissions (if available): While OpenRouter's current documentation primarily describes a single type of API key, if future iterations or other services offer granular permission controls, always generate keys with the minimum necessary permissions. This principle of least privilege limits the damage if a key is compromised.

  3. Regularly Rotate Keys: Periodically generate new API keys and revoke old ones. This practice reduces the window of opportunity for a compromised key to be exploited. The frequency of rotation depends on your security policy and the sensitivity of the data accessed.

  4. Monitor Usage: Regularly review your OpenRouter account dashboard for unusual API usage patterns. Spikes in requests or usage from unexpected geographical locations could indicate a compromised key. OpenRouter's pricing page details how usage is tracked, enabling users to monitor their consumption OpenRouter pricing documentation.

  5. Secure Development Environment: Ensure that your development and deployment environments are secure. This includes using strong passwords, enabling multi-factor authentication (MFA) on your OpenRouter account, and keeping your systems patched and up-to-date.

  6. Avoid Client-Side Exposure: Do not embed API keys directly into client-side code (e.g., JavaScript running in a web browser). If your client-side application needs to interact with OpenRouter, route requests through a secure backend server that can add the API key before forwarding the request. This backend acts as a proxy, protecting your key from being exposed to end-users.

  7. Implement Rate Limiting and Circuit Breakers: While these are not directly related to API key security, implementing them in your application can mitigate the impact of a compromised key by limiting the number of requests an attacker can make in a given period. This also protects against denial-of-service attacks.

  8. Secure Communication: Always use HTTPS when making API requests. OpenRouter, like all reputable API providers, enforces HTTPS to encrypt data in transit, protecting your API key and other sensitive information from interception during network transmission. The use of HTTPS is a fundamental security practice for web communications, as detailed by organizations like the W3C on web security best practices.