Test Data & API Mocking

What is API Mocking? How & When to Mock APIs

Smeet GohelUpdated 18 min read
Quick answer

API mocking replaces a real API with a stand-in that returns realistic responses from the same endpoints, so you can build and test before the real API exists, without a flaky third party, or with failures you choose. Generate the mock from the OpenAPI spec, make it dynamic, and keep contract tests on the real API.

Reviewed by Rishi Gaurav

Share:
A mock server generated from the OpenAPI spec answering a frontend app, consumer tests and CI in place of the real API, with contract tests running on the real API and three kinds of mock: static, dynamic and stateful

Part of the Test Data & API Mocking hub. Start with the pillar guide: Test data management best practices.

API mocking is replacing a real API with a stand-in — a mock API — that answers the same endpoints with realistic responses. Point a client or a test at the mock's URL instead of the real one and it behaves, for the purposes of building and testing, like the real thing. It is one of the core techniques in our test data management and mocking guide, and it removes the most expensive word in API work: blocked.

A frontend team waits for an endpoint backend has not finished. An integration team is rate-limited out of a third-party sandbox. QA cannot test error handling because the real service never returns a 503 on demand. A mock fixes all three: it follows the spec, it is always available, and it fails exactly when you tell it to.

This guide covers what API mocking is, when to use it and when not to, how to mock an API in five common tools, how to mock errors, delays and pagination, how mocking fits into API testing, and the contract testing that stops mocks from quietly lying.

In this guide

  1. What is API mocking?
  2. When to mock an API (and when not to)
  3. Static, dynamic and stateful mocks
  4. How to mock an API: five examples
  5. Mocking in API testing
  6. Mocking for parallel development
  7. Keeping the mock honest: mocking vs contract testing
  8. API mocking tools compared
  9. Frequently asked questions about API mocking

What is API mocking?

A mock API returns realistic responses without the real backend, database or third-party dependency behind it. The best mocks are generated from the API specification, so response shapes, status codes and field types match the contract by construction rather than by someone's memory of it.

An API mocking example. The orders service is not built yet, but its OpenAPI spec says GET /v1/orders/{id} returns an order. A mock generated from that spec answers immediately:

curl -s http://localhost:4010/v1/orders/42
# {"id":"42","sku":"A-1","qty":2,"status":"pending"}

The frontend renders it, the consumer's tests assert on it, and nobody waits for the provider.

Mock, stub, fake or service virtualization?

TermWhat it isTypical scope
StubCanned answer to one specific callInside a unit test
Mock (in unit-testing terms)A test double that also verifies how it was calledInside a unit test
Mock API / mock serverA stand-in for a whole HTTP service, often with request-dependent responsesAcross tests, teams and CI
FakeA lightweight working implementation (an in-memory database)Integration tests
Service virtualizationMock APIs at enterprise scale, often recorded from real trafficMany teams and environments

In API work, "API mocking" almost always means the third row: a mock server you can call over HTTP.


When to mock an API (and when not to)

Mock when:

  • The API does not exist yet. As soon as the spec is agreed, consumers build against a mock — including loading, empty and error states.
  • A third party is slow, rate-limited or paid per call. A local mock of the payment or shipping API is always up and never throttles.
  • You need failures on demand. A real gateway will not return a 402 or time out when asked; a mock will, so negative-path testing stops depending on luck.
  • You want fast, deterministic tests. Mocking downstream services in CI isolates the service under test, so a failure points at your code.

Do not rely on a mock when:

  • You need to prove two real systems integrate — that is a job for contract testing or a run against the real provider.
  • The behaviour under test lives in the dependency itself (its performance, its data).
  • The mock has no owner and no spec behind it — then it encodes one team's assumption, and the assumption is the real deliverable.
ApproachConsumer unblockedCatches provider driftSetup costBest when
Spec-derived mockImmediatelyNoMinutesThe provider does not exist yet
Hand-written stubImmediatelyNoLow, then ongoingOne exact edge case a test needs
Recorded traffic replayAfter the provider existsPartlyMediumThe provider exists but is slow or rate-limited
Shared staging environmentWhen staging is upYesHigh, and sharedLate integration verification
Contract testingImmediatelyYesMediumSeveral teams, independent releases

Static, dynamic and stateful mocks

  • A static mock always returns the same canned response. Fine for a quick UI stub; useless for branching logic.
  • A dynamic mock varies the response by request: different inputs give different outputs, invalid requests get validation errors, and chosen conditions produce chosen status codes. This is what makes a mock server a development and testing tool rather than a fixture.
  • A stateful mock remembers earlier calls, so a POST followed by a GET returns what was created. You need it for multi-step flows; WireMock scenarios and MockServer support it.

Two more properties matter in practice: latency (a mock that can delay its answer lets you test timeouts and loading states) and templating (echoing request values or generating IDs and timestamps so responses look real).


How to mock an API: five examples

1. From an OpenAPI spec with Prism

The fastest route when a spec exists — every operation is served with schema-valid responses:

npx @stoplight/prism-cli mock openapi.yaml --port 4010 --dynamic

To get a specific response, send a Prefer header. The status must be one the spec declares for that operation:

curl -i -H "Prefer: code=503" http://localhost:4010/v1/orders/42

2. Hand-written stubs with WireMock (errors and delays)

When a test needs one exact behaviour — a 503 after a two-second delay — a WireMock stub expresses it directly:

{
  "request": { "method": "POST", "urlPath": "/v1/charges" },
  "response": {
    "status": 503,
    "fixedDelayMilliseconds": 2000,
    "headers": { "Content-Type": "application/json", "Retry-After": "5" },
    "jsonBody": { "error": "gateway_unavailable" }
  }
}

3. A Postman mock server

Create a mock server from a collection; each saved example becomes a response. Request body and headers are ignored during matching unless you turn them on under Response Matching. The x-mock-response-code request header picks the example with a given status and x-mock-response-name picks one by name, so the same endpoint can return a 200 or a 404 on demand. You can also set a fixed network delay when you create the server. Good for sharing during API design; less suited to CI.

4. Mocking in the browser with Playwright

For frontend tests, Playwright intercepts the request inside the browser — no mock server at all:

Generate test data variants from your spec (free)

Free, runs in your browser, no sign-up needed.

await page.route('**/api/orders/42', (route) =>
  route.fulfill({
    status: 200,
    contentType: 'application/json',
    body: JSON.stringify({ id: '42', status: 'pending' }),
  })
);

5. In Node tests and React apps with Mock Service Worker

Mock Service Worker (MSW) intercepts requests in Node or the browser, so the same handlers can serve unit tests, Jest or Vitest suites, and a React app during development:

import { http, HttpResponse } from 'msw/http';
import { setupServer } from 'msw/node';

const server = setupServer(
  http.get('https://api.example.com/v1/orders/:id', ({ params }) =>
    HttpResponse.json({ id: params.id, status: 'pending' })
  )
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

Mock an error, a delay or a paginated list

Happy-path mocks are the easy part. These are the cases teams most often need to force:

What you needHow to produce it
A declared error statusPrism with Prefer: code=503, or Postman with x-mock-response-code: 503
A slow responsefixedDelayMilliseconds on a WireMock stub, or a fixed delay on a Postman mock server
A dropped connection"fault": "CONNECTION_RESET_BY_PEER" in a WireMock response, or route.abort('connectionreset') in Playwright
A different response per query parameterqueryParameters matching in a WireMock stub

Pagination is the query-parameter case. This WireMock stub returns the last page of a list, so a client has to stop when next is null:

{
  "request": {
    "method": "GET",
    "urlPath": "/v1/orders",
    "queryParameters": { "page": { "equalTo": "2" } }
  },
  "response": {
    "status": 200,
    "headers": { "Content-Type": "application/json" },
    "jsonBody": {
      "items": [{ "id": "43", "status": "pending" }],
      "page": 2,
      "next": null
    }
  }
}

Add one stub per page you care about: a first page with a next value, a last page, and an empty list. Those three catch most client pagination bugs without a stateful mock.

A hosted mock per project

In Shift-Left API, the mock server generates mocks on demand from the endpoints you imported — up to 500 in one go — using the spec's documented examples or schema-based placeholders, never AI-invented bodies. Each project gets its own mock host; responses can depend on query, header or body conditions (ten operators), echo request values or generate UUIDs and timestamps, carry a per-response delay in milliseconds, or return any 4xx/5xx status. It covers REST, SOAP and GraphQL, and the free plan includes 50 mocks. Responses allow cross-origin calls, so a browser frontend can use the mock URL directly. It does not record or proxy real traffic. A caller can pick any named response with an X-Mock-Scenario header (generated mocks include one per documented error), a response can time out or drop the connection on purpose, and a mock can remember records for a limited time. Mocks of an API whose spec changed are flagged as possibly out of date, and a contract check reports whether each stored response fits the documented schema; contract-checked API mocks walks through that workflow.

For a full comparison — Prism, WireMock, Microcks, MockServer, Mockoon, Hoverfly and more — see the best API mocking tools.


Mocking in API testing

Inside a test suite, mocks do three jobs.

Isolation. When the service under test calls three others, mocking those three means a failure is unambiguously in your code, not a flaky dependency. That is the backbone of service dependency testing.

Error and edge paths. Give each mocked dependency the responses your service must survive — 500, 503 with Retry-After, a 2-second delay, an empty list, a malformed body — and assert how your API reacts. Pair the mock with deliberate data from API test data generation so it exercises real branches, not one happy row.

Mock API for integration testing in CI. Start the mock inside the job, so the suite never depends on the provider being deployed. Use a step rather than a services: container here: service containers start before actions/checkout runs, so the spec is not on disk yet. Prism also has to listen on 0.0.0.0 to be reachable from outside its container:

# .github/workflows/consumer-tests.yml
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Start the mock from the spec
        run: |
          docker run -d --name orders-mock -p 4010:4010 -v "$PWD:/specs:ro" \
            stoplight/prism:5 mock -h 0.0.0.0 /specs/openapi.yaml
          timeout 30 sh -c 'until curl -s -o /dev/null http://localhost:4010/v1/orders/42; do sleep 1; done'
      - run: npm ci && npm test
        env:
          ORDERS_API_URL: http://localhost:4010

The wait loop matters: without it, the first tests can run before the mock is listening and fail for a reason unrelated to your code.

When mocked calls need to be strung into a flow — create, read back, update, handle the error branch — chain them with multi-step integration workflows whose environment's base URL points at the mock, then repoint the same workflow at the real service once it ships.


Mocking for parallel development

Mocking is the technical half of parallel development. The half that decides whether it works is an agreement between teams, made before either starts.

Agree the contract first, in writing. The spec is the interface. Both teams review it and it lands in version control before either writes code. A mock generated from a spec one team wrote alone is a guess with a server in front of it.

Name an owner for changes. Specs change during implementation. Someone has to own merging those changes and telling the other side, or the consumer keeps building against last week's mock.

Decide what a breaking change means. Adding an optional field is safe. Removing or renaming a field, or making an optional field required, is not. Write down which category needs a conversation.

Integrate early. Two teams working against a mock for six weeks and integrating at the end is the riskiest arrangement. A short integration against a half-built provider surfaces mismatches while they are cheap.

Signs the mock has drifted

  • The provider has shipped changes but the spec has not moved.
  • Consumer tests pass but the integration environment fails.
  • The mock returns fields the provider does not (often an aspirational spec).
  • Nobody has run the consumer against the real provider this sprint.
Free 1-page checklist

API Testing Checklist for CI/CD Pipelines

A printable 25-point checklist covering authentication, error scenarios, contract validation, performance thresholds, and more.

We email you the download link. No spam, unsubscribe any time.

Common mistakes

  • Mocking the happy path only — the first time the consumer sees a timeout should not be production.
  • Hand-writing a mock when a spec exists — a second artifact that drifts from both the spec and the code.
  • Never removing the mock — once the provider is ready, test against it.
  • Treating a mock-based suite as integration coverage — it proves the consumer works against its own assumptions, nothing more.

Keeping the mock honest: mocking vs contract testing

A mock proves your code works against your assumptions about the API. It does not prove the real API matches them. If the backend renames a field, the mock still returns the old name and the frontend still passes — until production.

Mocking unblocks; contract testing verifies. Contract tests check the real API against the same specification the mock was generated from. Three practices keep the pair honest:

Generate, do not write. A spec-derived mock cannot describe an operation the spec does not contain.

Fail the consumer's build when the spec moves. Pin the spec version the mock is generated from and treat a change as a reviewable event:

- name: Fetch the provider spec at the pinned version
  run: |
    curl -sf "$SPEC_REGISTRY/orders/${PINNED_SPEC_VERSION}/openapi.yaml" -o openapi.yaml
    sha256sum -c openapi.sha256 || {
      echo "::error::provider spec changed - review before bumping PINNED_SPEC_VERSION"
      exit 1
    }

Verify against the real provider on a schedule. Run the same consumer suite nightly against staging instead of the mock. Look at green runs as well as red ones: Shift-Left API's run analysis also examines passing runs and flags contract drift and assertions that check nothing, which is exactly the "mock returns fields the provider does not" problem.

Start with a spec-derived mock to unblock the work this week, and add contract verification when the number of consumers makes drift a matter of when rather than if.


API mocking tools compared

ToolMock sourceDynamic responsesStatefulSelf-hostedBest for
PrismOpenAPI documentYes (schema-derived)NoYesUnblocking consumers from a spec on day one
WireMockHand-written stub filesVia templatingYes (scenarios)YesOne exact edge case; errors and delays
MicrocksOpenAPI, AsyncAPI, Postman collectionsYesPartialYesMulti-protocol estates; mocks plus contract checks
MockServerJava/JS expectation APIYesYesYesMocks driven from inside test code
Postman mock serverSaved collection examplesExample-basedNoNoQuick sharing during design
Playwright page.routeTest codeYesIn codeYes (in test)Frontend tests without a mock server
Mock Service WorkerHandler codeYesIn codeYes (in test or browser)Sharing one set of handlers across Node tests and a frontend
MountebankProtocol-level impostersYesYesYesNon-HTTP protocols in one harness
Shift-Left API mock serverImported OpenAPI, WSDL or GraphQLYes (conditions, templates, delays, named scenarios)Yes (records kept for a limited time)Hosted, or your own installPer-project REST, SOAP and GraphQL mocks next to the tests

Spec-derived mocks cannot drift from the contract, because there is no second definition to drift from. Hand-written stubs can express things a spec cannot — which is exactly why they drift.


Frequently asked questions about API mocking

What is API mocking?

API mocking is replacing a real API with a stand-in that answers the same endpoints with realistic responses. Clients and tests point at the mock's URL instead of the real one, so work can continue before the API exists, without depending on an unreliable third party, and with errors or delays produced on demand.

What is mocking in API testing?

In API testing, mocking means replacing the services an API under test depends on with mocks whose responses you control. The test then exercises only your API, failures point at your code rather than a flaky dependency, and you can trigger error paths such as a 503 or a slow response whenever you need them.

Is API mocking the same as stubbing?

Closely related. A stub returns a canned value for one specific call, usually inside test code. A mock API stands in for a whole service over HTTP and can vary its response by request. In everyday use the terms overlap; the useful distinction is static versus dynamic behaviour.

When should you mock an API?

Mock when the real API does not exist yet, when a third-party sandbox is slow, rate-limited or costs money, when you need failure responses on demand, and when you want fast, deterministic tests in CI. Do not rely on mocks to prove integration; that needs contract tests or runs against the real API.

Should mocks be generated from the spec or written by hand?

Generate them from the OpenAPI spec whenever one exists, so response shapes, status codes and field types match the contract. Hand-write a stub only for one exact edge case a specific test needs, because hand-written mocks start drifting from the real API immediately.

Can I use mock APIs in CI?

Yes. Starting a mock of each downstream dependency inside the CI job makes tests fast and deterministic. Add a separate contract-testing stage, or a scheduled run against the real provider, so mocked assumptions cannot drift unnoticed.

How do I mock a slow or failing API response?

Declare the failure and force it, or write a stub for it. Prism returns a status the spec declares when you send a Prefer header such as code=503. WireMock adds fixed delays and connection faults, Postman can apply a fixed delay to a whole mock server, and Playwright can abort a browser request outright.

What free tools can I use to mock an API?

Prism, WireMock and Microcks are open source under Apache-2.0, and Mockoon, Mock Service Worker and Mountebank under MIT. Choose Prism when you have an OpenAPI spec, WireMock for exact stubs, Mock Service Worker for frontend and Node tests, and Mockoon if you prefer a desktop app.

Want spec-generated mocks next to your API tests? Start a free trial: import your OpenAPI spec, generate a mock per endpoint, and point your tests or frontend at the project's mock URL.

Sources and further reading

Key takeaways

  • API mocking replaces a real API with a stand-in that answers the same endpoints — so teams can build and test before, without or around the real thing.
  • Mock when the API does not exist, when a third party is unreliable, when you need failures on demand and when you want deterministic CI; do not mistake a passing mock-based suite for integration proof.
  • Prefer dynamic, spec-derived mocks; hand-write stubs only for the one edge case a test needs.
  • A mock says what the consumer expects; contract testing proves the provider still delivers it. Use both.
  • Start the mock inside the CI job and run the same suite against the real provider on a schedule.
Continue learning

Go deeper in the Learning Center

Hands-on lessons with runnable code against our live sandbox.

Ready to shift left with your API testing?

Import your OpenAPI spec and get a runnable test suite, in our cloud or on your own infrastructure.