Skip to content
Petra Vlk

Dec 5, 202614 min read

Switching providers means changing a model name in the request, not the integration.

The OpenRouter API is one OpenAI-compatible endpoint that routes your requests to models from many providers, using one key and one credit balance, which makes it easy to call from workflow tools like Activepieces as well as from your own code.

Understand OpenRouter API access and capabilities

What the OpenRouter API is

You send requests to a single base URL, https://openrouter.ai/api/v1, in the same request shape OpenAI's chat API uses. OpenRouter then forwards each request to whichever provider hosts the model you named, such as Anthropic, OpenAI, Google or DeepSeek.

One brass key on a ring entering a single small doorway in a wall, behind which the passage splits into four differently…

You authenticate once, with OpenRouter, and never hold a key from any of the four providers.

Because the providers sit behind OpenRouter, so do their differences. Each model carries its own price, and your credit balance, not a provider account, it's what gets drawn down.

When something fails, the error comes back through OpenRouter's own codes.

What you'll achieve with the OpenRouter API

By the end you'll have an authenticated request returning a completion from a model you chose, in minutes rather than a day. You'll also know where to look up what that request costs and what limits apply to your account.

You'll know what each error code means before one shows up in your logs at an inconvenient hour.

This was checked against OpenRouter's documentation on 5 December 2026. Pricing, limits and the model list change. Treat the docs as the source of record and this article as a map to them.

The quickstart is the page to keep open alongside it. If you'd rather skip code entirely, the same call can be made from a workflow in Activepieces, which allows unlimited flows on every plan, including free, and which a later section covers.

You need three things before the first call:

  1. An OpenRouter account.
  2. An API key created in that account.
  3. Credits on the account, because usage is billed against a credit balance rather than a provider subscription.

Everything below works on Activepieces' free plan. Start without code or a credit card.

Create an OpenRouter account and API key

Sign up at openrouter.ai, add credits, then create a key on the Keys page, in that order. A key made against an empty balance authenticates fine and then fails on paid models.

  1. Create an account and sign in.
  2. Add credits from the account's credits page. Paid models draw from this balance, so this step decides whether your first paid call works.
  3. Open Keys and choose to create a new key.
  4. Give it a name that says where it will run, such as the service or environment. When a key leaks or a bill looks wrong, the name is the only thing telling you which deployment to look at.
  5. Optionally set a credit limit (covered below), then create it.

Copy the key when it's shown. Treat it as a secret from that moment, because the dashboard isn't a place to retrieve it later.

Set a credit limit and store the key safely

Set a credit limit, which caps what one key can spend. Without one, a runaway loop or a leaked key can drain the whole account balance, and every other service sharing that balance stops with it.

A separate key per project, each with its own limit, keeps one failure from becoming everyone's failure.

Keep the key out of source files and put it in an environment variable:

export OPENROUTER_API_KEY="paste-your-key-here"

Once it's set, your code reads the variable, and the request carries it as a Bearer token:

curl https://openrouter.ai/api/v1/chat/completions \
 -H "Authorization: Bearer $OPENROUTER_API_KEY" \
 -H "Content-Type: application/json" \
 -d '{"model": "openai/gpt-6-luna", "messages": [{"role": "user", "content": "Say hello."}]}'

If that returns a completion, the key and the balance both work. If it returns an error, read the error body before changing anything. The authentication documentation describes the header format.

Bearer key versus OAuth PKCE for user-facing apps

When a request goes out with a Bearer key, it spends your credits, because the key belongs to you. That's correct for your own backend and wrong for an app where strangers do the typing.

A person at a restaurant counter handing their own credit card to a stranger who is typing at a keyboard, while a queue of…

For user-facing apps, OpenRouter documents an OAuth PKCE flow, in which the user signs in and your app receives a key tied to their account, so the usage is theirs and not yours.

Then there are management keys, which the docs also describe: they are for creating and administering other keys programmatically, not for sending completions.

They're worth reading about in the OpenRouter docs if you issue keys to teams or customers, since one that can mint keys deserves stricter handling than any single key it creates.

Activepieces AI providers configuration showing active keys for Anthropic, Google Gemini, and OpenAI with their project…

Send your first OpenRouter request and select model

To make your first request, send one POST to /api/v1/chat/completions with the key from the last section in a Bearer header and a model ID in provider/model form. Everything else is a variation on that call.

The steps:

  1. Export the key: export OPENROUTER_API_KEY=... so it stays out of your code.
  2. Pick a provider/model ID from GET /models.
  3. POST to /api/v1/chat/completions with Authorization: Bearer $OPENROUTER_API_KEY.
  4. Read choices for the text and usage for the token counts.
  5. Add a models array so a failure on one model doesn't end the request.
curl https://openrouter.ai/api/v1/chat/completions \
 -H "Authorization: Bearer $OPENROUTER_API_KEY" \
 -H "Content-Type: application/json" \
 -d '{"model": "openrouter/auto", "messages": [{"role": "user", "content": "Say hello."}]}'

Look in choices[0].message.content for the reply text. Read usage on every response: it reports the tokens you were billed for, so it's the number to reconcile against your credit balance.

Because the endpoint follows the OpenAI request shape, you keep the OpenAI SDK. Change two things: set base_url to https://openrouter.ai/api/v1 and pass your OpenRouter key as the API key.

Existing code then runs unchanged, but the model string now names a provider, and the bill follows that model's price, not a single vendor's.

Listing models and choosing between variants

To pick a model, call GET /models, which returns each model's ID, pricing and context length. Copy the ID from there instead of guessing it.

Some IDs carry a suffix such as :free. That's a different variant of the model, with its own terms. It isn't the same listing under another name, so check the limits the docs attach to it before you put it in front of users.

Fallbacks and provider routing options

Replace model with a models array and OpenRouter tries the entries in order if the first fails. To steer which providers serve a model, add a provider routing object in the request body.

A row of three differently coloured stepping stones across a stream, with a traveller's foot on the first, which has a…

Both are documented in the OpenRouter docs, including which errors trigger a fallback. Read that list before you rely on it. A fallback to a pricier model changes your cost, and usage is where you'll see it.

Easier to see it running than to read about it: set it up free, no card.

OpenRouter pricing and rate limits by account tier

Your tier does not change the per-token price, which follows the model. What changes by tier is the fee on credit purchases, how generous the free-model allowance is, and what happens when your balance reaches zero.

Read the last two columns of the table first, because they're where a prototype turns into an outage.

Tier Token price Free-model requests Per-minute cap Credit fee At zero credits
No credits Same as listed Smallest daily allowance Applies Not applicable Free models only
Small lifetime purchase Same as listed Larger daily allowance after purchase Applies Charged on purchase Free models only
Larger lifetime purchase Same as listed Larger daily allowance after purchase Applies Charged on purchase Free models only
BYOK Billed by your provider Not the point of this tier Provider's limits also apply Reduced fee Provider's billing governs

Confirm exact figures and their check dates on the pricing page and the rate-limit docs before you commit to a design.

Per-token pricing and the credit fee

Read per-token pricing from the /models endpoint, which returns it for each model, rather than from a screenshot or a blog post. Multiply by your expected tokens before you pick a default model.

A workflow execution interface showing a completed two-step Square OAuth token revocation flow with HTTP configuration

The credit fee is charged when you buy credits, not per request. Budget for it as a cost of topping up, because the credits you can spend are fewer than the amount you paid.

Free model limits versus paid accounts

When a model ID ends in :free, it has its own request caps, separate from paid models. Having purchased credits at some point raises the daily free allowance, but the per-minute cap still applies.

A free model is therefore fine for testing and a poor foundation for a workflow that must run every time. When a cap is hit, expect a rate-limit error and handle it with backoff.

Checking your balance and limits through the API

Query your balance and key details instead of waiting for a failure. The credits endpoint reports purchased and used totals, and the key endpoint reports the limit and usage attached to the key you're calling with.

Poll them on a schedule. An empty balance on a paid model returns a payment-related error, not a silent fallback to a free one.

Fix common OpenRouter API errors

That payment error is HTTP 402, one of eight status codes OpenRouter's errors documentation lists, and each one calls for a different response from your code.

Read the retry column first: only some of these failures are worth repeating. The table below condenses the documented cause of each code.

Code Documented cause Practical fix Retry?
400 Bad request: invalid or missing parameters Correct the request body No
401 Invalid credentials: bad, disabled or expired key Check or replace the key No
402 Insufficient credits Add credits, then resend No, until topped up
403 Input flagged by moderation Change the input No
408 Request timed out Resend, perhaps with a smaller prompt Yes
429 Rate limited Slow down and back off Yes, with backoff
502 Chosen model is down or returned an invalid response Retry or switch model Yes
503 No available provider meets your routing requirements Loosen constraints or switch model Yes

Retrying four of these codes only burns requests, since they need a human or a code change. The other four are transient.

Retries, backoff and model fallbacks

Back off exponentially on 429 and on 5xx responses, and add jitter so parallel workers don't retry in lockstep. Treat 402 as an alert, not a retry: watch your balance so it never reaches zero mid-job.

For 502 and 503, pass a fallback model so a dead route doesn't become a failed request. Check the errors page for the exact parameter.

Before you set a timeout, get some context. AILatency measured average latency through OpenRouter at 1,600 milliseconds in July 2026, 1,500 in August, 1,400 in September and 1,318 in October.

OpenRouter gateway latency month by month, 2026

But it's an average, not a ceiling. A timeout set near 1.3 seconds will cut off healthy requests, so set yours well above the average and tune it against your own slowest models.

Errors that appear mid-stream

Before the first token of a streamed response arrives, the 200 status has already gone out. If the model fails afterwards, the status line can't change, so the failure arrives inside the stream.

A client that checks only the status code will record success on a truncated answer.

Parse every chunk, look for an error object as well as content, and treat a stream that ends without a clean finish as failed.

A client that checks only the status code will record success on a truncated answer.

Call OpenRouter without code using Activepieces

With Activepieces, whose core is MIT-licensed, you can run the same chat completion inside a workflow, with no code. It handles the connection and the field mapping while you still own the model choice, the key's spending cap and the error handling.

Provider management interface showing configured AI API keys for multiple platforms including Gemini, Anthropic, and OpenAI…

Retries and fallbacks in your own workflow are your job; the builder doesn't decide them for you.

Add the OpenRouter connection and a first action

Create a connection by pasting an OpenRouter API key into the OpenRouter integration, one of the 751 integrations counted in Activepieces' open source monorepo. Use a key made for this workflow alone, with a credit limit set in the OpenRouter dashboard.

A runaway loop then stops at the cap instead of draining the account balance, and you can revoke one key without breaking anything else.

Next, add the chat completion action and type the model ID into its field exactly as OpenRouter's model page prints it. The ID is the string that tells OpenRouter which provider and model to route to.

A mistyped or retired ID comes back as an error from OpenRouter, not as a quiet substitution, so a failed step is worth reading before you rerun it.

Map a trigger's data into the prompt

In the screenshot below, a five-step automation is open in the Activepieces builder. Step 5, "Page Audit", is selected, and its panel shows a prompt field telling the model to produce an SEO audit with a 0-100 score and a 120-word summary.

Activepieces workflow builder showing a Page Audit step configured to use OpenAI's GPT-4o model for SEO analysis.

That prompt draws on the output of the earlier "Remove HTML Tags" step.

This particular step uses Activepieces' own Ask AI action with GPT-4o, not the OpenRouter integration. The mechanics are the same: the prompt is plain text with a reference to an earlier step's output dropped in.

Take from it the order of operations. Clean the data first, then hand the model only what it needs. Raw HTML pasted into a prompt is billed as input, and OpenRouter prices each model separately, so the stripping step is also a cost control.

In the OpenRouter action the pattern is the same. Pick a value from the trigger or a previous step, such as an email body or a form answer, and insert it into the prompt field beside your instructions.

If you already call the API from code, you gain little here. The value is for teams who want the call inside a workflow someone else can read and edit.

  1. Create a new OpenRouter key with a credit cap and name it for this workflow.
  2. Run one request with curl against the endpoint first, so you know the key and model ID work before the builder is involved.
  3. Add the key as an Activepieces connection and build the single action.
  4. Record the date you checked the model's pricing and limits on its OpenRouter page, and put a reminder to check again.

References

Share

Get started

Automate this without code.

Cloud or your own servers.

Start free Talk to sales