Built byPhoenix

© 2026 Phoenix

Blog

October 14, 2026·7 min read

A Sandbox Partners Can Use Without You

If every new client needs a call with you before their first request works, you don't have a platform yet. Test keys that carry their mode, the real pipeline with simulated providers, magic values for every outcome, and signed webhooks partners can replay.

  • APIs
  • Developer Experience
  • Webhooks
  • Python
  • FastAPI

If every new client needs a call with you before their first API request works, you don't have a platform yet. You have a consultancy with an API attached.

The sandbox is the product for the first two weeks of every client relationship. It's where a partner's engineer decides whether your API is pleasant or painful, usually before anyone on your side knows they're trying. I've spent a lot of time on the other side of this, integrating payment, banking and identity providers. The good sandboxes felt like the real thing with the danger removed. The bad ones meant a support ticket for every edge case.

This is what I build now, with the code in Python and FastAPI.

What "good" means

A partner should be able to do all of this without talking to you:

  1. Get a test key and make a successful call within an hour.
  2. Trigger every outcome they need to handle: success, decline, review, timeout.
  3. Receive, verify and replay webhooks.
  4. Switch to production by changing one key, and nothing else.

Each of those is a design decision, not a docs page.

Keys that carry their mode

The mode lives in the key: sk_test_... or sk_live_..., the scheme Stripe and Paystack made familiar. Not a header, not a query parameter, not a flag on the account. If the mode is in the key, a test key can't reach live data, whatever the request says.

Store a hash of the key, never the key itself, and show it to the partner once.

python
import hashlibfrom dataclasses import dataclassfrom typing import Literal
from fastapi import Depends, Header, HTTPException
Mode = Literal["test", "live"]

@dataclass(frozen=True)class Principal:    client_id: str    mode: Mode

async def authenticate(authorization: str = Header()) -> Principal:    scheme, _, key = authorization.partition(" ")    if scheme.lower() != "bearer" or not key.startswith(("sk_test_", "sk_live_")):        raise HTTPException(401, "Send Authorization: Bearer sk_test_... or sk_live_...")    mode: Mode = "test" if key.startswith("sk_test_") else "live"    key_hash = hashlib.sha256(key.encode()).hexdigest()    row = await db.fetchrow(  # an asyncpg pool        "SELECT client_id, mode FROM api_keys"        " WHERE key_hash = $1 AND revoked_at IS NULL",        key_hash,    )    if row is None or row["mode"] != mode:        raise HTTPException(401, "Unknown or revoked key")    return Principal(client_id=row["client_id"], mode=mode)

The error message tells the partner exactly what to send. That one sentence saves a support ticket per new client.

One code path, two sets of providers

The tempting way to build a sandbox is a second copy of the API that returns canned JSON. Don't. Canned responses drift from production within weeks, and partners end up integrating against something that isn't your product.

Instead, run the real code and swap only what touches the outside world. I build backends so they boot with no third-party credentials at all: every external dependency (the bank rail, the identity provider, SMS, push) sits behind an interface, and each interface has a simulated implementation next to the real one. A sandbox is the same idea, chosen per request by the key's mode rather than per environment.

python
from decimal import Decimalfrom typing import Protocol

class PayoutRail(Protocol):    async def send(self, account: str, amount: Decimal, reference: str) -> str: ...

class BankRail:  # live: calls the bank's API    ...

class SimulatedRail:  # test: decides the outcome from the amount    async def send(self, account: str, amount: Decimal, reference: str) -> str:        return OUTCOMES.get(amount % 1, "succeeded")

def rail_for(principal: Principal) -> PayoutRail:    return SimulatedRail() if principal.mode == "test" else BankRail()

Everything else, the validation, the rules, the database writes and the webhooks, is the code your live clients run.

Outcomes on demand

Partners need to test the unhappy paths, and they can't wait for a real decline to happen. Give them magic values: inputs that always produce a given outcome. Card networks publish test card numbers, and identity providers publish test IDs that always pass or always fail. Do the same, and document them in one table:

python
# The kobo of the amount picks the outcome; anything else succeeds.OUTCOMES = {    Decimal("0.01"): "declined",    Decimal("0.13"): "flagged_for_review",    Decimal("0.42"): "timeout",  # we answer after 30s, so clients can test their timeout}

Make them deterministic. The same input gives the same outcome every time, so partners can put them in their own test suites, which is where you want your API to live.

Simulate the event, run the real pipeline

For anything that normally starts outside your system, like an incoming transaction, give the sandbox an endpoint that creates one:

python
@app.post("/v1/sandbox/transactions", status_code=201)async def simulate_transaction(    body: SimulatedTransaction,    principal: Principal = Depends(authenticate),):    if principal.mode != "test":        raise HTTPException(403, "Simulations need a test key")    tx = await create_transaction(principal, body)  # the live code path    await pipeline.process(tx)  # rules, scoring, webhooks: all real    return tx

Two rules keep test and live data apart:

  • Every row carries the mode. Every query filters on (client_id, mode), through one repository layer so nobody forgets, with an index that starts with those two columns.
  • A reset button. POST /v1/sandbox/reset wipes a client's test data. Partners run their test suites more than you'd think, and a sandbox full of yesterday's junk makes their tests flaky.

Webhooks partners can trust and replay

Webhooks are where most integrations actually break, so make them observable.

Sign every delivery. HMAC-SHA256 over the timestamp and the body, with a secret per client and per mode:

python
import hashlibimport hmacimport time

def sign(secret: bytes, body: bytes, timestamp: int | None = None) -> str:    timestamp = timestamp or int(time.time())    mac = hmac.new(secret, f"{timestamp}.".encode() + body, hashlib.sha256)    return f"t={timestamp},v1={mac.hexdigest()}"

def verify(secret: bytes, body: bytes, header: str, tolerance_s: int = 300) -> bool:    parts = dict(item.split("=", 1) for item in header.split(","))    timestamp = int(parts["t"])    if abs(time.time() - timestamp) > tolerance_s:        return False  # too old: a replayed request, not a retry    expected = sign(secret, body, timestamp).split("v1=", 1)[1]    return hmac.compare_digest(expected, parts["v1"])

Publish verify in your docs, in the languages your clients use. Most webhook bugs I've seen on the receiving end are signature checks run against a re-serialised body instead of the raw bytes. Say that in bold in the docs.

Log every attempt, with the status code and response time, and show the log to the partner. "We sent it at 14:02:11, your server returned 500" ends a support thread in one message.

Let them replay. POST /v1/webhooks/deliveries/{id}/replay sends the same event again, with the same event ID. That's the detail that matters. A well-built receiver records each event ID it has processed and ignores duplicates. That's what I do on the receiving end of bank and payment webhooks, and replays with stable IDs are how a partner proves their own deduplication works before production does it for them.

Docs that get the first call working

  • Generate the OpenAPI spec from the code that validates requests. In FastAPI that's free: the Pydantic models are the schema. Hand-written specs go stale.
  • Ship a Postman collection with a sandbox environment prefilled, and update it in the same pull request as the endpoint it describes. Docs that lag the API by a sprint are worse than no docs.
  • Generate example responses by running the real code, not by typing them. Hand-written examples drift, and the drift is always in the field a partner depends on.
  • A quickstart with exactly three steps: get a test key, make one call, receive one webhook. If your quickstart needs a fourth step, that step is a product bug.

The checklist

  • The key decides the mode, and the mode is on every row.
  • The real code path, with only the outside world simulated.
  • Magic values for every outcome, deterministic and documented.
  • A simulate endpoint for events that start outside your system, and a reset button.
  • Signed webhooks, a delivery log partners can see, and replays that keep the event ID.
  • An OpenAPI spec and examples generated from code, and a three-step quickstart.

Get those right and most of your integration support becomes a link to the docs. That's the goal: a partner who goes live without needing you, and tells the next partner how easy it was.

Read next

  • The Fix That Didn't Remove the MalwareA cleanup commit for a supply-chain dropper was reviewed and merged, and the malware was still there. How it hid behind hundreds of tabs, why the diff lied, and the required check that now catches it by shape.Sep 14, 2026·6 min read
  • Building Payweave: One SDK for Every Payment ProviderAdd a second payment provider and you learn how much of your 'integration' was secretly just Stripe: different money units, different webhook signatures, different error shapes. Payweave is a TypeScript SDK that unifies Stripe, Paystack, and Flutterwave behind one client without hiding the parts where they genuinely differ.Jul 25, 2026·18 min read
All postsShare on X ↗
import hashlibfrom dataclasses import dataclassfrom typing import Literal
from fastapi import Depends, Header, HTTPException
Mode = Literal["test", "live"]

@dataclass(frozen=True)class Principal:    client_id: str    mode: Mode

async def authenticate(authorization: str = Header()) -> Principal:    scheme, _, key = authorization.partition(" ")    if scheme.lower() != "bearer" or not key.startswith(("sk_test_", "sk_live_")):        raise HTTPException(401, "Send Authorization: Bearer sk_test_... or sk_live_...")    mode: Mode = "test" if key.startswith("sk_test_") else "live"    key_hash = hashlib.sha256(key.encode()).hexdigest()    row = await db.fetchrow(  # an asyncpg pool        "SELECT client_id, mode FROM api_keys"        " WHERE key_hash = $1 AND revoked_at IS NULL",        key_hash,    )    if row is None or row["mode"] != mode:        raise HTTPException(401, "Unknown or revoked key")    return Principal(client_id=row["client_id"], mode=mode)
from decimal import Decimalfrom typing import Protocol

class PayoutRail(Protocol):    async def send(self, account: str, amount: Decimal, reference: str) -> str: ...

class BankRail:  # live: calls the bank's API    ...

class SimulatedRail:  # test: decides the outcome from the amount    async def send(self, account: str, amount: Decimal, reference: str) -> str:        return OUTCOMES.get(amount % 1, "succeeded")

def rail_for(principal: Principal) -> PayoutRail:    return SimulatedRail() if principal.mode == "test" else BankRail()
# The kobo of the amount picks the outcome; anything else succeeds.OUTCOMES = {    Decimal("0.01"): "declined",    Decimal("0.13"): "flagged_for_review",    Decimal("0.42"): "timeout",  # we answer after 30s, so clients can test their timeout}
@app.post("/v1/sandbox/transactions", status_code=201)async def simulate_transaction(    body: SimulatedTransaction,    principal: Principal = Depends(authenticate),):    if principal.mode != "test":        raise HTTPException(403, "Simulations need a test key")    tx = await create_transaction(principal, body)  # the live code path    await pipeline.process(tx)  # rules, scoring, webhooks: all real    return tx
import hashlibimport hmacimport time

def sign(secret: bytes, body: bytes, timestamp: int | None = None) -> str:    timestamp = timestamp or int(time.time())    mac = hmac.new(secret, f"{timestamp}.".encode() + body, hashlib.sha256)    return f"t={timestamp},v1={mac.hexdigest()}"

def verify(secret: bytes, body: bytes, header: str, tolerance_s: int = 300) -> bool:    parts = dict(item.split("=", 1) for item in header.split(","))    timestamp = int(parts["t"])    if abs(time.time() - timestamp) > tolerance_s:        return False  # too old: a replayed request, not a retry    expected = sign(secret, body, timestamp).split("v1=", 1)[1]    return hmac.compare_digest(expected, parts["v1"])