Scripting a Faithful Stateful API Environment From Scratch on Your Local Machine

Build a local simulator that tracks state, so multi-step API tests mean something.

· 8 min read
Cover illustration for “Scripting a Faithful Stateful API Environment From Scratch on Your Local Machine”
API Simulation and Mocking · November 10, 2026 · 8 min read · 1,811 words

Integration testing against stateful APIs needs a local simulator where each mutating call is a transition in shared server-side state. Reads, related-resource requests, and webhooks must resolve the IDs and states produced by earlier calls. Building that environment from scratch means implementing a resource store, valid transitions, seed data, isolation, and deterministic faults.

Why stateless mocks cannot represent multi-step API workflows

POST /customers returns a customer ID, but GET /customers/{id} returns 404 because the mock never stored the customer. The response promised a resource that does not exist. A stateless mock effectively acts as a lookup table, returning a configured response for a path regardless of earlier calls. Configuring the GET to return a customer can hide the failure, but it does not establish that creation worked.

That gap becomes consequential in a Stripe-style payment flow. Creating a payment intent requires the customer ID, confirming it requires the payment intent ID, and handling its webhook depends on the resulting state. Independent fixtures cannot enforce those relationships. A charge returned as captured before any capture call tests the fixture configuration. These tests can pass just before deployment even when the real API rejects a missing parent resource or an invalid transition.

What "stateful" means at the implementation level

A stateful simulator makes every mutating request change a shared resource store. A state transition is the permitted change from a resource’s current state to its next state. ID correlation links calls by looking up the identifiers they return in that store.

The relevant distinction is between a stub, a mock, and a fake. A stub returns canned responses, a mock also checks that the expected calls were made, and a fake is a simpler implementation that works. The in-memory environment built here is a fake. Its fidelity depends on stateful flows, correlated resources, coherent seed data, and fault behavior. Dynamic templating and record-and-replay capability are additional evaluation dimensions alongside shared state.

Most tests should still remain stateless. Reserve stateful tests for complex multi-step workflows, where order and accumulated changes determine correctness. Those tests need their own data contexts and must run one at a time when they share an instance.

Designing the in-memory resource store

Use a dictionary keyed by resource ID, with each entry holding the full resource representation. Create that dictionary once at module level so every handler references the same instance. A minimal implementation sketch has a module-level store = {}, a POST handler that inserts a resource, a GET handler that retrieves it, and a LIST handler that reads its values. The shared reference is the essential design choice. If each handler has its own private dictionary, the endpoints work with separate data even though they otherwise fit together.

Generate IDs when resources are created, using a consistent prefix-plus-random pattern such as cust_<uuid> or pi_<uuid>. PATCH and DELETE must operate on the same entries that POST created. LIST must build its response from what is in the store at the time instead of a fixed array, so a new resource appears when the collection is read again.

Related resources need an explicit connection in this structure. A child resource can hold its parent ID as a foreign key, while the parent may hold child IDs. A nested map is another supported design. With either approach, handlers must use the identifier from the caller to look up the related resource as well as echo it.

Implementing state transitions and enforcing valid sequences

Encode permitted changes as a map from each current state to its allowed next states. An action endpoint or PATCH handler checks that map before changing the stored resource and returns an error when the requested transition is invalid. Only an accepted transition changes the resource representation.

For the Stripe-style payment flow, model the progression through requires_payment_method, requires_confirmation, and then succeeded or failed. The confirmation handler must inspect the payment’s current state and return success only for a valid transition. Capture and refund behavior needs equivalent guards. A premature operation must produce an error such as 409 Conflict.

When creating a payment intent, resolve the supplied customer ID against the customer store and reject a nonexistent parent. After a valid capture, GET /charges/{id} must return the captured state, and a refund attempt must check for that state first. These checks make the simulator enforce both resource relationships and operation order.

Seeding realistic data before tests run

Without enough records, pagination never reaches page two, foreign-key filters have little to distinguish, and quota behavior may never be exercised. Starting empty is therefore not a neutral choice. It limits what passing tests can establish.

Load a JSON or YAML fixture into the store before the server accepts connections. The fixture should have customers, orders, and payment intents that belong to the same scenario. Every seeded order should point to a customer that exists. Include a mid-sized customer base and resources in pending, succeeded, and failed states so tests can exercise existing and terminal resources without constructing every history first.

Keep this seed layer separate from records created for mutation tests. Tests should add their own resources instead of modifying the baseline that reset will restore. Well-designed simulator vendors make cohesive pre-seeded scenarios a first-class feature, allowing every team to evaluate realistic relationships and collection behavior from startup using the supplied scenarios.

Resetting and isolating state between test runs

When tests share mutable state, earlier runs can affect them. Provide a reset endpoint such as POST /_control/reset that clears runtime state and reloads the seed fixture without restarting the server. Call it from beforeEach or equivalent test-fixture setup. Each test then begins from a known baseline.

Place reset, inspection, and fault scripting on a separate, unauthenticated loopback port, never on the API port under test. The approved Obtuse8053/Ilmar Issue #51 provides the GitHub emulator example of this production-grade control-API pattern. Its treatment of state inspection also makes internal state a first-class testing concern. A route such as GET /_control/state/{resource} lets a test check that DELETE removed a record as well as returning 204.

Tests sharing one simulator instance must run serially. Unique-prefixed IDs can prevent naming collisions between suites, but they do not remove the hazards of shared resets or interleaved mutations. For parallel CI jobs, give each job its own simulator instance. A cheap, self-contained startup makes replication preferable to coordinating shared state.

Correlating IDs across a multi-step workflow end to end

Begin the payment workflow after resetting to the seeded baseline. POST /customers creates a record, assigns cust_abc, and returns that identifier. The next call posts a payment intent with cust_abc as its customer reference. The simulator looks up that customer, validates its existence, stores the intent, and assigns pi_xyz. Neither identifier is merely decorative response data.

The application then calls POST /payment_intents/pi_xyz/confirm. The handler retrieves that intent and checks that its state permits confirmation before transitioning it to succeeded. A subsequent GET /payment_intents/pi_xyz returns the resulting state. That read is the decisive check. A stateless mock returns its configured fixture, whereas the simulator returns the resource reached through the preceding calls.

On the state transition, the simulator sends an event to the configured local endpoint, where the test can assert on its payload without an external tunnel or live API credentials. Stripe signature verification requires Stripe-Signature signed over the timestamp and raw body. Slack uses X-Slack-Request-Timestamp and X-Slack-Signature when a signing secret is configured, illustrating that local simulation must exercise verification.

Injecting faults to test resilience alongside the happy path

A successful workflow leaves error handling largely unexamined. Add configurable response delays, 429 responses with Retry-After, timeouts that outlast the client’s timeout, mid-response connection resets, and malformed bodies that fail schema validation. Each fault exercises a different response path. A rate-limit response, for example, tests retry and backoff behavior.

Commit the resource to the store, then drop the response so the client receives a network error. The client cannot infer whether creation happened. On retry, it must use idempotency keys or handle duplicate creation gracefully. Dropping the connection before committing the write does not test this ambiguity.

Script faults through the control API before running the workflow. A rule posted to /_control/faults can return 429 on the next two calls to POST /charges, then expire. The same issue specifies deterministic faults applied at chosen sequence points, making failures reproducible across CI runs. To test more cases, a --scenario auth_failure mode can return 401 from authentication endpoints and show where customer and payment-intent operations handle failures in different ways.

Running the simulator in CI without live credentials or rate limits

Start the simulator as a local process or container with its fixtures and control API available locally. It must make no external network calls. Vendor API keys, sandbox connections, and exposure to live rate limits would reintroduce the dependency the environment is meant to replace. Scripted 429 responses can still be used without using up a vendor’s quota.

The pipeline’s startup sequence is straightforward and ordered. Launch the simulator, wait until its health endpoint returns 200, run the test suite, and use the suite’s exit code to determine the job outcome. Teardown occurs when the CI job ends.

Air-gapped enterprise environments make offline operation a requirement. Package everything needed for the run, including seed fixtures and support for loopback HTTPS. The openssl CLI can generate a throwaway certificate authority and a 127.0.0.1 or localhost certificate for each test session. Use that session-specific authority for certificate validation with TLS checks enabled. Plain HTTP would skip the application’s TLS verification path, leaving the test environment different from the production transport in a consequential way.

Keeping the simulator faithful as the real API evolves

Real APIs change response shapes, introduce required fields, deprecate enum values, and revise transition rules. Tests will continue passing if both the simulator and its expectations preserve the old behavior. Passing results alone cannot reveal that drift.

Compare versions of the OpenAPI specification in CI before deployment to catch changes to the contract that have been documented. That approach depends on the specification remaining current. Live probing addresses a different gap by running parameterised calls against both the simulator and the real API, comparing responses, and reporting divergence. For a homegrown environment, shared contract tests that also run against the real API are the minimum viable detector. A contract that passes locally but fails against the live service exposes a discrepancy requiring investigation.

Keep that live verification separate from offline application-test execution. The CI suite can remain self-contained while the simulator’s maintenance process checks fidelity on a schedule and before every release. For an off-the-shelf simulator, fidelity scores that are published and kept up to date should show what the probes cover and how closely the simulator matches live behavior. Those scores provide evidence within the scope of the probes’ coverage. Trust rests on demonstrated agreement about the states, relationships, and failure modes that the integration actually exercises.

More in API Simulation and Mocking