How to test a paid campaign API locally (without Meta spend or a hosted sandbox)
You are wiring create → activate → spend → stop → refund against a paid-campaign API. Production keys move real wallet balance. Meta still reviews creatives. A second hosted environment means another deploy, another key, and another place for the contract to drift.
Meta’s own Marketing API sandbox ad account doesn’t close this gap either. It accepts API calls without delivering ads, but it returns no Insights, and it knows nothing about a Soundlink wallet, a campaign fee, or a refund.
You need the same request shapes and the same wallet math on your laptop. That is what a stateful API emulator is for.
Why teams ship emulators now
This pattern shows up in a lot of API work now.
AWS recently shipped a local emulator so SDKs can hit the same APIs on your machine without creating billable cloud resources. Stripe has long used a different shape of the same idea: sandbox / test mode, where sk_test_… and sk_live_… hit the same API surface with isolated data and no real money moving.
For a paid campaign API, you want the same outcome at a smaller scale: exercise create, spend, and refund without Meta delivery and without touching a live wallet. A local emulator covers that today. A hosted test mode (closer to Stripe’s model) is something we may add later if partners need a shared sandbox without running a process on the laptop.
| Pattern | How you select it | Where state lives | Good for |
|---|---|---|---|
| Local emulator | Point the client at 127.0.0.1 |
Your process / machine | CI, offline loops, no second environment |
| Hosted test mode | Test key (or flag) against the real host | Provider-side sandbox | Shared QA and demos |
| Production | Live key | Live account | Real spend and real delivery |
Stateful emulator ≠ static mock
A static mock returns a fixed JSON blob. That fails the first time refund depends on fee rate and media spend.
Example: a campaign at $10/day for 7 days commits $70. You activate it, spend $40 on media, then stop. With a 10% plan fee, the refund is about $25.56, not $30. You can’t hard-code that once. The emulator keeps wallet, committed amount, spend, and fee in memory and settles the way the Public API does.
If your test only asserts status === 'ended', a mock is enough. If your test asserts wallet available after stop, you need state.
Four layers that make the loop useful
- Contract: same paths and error codes as the Public API (
invalid_request,insufficient_credit,idempotency_key_conflict, …). - In-memory store: campaigns, wallet, idempotency keys. Restart or
resetclears it. - Harness transitions: the events production leaves to Meta or to time, like
activate,reject_meta,set_spend,end, and creative disapproval. - Real client: the official TypeScript SDK, or any HTTP client, pointed at the local base URL. Your integration code should not special-case “emulator mode” beyond config.
What to emulate vs what to leave alone
Be explicit about fidelity and non-goals.
| Emulate | Do not pretend |
|---|---|
POST /v1/campaigns, stop, wallet debit/refund |
Real Meta delivery or real CPM |
| Idempotency-Key rules | OAuth sign-in flows mixed into the same process |
| Fee-aware refund math | Live Insights from Meta |
| Injected edges: Meta reject, insufficient credit, creative disapproval, timeouts, 500s | Security or abuse testing as if it were production |
Deterministic metrics seeds after activate |
“This spend number will match production tomorrow” |
An emulator that claims 100% production parity is lying. An emulator that matches the paths you integrate against, and fails loudly on the rest, is useful.
Workflow: create → refund on your machine
The emulator ships in the soundlink npm package from 2.10.0. Install the latest version to get every harness action below.
import { Soundlink } from "soundlink";
import { createApiEmulator } from "soundlink/api-emulator";
const apiKey = "sk_emulator_test";
const emu = createApiEmulator({
apiKey,
initialWalletBalance: 500,
plan: "enterprise", // 10% fee preset, so the refund math is real
});
const server = await emu.listen(); // loopback only
const soundlink = new Soundlink({ apiKey, baseUrl: server.baseUrl });
const { data: created } = await soundlink.campaigns.create(
{
spotifyUrl: "https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7Rh",
dailyBudget: 10,
durationDays: 7,
genre: "Pop",
strategyType: "maximum_growth",
},
{ idempotencyKey: "demo-1" },
);
await emu.transition(created!.campaignId, "activate");
await emu.transition(created!.campaignId, "set_spend", 40);
await soundlink.campaigns.stop(created!.campaignId, {
idempotencyKey: "stop-1",
});
const { data: wallet } = await soundlink.wallet.get();
// refund ≈ 25.56, so available ≈ 455.56 and reserved === 0
await server.close();Harness actions you will use often:
| Action | Effect |
|---|---|
activate |
creating → active, seeds overview metrics |
set_spend |
Sets media spend before refund |
reject_meta |
→ inactive without refund (a later stop refunds in full) |
end |
→ ended, then the same refund as stop |
disapprove_creatives |
Creatives children report delivery_state: "disapproved" |
Not a TypeScript shop? Use plain HTTP
listen starts a normal HTTP server. Start it once from a small Node script with a fixed port (emu.listen({ port: 8787 })), then call it from your Python, PHP, or Go backend with any HTTP client. Same Authorization: Bearer header, same paths, same JSON.
curl -s http://127.0.0.1:8787/v1/ping \
-H "Authorization: Bearer sk_emulator_test"
curl -s -X POST http://127.0.0.1:8787/__emulator/campaigns/CAMPAIGN_ID/transition \
-H "Content-Type: application/json" \
-d '{ "action": "activate" }'The server binds to 127.0.0.1 only. Harness routes under /__emulator have no auth on purpose, which is why non-loopback hosts are refused.
Test the failures, not only the happy path
Retries and idempotency are where integrations break in production. The emulator can fail the next authenticated call on demand:
timeout: the request hangs, so you can check your client timeoutconflict: one409 idempotency_key_conflictserver_error: a500long enough to exhaust the SDK’s default retries, then the next call succeeds
Arm it with emu.failNext('server_error') in-process, or POST /__emulator/fault over HTTP. For unit tests that don’t need a socket, emu.dispatch({ method, path, headers, body }) runs the same handlers without TCP.
Docs: API emulator. Example app: soundlink-api-emulator-example.
How we built it with AI (and what still needs a human)
The HTTP part of an emulator is small: a server, a router, an in-memory store. The work is in the business rules: how a create reserves the wallet, what a Meta reject does to the balance, how fee and spend combine into a refund. Coding agents helped a lot there. We described a rule, had the agent write the Vitest case first, then the handler, and ran the suite on every change.
What needed a human:
- Scope. The first version also mocked self-serve endpoints nobody needed yet. We cut it to the paid campaign lifecycle.
- PR size. The first PR was about 2,700 lines. We split it by concern (core lifecycle, plan presets and fees, docs) so reviewers could check the contract changes one at a time.
- Public repo hygiene. The SDK is public on npm and GitHub. Generated PR descriptions and docs tend to copy internal context out of the conversation. We added a rule to the repo’s agent instructions so that stays out of commits, docs, and PR text.
- Keeping up with production. This is the hard part long term. The emulator ships in the same npm package as the client, so when the API adds a field, the client type and the emulator response change in the same release.
What we optimize for:
- Configurable
planandfeeRate, so refund tests are intentional - Harness transitions for Meta-shaped events you can’t wait for in CI
- A separate import (
soundlink/api-emulator), so production clients don’t pull the test harness by accident
Mistakes that waste a week
- Mock without wallet state: status assertions pass; refund tests lie.
- Fee rate left at 0: every refund looks “correct” until the first plan with a fee. The emulator defaults to 0, so pass
planorfeeRate. - Reusing an Idempotency-Key after a
402: the Public API can replay a recorded402for the same key. After a top-up, retry with a new key. The emulator doesn’t store the402, so reusing the key passes locally and fails in production. - Pointing OAuth sign-in at the emulator: auth and the campaign lifecycle are different jobs. Keep them in different processes.
- Coding against emulator-only behavior: if a field or route isn’t in the Public API docs, don’t depend on it.
- Skipping a production smoke test after green local tests: local fidelity is not a go-live.
Shortcut: use the package we already ship
If you are integrating Soundlink today, you don’t need to build the four layers yourself.
- Import
createApiEmulatorfromsoundlink/api-emulator - Point
Soundlink(or your HTTP client) at the local base URL - Drive Meta-shaped edges with
transitionand failures withfailNext - Read the public guide and the example repo linked above
What’s next: local emulator today, hosted test mode later
Two models, both valid:
Today: local emulator. Runs on your machine or in CI. No Soundlink account needed for the loop, since the emulator doesn’t validate keys against Soundlink. State resets with the process. Best for automated tests and agent-driven iteration.
Later: hosted test mode (similar idea to Stripe sandboxes). Same Public API host. A test key or an org flag selects an isolated dataset: no Meta spend, a simulated wallet, objects that never touch live campaigns. Better when several people need a shared sandbox without installing Node, or when a demo has to outlive one process.
We are not shipping hosted test mode in this post. The local emulator unblocks the lifecycle now. If we add a hosted test mode, the integration code should still look the same: change the key or the base URL, keep the calls.
Until then: run create → refund locally, inject a reject, a creative disapproval, and a 500, then run one real campaign when the contract is stable.
Checklist (do this today)
- [ ] Install the latest
soundlink(the emulator needs 2.10.0 or later) - [ ]
createApiEmulator({ apiKey, initialWalletBalance, plan })andlisten() - [ ] Create with a real
Idempotency-Key - [ ]
activate→set_spend→stop, then assert walletreserved === 0 - [ ] Add one negative path:
reject_metaor insufficient credit - [ ] Arm one fault (
server_errorortimeout) and check your retries - [ ] Reset between tests so state doesn’t leak
- [ ] Run the same flow once against production when you are ready



