How to get an API key for OpenRouter

Projects

Añade servicios, genera credenciales y gestiona la facturación desde la CLI o deja que tu agente se encargue por ti.

Más información 
  1. Introducción
  2. Key takeaways
  3. How do you get an application programming interface (API) key for OpenRouter?
  4. Why should you use OpenRouter for your application?
  5. How do you get an OpenRouter API key manually?
    1. 1. Create an account
    2. 2. Go to the keys page
    3. 3. Generate a new key
    4. 4. Copy the key immediately
    5. 5. Store it in an environment file
    6. 6. Exclude the file from version control
    7. 7. Test the key
  6. How do you get an OpenRouter API key with Stripe Projects?
    1. 1. Install the plugin
    2. 2. Initialize a project
    3. 3. Add OpenRouter
    4. 4. Allow Stripe to sync the credential
    5. 5. Confirm the key landed
  7. How do you configure an OpenRouter API key in your application?
  8. What are some common pitfalls when using an OpenRouter API key?
  9. How Stripe Projects can help

Software increasingly relies on multiple AI models, such as OpenRouter. This marketplace for large language models (LLMs) directs AI prompts to the best LLM based on factors such as cost. Your software can use OpenRouter programmatically through its application programming interface (API), provided you have an API key, which is a unique, secret authentication credential.

It takes a few manual steps to get an OpenRouter API key. First, you’ll decide how the key fits into your application. A router that touches hundreds of models needs more thought given to storage, fallback behavior (e.g., a backup plan when an initial API call fails), and cost limits than a typical single-provider API key. You can also get an OpenRouter API key more quickly and more easily with Stripe Projects, which handles provisioning, credential storage, and billing for third-party infrastructure services.

Below, we’ll discuss the manual setup process, how Stripe Projects makes setup easier, and how to load an API key into your application safely, including environment configuration, error handling, and common mistakes that can expose a key or drain a budget.

Key takeaways

  • Creating an OpenRouter key is straightforward, but it requires care to store and scope it correctly.

  • Routing requests through OpenRouter means your application code can switch models without a rewrite.

  • Common failures include hardcoding keys, skipping rate-limit handling, and assuming that every model supports the same features.

How do you get an application programming interface (API) key for OpenRouter?

First, you need to understand what OpenRouter does. The OpenRouter unified API is one of three ways to engage with OpenRouter. It routes requests to language models from dozens of providers, including OpenAI, Anthropic, Google, and Meta, through a single endpoint and a single API key. Instead of writing separate integration code for each model provider, you send requests and OpenRouter forwards them to the model.

Why should you use OpenRouter for your application?

Building a chat feature, a coding assistant, or any AI-driven tool usually means selecting a model. But the model that works best often changes based on the task, the budget, or what’s available that week. It’s worth checking which models actually support the features you need. OpenRouter lets you make that decision at the request level rather than locking it into your codebase.

It offers flexibility in a few concrete ways:

  • Model experimentation: You can A/B test GPT-4 against Claude on the same prompt without rewriting integration code for each one.

  • Cost control: Cheaper models can handle simple requests such as classification or summarization. Expensive models get reserved for complicated reasoning tasks, and you can switch between them by changing a parameter.

  • Provider redundancy: If a provider has an outage or changes its terms, you can reroute to a different model without rebuilding your integration layer.

  • Faster iteration: OpenRouter adds new models regularly, so you can test frontier models quickly.

How do you get an OpenRouter API key manually?

Creating a new OpenRouter API key manually takes a few steps.

Here’s how it works:

1. Create an account

Go to openrouter.ai and sign up with an email address or an existing Google or GitHub account.

2. Go to the keys page

Under your account settings, find the keys section, where you can generate, name, and manage individual API keys.

3. Generate a new key

Click the button to create a key, give it a descriptive name such as production-chatbot so you can identify it later, and set an optional spending limit for that specific key.

4. Copy the key immediately

Copy the full key value before closing the dialog.

5. Store it in an environment file

For example, add the key to a .env file in your project root. Don’t write it directly into your application code.

6. Exclude the file from version control

Add .env to your .gitignore file before your first commit since a key pushed to a public repository can get scraped and abused.

7. Test the key

Send a request to OpenRouter’s API to confirm the key works before building further.

How do you get an OpenRouter API key with Stripe Projects?

Stripe Projects, an extension of the Stripe CLI, collapses the manual process into a single command run from your terminal.

Here’s how:

1. Install the plugin

If you haven’t already, run stripe plugin install projects, then confirm the command line interface (CLI) recognizes the projects command.

2. Initialize a project

From your app’s directory, run stripe projects init to set up projects.

3. Add OpenRouter

Run stripe projects add openrouter/api. This associates an OpenRouter account with your Stripe account, or creates one if you don’t have one yet, then provisions API access.

4. Allow Stripe to sync the credential

The CLI fetches your OpenRouter API key, encrypts a copy in .projects/vault/vault.json, and writes it to your .env file as an environment variable.

5. Confirm the key landed

Run stripe projects status to see the OpenRouter resource listed alongside its current tier and health status.

How do you configure an OpenRouter API key in your application?

Once the key is in your .env file, your application needs a way to read it and send requests through OpenRouter’s endpoint rather than contacting each model provider directly. Since OpenRouter uses the same request format as OpenAI’s API, you need to change only the base URL and model parameter, provided you’ve already integrated OpenAI. Load the key from the environment rather than hardcode it. From there, specify which model handles the request by passing a provider-prefixed model name in the model field.

A few configuration details matter beyond the basic connection:

  • Set a request timeout: Different models respond at different speeds, so a timeout tuned for a fast model might cut off a slower one mid-response. Set it generously and adjust per model if your application calls more than one.

  • Handle rate limit errors explicitly: OpenRouter returns a 429 status code when you exceed your limit. Catch it separately from other errors.

  • Separate model configuration from application logic: Keep model names, fallback lists, and per-request parameters, such as temperature, in a configuration file or environment variables rather than scattered through your codebase. Changing providers doesn’t have to mean touching every call site.

  • Set usage limits per key: OpenRouter lets you cap spending on individual keys. This matters if you’re issuing separate keys for development, staging, and production environments.

What are some common pitfalls when using an OpenRouter API key?

A few mistakes show up often when using an OpenRouter API key.

Avoid the following missteps:

  • Exposing the key in browser code: If your application calls OpenRouter from client-side JavaScript, the key is visible to anyone who opens the browser’s developer tools. Route requests through your own backend instead, and keep the key server-side only.

  • Committing the .env file: A key pushed to a public repository can get picked up by scrapers almost immediately and used until you notice the charges. Check that .env is in .gitignore before your first commit.

  • Assuming every model supports the same features: Function calling, vision input, and structured outputs aren’t universal across the models OpenRouter routes to. Check a model’s capabilities before switching to it in production. A request that worked fine on one model might fail silently or error out on another.

  • Skipping rate limit handling: Hitting a 429 without a retry strategy can mean failed requests during traffic spikes. Build in backoff logic from the start rather than adding it after an outage.

  • Ignoring per-model pricing differences: When you route a high-volume, simple task to an expensive model, it inflates your bill. Match model cost to task complexity, and revisit that mapping as OpenRouter adds new models.

  • Using one key across every environment: A single key shared between development, staging, and production makes it hard to tell where a spike in usage or a leaked credential originated. Separate keys per environment, each with its own spending limit, help isolate the problem when something goes wrong.

How Stripe Projects can help

Stripe Projects lets developers and their AI agents add services, generate credentials, and manage billing from the command line interface (CLI).

Stripe Projects helps you:

  • Provision third-party services from the command line: Use one workflow to add services, manage credentials, and upgrade plans, instead of different tools and workflows for every provider. Manage hosting, databases, auth, AI, and more without needing dashboards, config files, or infrastructure code.

  • Sync credentials automatically: Keep environment variables portable across local setups, machines, teammates, and agents—no copy-pasting application programming interface (API) keys.

  • Manage billing from the CLI or your coding agent: Set up billing details once and securely share them with third-party services. Upgrade and downgrade tiers, monitor usage, and manage subscriptions from the CLI.

Learn more about how Stripe Projects helps simplify app provisioning, or copy and paste this command into your terminal to get started today:

brew install stripe/stripe-cli/stripe && stripe plugin install projects && npx skills add https://github.com/stripe/ai --skill stripe-projects -y -g

El contenido de este artículo tiene solo fines informativos y educativos generales y no debe interpretarse como asesoramiento legal o fiscal. Stripe no garantiza la exactitud, la integridad, la adecuación o la vigencia de la información incluida en el artículo. Busca un abogado o un asesor fiscal profesional y con licencia para ejercer en tu jurisdicción si necesitas asesoramiento para tu situación particular.

Más artículos

  • Se ha producido un error. Vuelve a intentarlo o contacta con soporte.

¿A punto para empezar?

Crea una cuenta y empieza a aceptar pagos: no tendrás que firmar ningún contrato ni proporcionar datos bancarios. Si lo prefieres, puedes ponerte en contacto con nosotros y diseñaremos un paquete personalizado para tu empresa.
Payments

Payments

Acepta pagos por Internet, en persona y desde cualquier rincón del mundo con una solución de pagos diseñada para todo tipo de negocios.

Documentación de Payments

Encuentra una guía para integrar las API de pagos de Stripe.