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, then set two environment variables — OPENAI_API_KEY and OPENAI_BASE_URL (usually https://api.openai.com/v1). 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 env var |
| 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):
npm install -g @openai/codex
Or use the official one-liner:
curl -fsSL https://chatgpt.com/codex/install.sh | sh
Verify:
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 is two environment variables. Codex reads them at runtime:
export OPENAI_API_KEY="sk-your-key"
export OPENAI_BASE_URL="https://api.openai.com/v1"
OPENAI_BASE_URLmust end in/v1with no trailing slash.- Add the exports to
~/.zshrc(macOS/Linux) or set them in Windows system environment variables to persist across sessions. - Codex also auto-loads a
.envfile at your project root — convenient for per-project keys:
# .env at project root
OPENAI_API_KEY=sk-your-key
Windows PowerShell
setx OPENAI_API_KEY "sk-your-key"
setx OPENAI_BASE_URL "https://api.openai.com/v1"
Reopen the terminal after setx, then confirm with env | grep OPENAI.
Step 4: Run Codex
Start an interactive session or run a one-shot task:
codex
codex "Add unit tests for the auth module"
If OPENAI_API_KEY is set, Codex uses the API key for authentication and ignores any logged-in ChatGPT session.
For scripts and CI, use one-shot mode — it returns output to stdout and is trivially automatable:
codex "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):
model = "gpt-5.5"
model_provider = "gateway"
[model_providers.gateway]
name = "TeamoRouter"
base_url = "https://gateway.teamorouter.com/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; "chat" → POSTs to /chat/completions. Most gateways use one or the other |
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:
codex --config model_provider=gateway --model gpt-5.5 "your task"
codex --config model_provider=openai-direct --model gpt-5.5 "..."
Reserved provider IDs:
openai,ollama, andlmstudioare 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 |
If the gateway serves /chat/completions, set wire_api = "chat"; 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 two variables (or one config.toml block), and the same key slides into every OpenAI-compatible tool you run:
export OPENAI_API_KEY="your-teamorouter-key"
export OPENAI_BASE_URL="https://gateway.teamorouter.com/v1"
Security Best Practices for API Keys
An API key is a password that spends money. Treat it accordingly:
- Never commit keys to git. Add
.envto.gitignoreand scan your history with tools likegit secretsorgitleaksbefore 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.envor 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:
- Create one shared key (or per-member keys) on the gateway.
- Store it in the team's secrets manager and inject it via CI environment variables.
- Track usage per member or per project through the gateway dashboard.
- 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?
If OPENAI_API_KEY is set, Codex uses the API key and ignores any logged-in ChatGPT session.
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.
Get Started
- Sign up for TeamoRouter and get an API key
- Follow the Codex install guide to configure env vars and base URL
- Run
codexin your terminal and start coding
Access Codex, Claude Code, and Gemini CLI stably through TeamoRouter.