How to Set Up an OpenAI API Connection on Claude Code
In this article
- What is the best way to connect to the OpenAI API from inside Claude Code?
- How to set the OpenAI API key before you start
- How to scaffold the OpenAI SDK with Claude Code
- Key prompts to use during the integration
- How to use the MCP approach for persistent tool access
- Comparing integration approaches
- How to avoid losing progress to a usage limit mid-integration
- Key takeaways
- Sources
You can connect to the OpenAI API inside Claude Code by storing your API key as an environment variable, then prompting Claude to scaffold the SDK integration or HTTP calls you need. Claude Code handles the boilerplate, keeps secrets out of source files, and lets you iterate on the integration without switching contexts. To avoid hitting your Claude usage ceiling mid-task, use Usagebar to monitor your remaining quota from the macOS menu bar.
- Works on any stack: Node.js, Python, or raw HTTP
- OpenAI maintains official SDKs for JavaScript/TypeScript and Python with full TypeScript types
- Claude Code's
/usagecommand shows your Anthropic quota; Usagebar shows it persistently without breaking flow
What is the best way to connect to the OpenAI API from inside Claude Code?
The cleanest approach is to export OPENAI_API_KEY in your shell profile or a .env file (git-ignored), then ask Claude Code to wire up the SDK. Claude reads the environment, writes the integration code, and runs it immediately, all inside the same session. No tab-switching, no copy-pasting keys into editors.
How to set the OpenAI API key before you start
Claude Code inherits environment variables from the shell that launched it. The safest pattern is a project-level .env file loaded at runtime, so the key is never committed.
Option 1: shell export (quick test)
export OPENAI_API_KEY="sk-..."
claude # launch Claude Code in your project directory
Option 2: .env file (recommended for projects)
Create a .env at the project root:
OPENAI_API_KEY=sk-...
Then add .env to .gitignore. Claude Code will surface the variable to any code it runs or generates in that session. According to Anthropic's Claude Code documentation, Claude Code runs commands in your local shell context, so variables you export are available immediately.
Option 3: macOS Keychain (most secure)
Store the key in macOS Keychain and retrieve it at launch:
security add-generic-password -a "$USER" -s "openai-api-key" -w "sk-..."
export OPENAI_API_KEY=$(security find-generic-password -a "$USER" -s "openai-api-key" -w)
This mirrors how Usagebar stores your Anthropic credentials: keys in Keychain, never in plaintext.
How to scaffold the OpenAI SDK with Claude Code
Once the key is in the environment, delegate the scaffolding to Claude. Concrete prompts work far better than vague requests.
For a Node.js / TypeScript project
Type this directly in the Claude Code session:
> install the openai npm package and create a helper module at src/lib/openai.ts
that exports a pre-configured OpenAI client using OPENAI_API_KEY from process.env.
Add a typed wrapper for chat completions.
Claude will run npm install openai, create the file, and confirm the types compile. The official OpenAI Node SDK is fully typed, so Claude can also generate correct interface definitions for request and response shapes.
For a Python project
> install openai with pip, then create openai_client.py that initialises
the OpenAI client from OPENAI_API_KEY and exposes a simple chat() helper.
Claude handles pip install openai, writes the module, and can run a quick smoke test in the same turn.
Key prompts to use during the integration
These prompts are effective inside an active Claude Code session:
- Validate the key: "Make a minimal API call to /v1/models and print the response so we can confirm the key works."
- Add streaming: "Update the chat helper to support streaming responses using the stream option."
- Error handling: "Wrap calls in proper error handling for RateLimitError and AuthenticationError from the openai SDK."
- Switch model: "Change the default model to gpt-4o and add a parameter to override it per call."
- Add retries: "Use tenacity to add exponential backoff for rate limit errors." (Python)
For more on structuring prompts effectively, see how to do API documentation on Claude Code and how to do API testing on Claude Code.
How to use the MCP approach for persistent tool access
If you need Claude Code itself to call the OpenAI API as a tool during a session (not just generate code that calls it), you can register a custom Claude Code skill via MCP. This is an advanced pattern: define an MCP server that wraps OpenAI endpoints, then reference it in your .claude/settings.json. Claude Code will surface those as first-class tools it can invoke.
For most integrations, the SDK approach above is sufficient. Reserve MCP for cases where you want Claude to dynamically query OpenAI models as part of multi-step agentic tasks.
Comparing integration approaches
| Approach | Best for | Key tradeoff |
|---|---|---|
| SDK via npm / pip | Most projects | Simplest, fully typed, officially maintained |
| Raw HTTP (fetch / httpx) | Zero-dependency scripts | More manual error handling |
| MCP skill registration | Agentic multi-step workflows | More setup, but Claude can invoke the API itself |
| Proxy / gateway (LiteLLM) | Multi-provider routing | Adds infra, enables model-agnostic code |
How to avoid losing progress to a usage limit mid-integration
Wiring up a third-party API is exactly the kind of task where getting hit by a 5-hour Claude usage lockout is most painful: you are mid-conversation with context built up, files partially modified, and a test suite half-fixed. Claude Code usage limits reset on a rolling window, and the default CLI gives you no real-time signal before the wall hits.
The /usage command shows a snapshot, but you have to remember to type it. Usagebar sits in the macOS menu bar and shows your live quota at a glance, with alerts at 50%, 75%, and 90% so you know to wrap up or checkpoint before the cutoff. If you are a student, Usagebar is free. Otherwise it is pay-what-you-want.
See also: how to check your Claude Code usage limits, when Claude Code usage resets, and how to reduce Claude Code token usage.
Key takeaways
- Export
OPENAI_API_KEYvia.envor shell before launching Claude Code - Prompt Claude to install the official SDK and scaffold a typed helper module
- Use targeted prompts to add streaming, retries, and error handling incrementally
- For advanced agentic use, register an MCP skill to let Claude invoke OpenAI directly
- Monitor your Claude quota in real time with Usagebar to avoid a mid-task lockout
Ready to stay in flow? Get Usagebar for instant download and flexible pricing, including a free tier for students.
Sources
Never Get Locked Out Mid-Task Again
Never hit your usage limits unexpectedly. Usagebar lives in your menu bar and shows your 5-hour and weekly limits at a glance.
Get Usagebar$9 — one-time, lifetime updates