Using an API key with Claude Code and Codex: setup, custom endpoints, and switching back
How to run Claude Code or Codex with an API key or custom endpoint, what changes from a subscription, how to switch back, and how to manage keys per session.


The short answer
Both Claude Code and Codex can run on a pay-as-you-go API key instead of a monthly subscription. In Claude Code, set ANTHROPIC_API_KEY from the Claude Console and approve it when prompted (or sign in to Console with /login without creating a static key). In Codex CLI, pipe an OpenAI key into codex login --with-api-key, or pass CODEX_API_KEY inline for non-interactive runs like codex exec. Both also let you point requests at a gateway or compatible endpoint.
| Claude Code | Codex | |
|---|---|---|
| Where to get a key | platform.claude.com | platform.openai.com/api-keys |
| CLI setup | Set ANTHROPIC_API_KEY, run claude, approve once | printenv OPENAI_API_KEY | codex login --with-api-key |
| CI / non-interactive | claude -p always uses ANTHROPIC_API_KEY when set | Set CODEX_API_KEY inline for codex exec or review |
| Custom endpoint | ANTHROPIC_BASE_URL + ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY | openai_base_url or [model_providers.*] in ~/.codex/config.toml |
| Check active auth | /status | codex login status |
Using an API key in Claude Code
Anthropic gives you two ways to pay per token in Claude Code: set a static ANTHROPIC_API_KEY, or pick “Sign in with your Console account” during /login (which stores an OAuth token and creates no key). For rotating credentials from a vault, configure an apiKeyHelper script in settings.
# Direct Anthropic API (Claude Code asks once to approve it)
export ANTHROPIC_API_KEY="YOUR_ANTHROPIC_KEY"
claude
# Custom gateway using a bearer token
export ANTHROPIC_BASE_URL="https://gateway.example.com"
export ANTHROPIC_AUTH_TOKEN="YOUR_GATEWAY_TOKEN"
claude- Header difference:
ANTHROPIC_API_KEYsendsX-Api-Key;ANTHROPIC_AUTH_TOKENsendsAuthorization: Bearerand takes precedence overANTHROPIC_API_KEY. - Toggle without unsetting: while
ANTHROPIC_API_KEYis in your shell,/configshows a “Use custom API key” toggle so you can turn it off or back on. - Base URL alone isn't enough: setting
ANTHROPIC_BASE_URLwithout a gateway credential keeps your saved claude.ai subscription login active.
Using an API key in Codex
In the ChatGPT desktop app, pick “Sign in another way” on the signed-out screen; in the IDE extension, pick “Use API Key”. In the CLI, pipe the key into codex login --with-api-key for interactive sessions, or set CODEX_API_KEY inline for scripted runs (codex exec, review, or the TypeScript SDK).
# Sign in interactively with a key from your environment
printenv OPENAI_API_KEY | codex login --with-api-key
# Non-interactive run with an inline key (recommended over job-wide env in CI)
CODEX_API_KEY="YOUR_OPENAI_KEY" codex exec "Run the test suite and summarize failures"
# Switch back to a ChatGPT subscription
codex logout && codex loginTo route Codex through a proxy or another OpenAI-compatible provider, edit your personal ~/.codex/config.toml — Codex ignores model_providers and openai_base_url in a repository's .codex/config.toml for safety.
model = "gpt-6.2-sol"
model_provider = "my_gateway"
[model_providers.my_gateway]
name = "OpenAI-compatible gateway"
base_url = "https://gateway.example.com/v1"
env_key = "OPENAI_API_KEY"What changes compared to a subscription
- Billing and limits: API-key sessions pay per token on your Console or OpenAI Platform account and don't draw on your 5-hour or weekly subscription allowance.
- Cloud features: Codex cloud and Work Cloud local computer access require signing in with ChatGPT, not an API key. In Claude Code, Remote Control needs Claude Code talking to
api.anthropic.com. - Data and admin policy: with an API key, Codex follows your API organization's retention and data-sharing settings rather than ChatGPT workspace policies; Claude Code follows your Console org policy.
Common API key errors (401, 403, 429)
- 401 / Invalid API key
- The key is revoked, mistyped, or sent with the wrong header (for example
ANTHROPIC_API_KEYwhen your gateway expectsANTHROPIC_AUTH_TOKEN, or a leftoverANTHROPIC_API_KEYoverriding your login). Check/statusin Claude Code orcodex login statusin Codex, then re-export or re-login. - 403 / Organization or API key disabled
- An admin disabled API key login (
Your organization has disabled API key authentication), the key belongs to a disabled organization, or the model/region isn't enabled for that key. Remove the old key or check your Console / Platform organization settings. - 429 / Credit balance too low or spend limit
- Your API account hit its rate limit, ran out of prepaid credits (
Credit balance is too low), or hit a monthly spend cap. Check billing and usage limits in Console or OpenAI Platform, or switch the session to another model or account.
Switching keys and credit per session in Mirasim
Instead of editing shell profiles every time you move between a subscription, your own API key, and a custom endpoint, Mirasim lets you pick who pays for each session right in the composer — and switch back anytime.
- Add any provider once: in Settings › Models › Model providers, add Anthropic, OpenAI, Google, or any OpenAI-compatible endpoint (including OpenRouter) and scan its models. Mirasim also translates protocols so Claude Code can talk to OpenAI-compatible endpoints.
- Import what you already have: Settings › Models › Import existing setup reads CC Switch, claude-code-router, Claude Code and Codex config files, and
ANTHROPIC_API_KEY/OPENAI_API_KEYwithout changing your original files, storing keys in the system keychain. - Zero credit fee for your own keys: set “Paying with” to “API key” in the composer (or set an agent's default in Settings › Agents). Sessions on your own API key or local subscription don't use Mirasim credit.
- Or use Mirasim credit per token without separate API billing accounts: Claude Opus 5.5 50% off, Sonnet 5.5 50% off, and GPT-6.2 Sol Limited time: 90% off off official API prices.
Chapter 16 · Models, accounts and quota › Bring your own keys → Bring your own keys, and importing from CC Switch or config files.
Questions
- Should I use an API key or a monthly subscription?
- Light or occasional use, CI automation, and custom endpoints fit an API key. Heavy daily coding is usually cheaper on a subscription until you hit its rolling limits.
- Can I use OpenRouter with Claude Code or Codex?
- Codex talks to OpenAI-compatible endpoints via
[model_providers.*]in~/.codex/config.toml. In Mirasim, add OpenRouter once under Settings › Models › Model providers and both Codex and Claude Code can use it per session. - Why is Claude Code still billing my API key after I subscribed?
ANTHROPIC_API_KEYoutranks a/loginsubscription once approved. Rununset ANTHROPIC_API_KEY, remove it from your shell profile, and check/status.
Article · Claude Code login: how to sign in, switch accounts, and fix login problems → Claude Code login: sign-in flows, multiple accounts, and login errors.
Article · Codex login: sign in with ChatGPT or an API key, sign in on a server, and fix login problems → Codex login: ChatGPT vs. API key, credential storage, and SSH.
Article · Claude Code pricing: what each plan costs, what the API costs, and paying only for what you use → Claude Code pricing: plans vs. API rates.
Article · Codex pricing: what each ChatGPT plan includes, what an API key costs, and paying only for what you use → Codex pricing: ChatGPT plans vs. API rates.
Article · Claude Code errors: fixing 529 Overloaded, 429, Prompt is too long, and connection errors → Fixing Claude Code 529 Overloaded, 429, Prompt is too long and connection errors.
Article · Running Claude Code and Codex with Ollama: local models, 64k context, and setup → Full setup guide for running Claude Code and Codex with Ollama and local models.
Article · Running Claude Code and Codex in GitHub Actions: setup, secrets, and safety → Running Claude Code and Codex in GitHub Actions CI workflows.
Article · Running Claude Code (`claude -p`) and Codex (`codex exec`) in scripts and CI → Running `claude -p` and `codex exec` non-interactively in scripts and CI.
Article · Running Claude Code and Codex on Amazon Bedrock, Vertex AI, and Microsoft Foundry → Running Claude Code and Codex through Amazon Bedrock, Google Cloud Vertex AI, or Microsoft Foundry.
Article · Fixing OpenAI and Codex 403 “unsupported_country_region_territory” → Getting 403 unsupported_country_region_territory from OpenAI? Checking false positives and alternatives.
Sources
Checked on November 28, 2026 against Anthropic's Claude Code docs (code.claude.com/docs: Authentication, Connect to an LLM gateway, Errors) and OpenAI's Codex docs (learn.chatgpt.com/docs: Authentication, Environment variables, Advanced configuration). Check those pages for current flags and limits.
Keep reading

Fixing OpenAI and Codex 403 “unsupported_country_region_territory”
Why OpenAI and Codex return 403 unsupported_country_region_territory, how to fix false positives on VPNs or cloud IPs, and compliant alternatives.

Running Claude Code and Codex on Amazon Bedrock, Vertex AI, and Microsoft Foundry
Connect Claude Code and Codex to Amazon Bedrock, Vertex AI, and Microsoft Foundry: env vars, config.toml, auth, model pinning, and limits.

Using Claude Code with Chrome and Codex Browser: live debugging, Playwright, and previews
How to connect Claude Code to Chrome (extension, console logs, login limits) and use Codex Browser or Playwright, plus live dev-server previews in Mirasim.