
How to Mock the OpenAI API for Local Dev and Tests (No Token Burn)
Run an OpenAI mock locally so your AI app's tests and dev loop never spend tokens, never need a real key, and never flake on the model. Route the SDK through a proxy and return deterministic chat completions, tool calls, and embeddings.
To mock the OpenAI API, put a local proxy in front of the OpenAI SDK and return canned responses for /v1/chat/completions, tool calls, and /v1/embeddings. Your app code and SDK stay unchanged — only the network layer is intercepted. The result: tests that cost zero tokens, need no real API key, and return the same answer every run.
Why you should mock the OpenAI API
Calling the real OpenAI API from your dev loop and test suite is the default, and it is the wrong default for three concrete reasons:
- Cost. Every test run that hits
gpt-4or an embeddings endpoint spends real money. A CI matrix that runs on every push turns your test suite into a metered API bill. - Non-determinism. The model returns different text every call. Any assertion stronger than "the request didn't throw" is flaky by construction, so most teams stop asserting on the interesting part — the model output and the tool-call arguments.
- Secrets in CI. Hitting the real API means a live
OPENAI_API_KEYin every CI environment and every contributor's machine. That is a key surface area you do not need for testing your own code.
Mocking the API removes all three at once. You are not testing whether OpenAI works — you are testing whether your code handles a given response correctly. For that, a deterministic fake is strictly better than the real thing.
The approach: intercept at the network, not the SDK
The brittle way to mock OpenAI is to monkey-patch the SDK or inject a fake client. That couples your tests to the SDK's internal shape, breaks on every SDK upgrade, and never exercises your real request-building and response-parsing code.
The robust way is to intercept at the HTTP boundary. The OpenAI SDK ultimately makes an HTTPS request to api.openai.com. Put APXY — a local capture-and-mock proxy — in that path, and you mock the wire, not the library. Your app builds the real request, the proxy answers it, and your real parsing code runs against a controlled response.
1. Start the proxy
apxy start --port 80802. Mock a chat completion
Add a rule that matches the chat completions endpoint and returns a valid OpenAI response envelope:
apxy mock add \
--name "openai-chat-completion" \
--method POST \
--url "https://api.openai.com/v1/chat/completions" \
--status 200 \
--headers "Content-Type=application/json" \
--body '{"id":"chatcmpl-mock","object":"chat.completion","model":"gpt-4","choices":[{"index":0,"message":{"role":"assistant","content":"Mocked reply."},"finish_reason":"stop"}],"usage":{"prompt_tokens":9,"completion_tokens":3,"total_tokens":12}}'3. Point your app at the proxy
The OpenAI SDKs honor standard proxy environment variables, so you do not change a line of application code:
HTTPS_PROXY=http://localhost:8080 OPENAI_API_KEY=sk-test npm testOPENAI_API_KEY=sk-test is deliberate — the request never reaches OpenAI, so the key only has to satisfy the SDK's local "is a key present" check. No real secret in CI.
That is the entire loop: real SDK, real request, deterministic response, zero tokens.
Use the pre-built OpenAI template
You do not have to hand-write every envelope. APXY ships a ready-made OpenAI rule set covering the common endpoints:
curl -fsSL https://raw.githubusercontent.com/apxydev/apxy/main/mock-templates/openai/rules.json \
-o openai-rules.json
apxy mock import --file openai-rules.jsonBrowse the full list at apxy.dev/templates. Import it once and your local environment answers OpenAI calls immediately — useful for offline development and for onboarding contributors who do not have a key.
The hard parts: streaming, tool calls, and embeddings
Generic "mock a REST API" advice covers the simple case. LLM APIs have three response shapes that need specific handling.
Streaming (SSE) chat completions
When you call with stream: true, OpenAI returns Server-Sent Events: a sequence of data: lines, each a partial chunk, terminated by data: [DONE]. To exercise your streaming parser, the mock body must be that exact SSE shape:
apxy mock add \
--name "openai-chat-stream" \
--method POST \
--url "https://api.openai.com/v1/chat/completions" \
--status 200 \
--headers "Content-Type=text/event-stream" \
--body 'data: {"choices":[{"delta":{"content":"Mock"}}]}
data: {"choices":[{"delta":{"content":" reply"}}]}
data: {"choices":[{"delta":{},"finish_reason":"stop"}]}
data: [DONE]
'Now your for await (const chunk of stream) loop runs against a deterministic stream — you can assert on the assembled text, something you can never do reliably against the live model.
Tool / function calls
The interesting branch in most agent code is "the model decided to call a tool." That path almost never gets tested because you cannot make the real model reliably emit a specific tool_calls payload. With a mock you make it deterministic:
apxy mock add \
--name "openai-tool-call" \
--method POST \
--url "https://api.openai.com/v1/chat/completions" \
--status 200 \
--headers "Content-Type=application/json" \
--body '{"id":"chatcmpl-mock","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":null,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Berlin\"}"}}]},"finish_reason":"tool_calls"}]}'Your tool-dispatch logic now has a stable, repeatable input on every test run.
Embeddings
For retrieval and similarity code, mock /v1/embeddings with a fixed vector so your nearest-neighbour assertions are stable:
apxy mock add \
--name "openai-embeddings" \
--method POST \
--url "https://api.openai.com/v1/embeddings" \
--status 200 \
--headers "Content-Type=application/json" \
--body '{"object":"list","data":[{"object":"embedding","index":0,"embedding":[0.01,0.02,0.03]}],"model":"text-embedding-3-small","usage":{"prompt_tokens":5,"total_tokens":5}}'Mock the failure cases too
The responses that actually break production are the error cases, and they are the ones you almost never see in manual testing: a 429 rate limit, a 503 overload, a context-length 400. Add rules for them and you can finally test your retry and back-off logic on demand:
apxy mock add \
--name "openai-rate-limit" \
--method POST \
--url "https://api.openai.com/v1/chat/completions" \
--status 429 \
--headers "Content-Type=application/json" \
--body '{"error":{"message":"Rate limit reached","type":"rate_limit_error"}}'Add --delay 5000 to a rule to simulate a slow upstream and verify your timeout handling. This is the same pattern described in The Real Cost of Flaky API Tests — the cheapest way to make a test reliable is to control the dependency, not to retry around it.
Build mocks from real responses
You do not have to invent payloads by hand. Run your app against the real API once with the proxy capturing, then promote the captured response to a mock rule. That is the Record & Replay workflow covered in Record and Replay API Traffic for Regression Testing: your mock then reflects exactly what OpenAI returned, including fields you would have forgotten to fake. For the general single-endpoint walkthrough, see How to Mock a REST API in 5 Minutes.
Frequently asked questions
Do I need to change my application code to mock OpenAI?
No. The OpenAI SDKs route through standard HTTPS_PROXY settings, so you point the environment at APXY and your code builds and parses the same real request and response. The mock lives entirely at the network layer.
Can I mock streaming chat completions?
Yes. Set the response Content-Type to text/event-stream and make the body the SSE chunk sequence ending in data: [DONE]. Your streaming parser then runs against a deterministic stream and you can assert on the assembled output.
How do I test rate limits and errors without hitting OpenAI?
Add a rule that matches /v1/chat/completions and returns 429, 503, or a 400 error envelope. Use --delay to simulate a slow upstream. You can now trigger retry and back-off code paths on every test run instead of waiting for a real outage.
Do I still need a real OpenAI API key in CI?
No. Because the request never leaves your machine, the SDK only needs a syntactically present key like sk-test. You remove the live secret from CI and from every contributor's environment.
Will mocked tests still cost tokens?
Zero. The request is answered by the local proxy and never reaches OpenAI, so there is no token usage and no API bill — the entire point of mocking the API for tests.
Summary
Hitting the real OpenAI API from your tests is slow, non-deterministic, and metered. Put APXY in front of the SDK, return controlled responses for chat completions, streaming, tool calls, embeddings, and errors, and your AI app's test suite becomes free, deterministic, and key-free. Install APXY for free and import the OpenAI mock template to have it answering calls in under five minutes. Building the app with an agent? See APXY with Claude Code.
Debug your APIs with APXY
Capture, inspect, mock, and replay HTTP/HTTPS traffic. Free to install.
Install FreeRelated articles
Why Your AI Coding Agent Needs Network Visibility
AI coding agents are excellent at reading code. They cannot see the network. That gap is where most agent-assisted debugging sessions get stuck. Here is how to close it.
GuideWhat is API Mocking? A Developer's Guide
API mocking lets you simulate a real API without calling it. This guide explains what it is, why developers use it, when to mock vs when not to, and how to get started in under five minutes.