Blog

Codex API Key Setup: Complete Guide for Developers (2026)

Quick Answer

To use Codex with an API key in 2026: install the CLI (npm install -g @openai/codex), get a key from platform.openai.com, set OPENAI_API_KEY, then register it with printenv OPENAI_API_KEY | codex login --with-api-key (the official endpoint is the default, so no base URL is needed). For custom or gateway providers, define a [model_providers.<id>] block in ~/.codex/config.toml and switch with --config model_provider=<id>. If you want one key that works for Codex, Claude Code, and Gemini CLI with no international payment headache, a gateway like TeamoRouter replaces the whole setup with a single OpenAI-compatible endpoint.

Why API Keys Beat ChatGPT Login for Developers

Codex CLI supports two authentication paths: ChatGPT OAuth login and API keys. For most developer workflows the API key is the better choice:

  • Programmability — CI/CD pipelines, scripts, and background agents cannot use a browser login to call an API.
  • Usage-based billing — you see exactly what each request costs, with no subscription-expiry surprises.
  • Multi-tool sharing — one key works across Codex CLI, IDE plugins, and custom applications.
  • Team collaboration — a shared key (or pooled gateway key) centralizes billing and usage tracking.

The friction with getting an OpenAI key directly: international payment (foreign card required) and network restrictions from certain regions. A gateway removes both.

ChatGPT Login vs API Key: Which Should You Use?

Aspect ChatGPT Login API Key
Setup codex login with OAuth in the browser Set OPENAI_API_KEY, then codex login --with-api-key
Billing Tied to ChatGPT subscription Pay-per-use, prepaid credits
Scripting / CI Not available Fully supported
Sharing across tools No Yes — one key, many tools
When to use Quick personal tinkering Anything programmatic or repeatable

Use OAuth for occasional interactive tinkering; use an API key the moment you script, automate, share, or deploy.

Step 1: Install the Codex CLI

Install globally via npm (Node.js 22+ recommended):

bash
npm install -g @openai/codex

Or use the official one-liner:

bash
curl -fsSL https://chatgpt.com/codex/install.sh | sh

Verify:

bash
codex --version

Step 2: Get an API Key

Create a key at platform.openai.com/api-keys. Copy it once — OpenAI does not show it again after creation. Keys look like sk-....

If you do not have a foreign card to fund the account, or your region blocks the platform, skip to the gateway section below.

Step 3: Configure Environment Variables

The simplest setup: put the key in an environment variable, then register it with Codex once:

bash
export OPENAI_API_KEY="sk-your-key"
printenv OPENAI_API_KEY | codex login --with-api-key
  • No base URL is needed for the official endpoint — it is the default. Current Codex does not read an OPENAI_BASE_URL environment variable; a custom endpoint goes in ~/.codex/config.toml as base_url (ending in /v1, no trailing slash) — see the config.toml section below.
  • Add the exports to ~/.zshrc (macOS/Linux) or set them in Windows system environment variables to persist across sessions.
  • Codex also auto-loads ~/.codex/.env (it does not read a .env at your project root). A key stored there is picked up by a custom provider's env_key (see the config.toml section below):
bash
# ~/.codex/.env
OPENAI_API_KEY=sk-your-key

Windows PowerShell

powershell
setx OPENAI_API_KEY "sk-your-key"

Reopen the terminal after setx, confirm with Get-ChildItem Env:OPENAI*, then register the key with $env:OPENAI_API_KEY | codex login --with-api-key.

Step 4: Run Codex

Start an interactive session or run a one-shot task:

bash
codex
codex exec "Add unit tests for the auth module"

After codex login --with-api-key, Codex authenticates with the API key. Setting OPENAI_API_KEY alone is not enough for the built-in OpenAI provider.

For scripts and CI, use one-shot mode — it returns output to stdout and is trivially automatable:

bash
codex exec "Summarize the changes in the last 10 commits"

Interactive mode (codex with no arguments) is better for exploratory work where you want to review each step as it happens. Most teams use a mix: interactive for design and review, one-shot for grunt work and pipelines.

Advanced: Config.toml Model Providers

For multiple providers, custom endpoints, or per-provider settings, define [model_providers.<id>] blocks in ~/.codex/config.toml (macOS/Linux) or %USERPROFILE%\.codex\config.toml (Windows):

toml
model = "gpt-5.5"
model_provider = "gateway"

[model_providers.gateway]
name = "TeamoRouter"
base_url = "https://api.teamorouter.vip/v1"
env_key = "OPENAI_API_KEY"
wire_api = "responses"
requires_openai_auth = false

Key fields:

Field Purpose
base_url API root, ending in /v1 for OpenAI-compatible endpoints, no trailing slash
env_key Environment variable Codex reads for the Bearer token — never hard-code keys in TOML
wire_api "responses" → POSTs to /responses. Current Codex accepts only "responses" — "chat" is no longer supported
requires_openai_auth Set false for gateways whose keys do not start with sk-
http_headers Static headers merged into every request

Switch providers on the command line:

bash
codex --config model_provider=gateway --model gpt-5.5 "your task"
codex --config model_provider=openai --model gpt-5.5 "..."

Reserved provider IDs: openai, ollama, and lmstudio are taken — use different names for custom providers.

Common API Key Errors and Fixes

Error Cause Fix
401 Unauthorized / invalid_api_key Wrong or expired key Re-copy the key, check for whitespace, confirm it is still active
404 Not Found Wrong wire_api or base URL Set wire_api = "responses" ("chat" is no longer supported); confirm base_url ends in /v1
insufficient_quota No balance on the account Top up the account (or the gateway wallet)
model_not_found / permission error Model not enabled for the key Use the exact model ID the endpoint supports; gateways expose multiple models under one key
Connection timeout Network path blocked See Codex Request Timed Out? 7 Fixes

The Gateway Shortcut: One Key for Everything

If any of these steps gave you pause — a foreign card requirement, region blocks, or managing five provider configs — the pragmatic 2026 shortcut is a unified gateway.

TeamoRouter gives you:

  • One API key for Codex, Claude Code, and Gemini CLI — the same key works in each tool's config.
  • Local payment — Alipay and WeChat Pay, no foreign card needed, low minimum top-up.
  • Stable access — the endpoint is directly reachable from restricted networks, eliminating proxy/DNS failures.
  • Cost control — prompt caching (>99% hit rate) and floating-rate discounts vs. official pricing.

Setup is one config.toml block plus one variable, and the same key slides into every OpenAI-compatible tool you run:

toml
# ~/.codex/config.toml
model_provider = "teamorouter"
model = "gpt-6.1-sol"

[model_providers.teamorouter]
name = "TeamoRouter"
base_url = "https://api.teamorouter.vip/v1"
env_key = "OPENAI_API_KEY"
wire_api = "responses"
bash
export OPENAI_API_KEY="your-teamorouter-key"

Security Best Practices for API Keys

An API key is a password that spends money. Treat it accordingly:

  • Never commit keys to git. Add .env to .gitignore and scan your history with tools like git secrets or gitleaks before pushing.
  • Scope the key. Create separate keys for local development, CI, and production so you can revoke one without breaking everything.
  • Rotate periodically. If a team member leaves or a key leaks, revoke and re-issue immediately.
  • Use environment variables, not shell history. Avoid export OPENAI_API_KEY=... inline in files; source it from an uncommitted .env or a secrets manager.
  • Watch your usage. Set up billing alerts on the platform so unusual spend is visible before it becomes a surprise invoice.
  • Prefer gateway keys for teams. A pooled gateway key with per-member usage tracking keeps spend centralized instead of scattered across individual OpenAI accounts.

Using Codex API Keys on a Team

Teams get the most value from API keys when billing and access are centralized:

  1. Create one shared key (or per-member keys) on the gateway.
  2. Store it in the team's secrets manager and inject it via CI environment variables.
  3. Track usage per member or per project through the gateway dashboard.
  4. Rotate the key quarterly or on any offboarding.

This is materially simpler than each developer running their own OpenAI account with their own card — and it is why gateway-based setups are the default for teams in 2026.

FAQ

Can I use the API credits that come with ChatGPT Plus?

No. ChatGPT Plus subscription ($20/month) and API usage billing are completely independent. Plus credits only work on chat.openai.com and cannot be consumed via an API key — and API usage does not count toward your Plus subscription.

Can one API key be used across Codex CLI and other tools?

Yes. The same key works for Codex CLI, IDE plugins, and custom apps. TeamoRouter's unified key supports Codex, Claude Code, and Gemini CLI simultaneously — just configure each tool's base URL.

Is there a risk of API key leakage?

Yes, if you hard-code a key in source code and commit it to GitHub. Use environment variables or .env files, and add .env to your .gitignore. Treat keys like passwords.

Which takes priority — OPENAI_API_KEY or ChatGPT login?

The built-in OpenAI provider does not read the OPENAI_API_KEY variable: it uses the credential you saved with codex login (ChatGPT) or codex login --with-api-key (API key). A custom provider in config.toml, such as TeamoRouter, reads the key from the variable named in its env_key.

Does TeamoRouter require a credit card to get an API key?

No. Sign up to get an API key, prepay before use, and pay with Alipay or other local methods with a low minimum top-up. Outside China you can pay by card.

Get Started

  1. Sign up for TeamoRouter and get an API key
  2. Follow the Codex install guide to configure env vars and base URL
  3. Run codex in your terminal and start coding

Get Your Free Codex Setup →

Access Codex, Claude Code, and Gemini CLI stably through TeamoRouter.

Ready to connect?Log in · top up · create an API key — three steps to start.