What is API Mocking? Tools, Use Cases, Examples

API mocking replaces a real API with a fake that returns set responses. Learn when to mock, which tools to use, and how to stop mocks drifting.

What is API mocking?

API mocking means standing in for a real API with a fake one that returns pre-defined responses. The client calls the same URLs and gets the same response format, but nothing reaches the real backend: no database, no side effects, no third-party bill. Because you control the answers, tests become deterministic and you can trigger cases that are hard to produce on demand, such as a 500 error or a slow response.

Teams use mocks for three things: building a frontend before the backend exists, keeping automated tests independent of services that may be down, and checking that a client handles the documented responses. A mock is a tool for development and testing, not a substitute for testing the real API. See API testing for the bigger picture.

How API mocking works

A mock server (or an interceptor inside your test process) listens for a request, matches it on method, path, headers or body, and replies with a canned or computed response. You point the client at the mock by changing the base URL, usually through an environment variable, or the interceptor catches outgoing calls so no code change is needed.

// Dev: API_BASE=http://localhost:8000 (mock)
// Prod: API_BASE=https://api.example.com (real)
const API_BASE = process.env.API_BASE || 'https://api.example.com';
fetch(`${API_BASE}/users/42`);

When to use API mocking

  • Frontend work before the backend is ready. Build against the agreed JSON shape, then swap the base URL.
  • Unit and integration tests. No network, no flaky third party.
  • Error paths. Return 429, 500 or a timeout whenever you need one.
  • Metered or rate-limited APIs. Avoid paying for, or being throttled on, every test run.
  • Demos and offline work. No production data, no connection needed.

Types of API mocks

  • Static: the same response every time.
  • Dynamic: the response depends on the path, query string or body.
  • Recorded: real responses captured once and replayed later.
  • Spec-driven: generated from an OpenAPI file, so the mock follows the documented schema (see Swagger).
  • Stateful: a POST creates something that a later GET returns. Useful for end-to-end flows, but costly to maintain.

Common API mocking tools

ToolBest for
WireMockScriptable HTTP mocking on the JVM, common in CI
MockoonLocal mock servers with a desktop app
MSW (Mock Service Worker)Intercepting requests in browser and Node tests; also handles GraphQL
PrismMock server generated from an OpenAPI description
nockPer-test HTTP interception in Node.js
json-serverA quick REST API from a JSON file
Postman mock serversMocks built from saved example responses in a collection

Example with MSW (v2 syntax):

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

const server = setupServer(
  http.get('https://api.example.com/users/:id', ({ params }) => {
    return HttpResponse.json({ id: params.id, name: 'Alice' });
  })
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

Example with nock:

const nock = require('nock');
nock('https://api.example.com')
  .get('/users/42')
  .reply(200, { id: 42, name: 'Alice' });

Mock, stub, fake and spy

  • Stub: returns a canned answer.
  • Mock: a stub that also checks it was called the way you expected.
  • Fake: a working but simplified implementation, such as an in-memory database.
  • Spy: wraps the real call and records what was sent.

In everyday talk, "mocking" covers all four. The strict meanings only matter in unit-testing frameworks.

Common mistakes

  • The mock drifts from the real API. The provider changes a field, your mock does not, tests stay green and production breaks. Generate mocks from the spec, or use contract testing, which checks both sides against the same contract.
  • Only testing against mocks. Keep some integration tests against a staging or real API.
  • Mocks that are too forgiving. The real API validates input and rejects what the mock accepts.
  • Only the happy path. Add errors, empty results, slow responses and malformed bodies. More in common mocking mistakes in API testing.
  • A mock that grows into a second backend. When it needs its own business logic, use a test environment instead.

Mocks, load testing and monitoring

A load test against a mock measures the mock, not your service, so do not use one to prove your API can take traffic. Mocks do help inside a load test when a slow or rate-limited third party sits behind your service: stub that dependency so the result shows your own code. Run the actual capacity test against the real API in a staging environment with LoadFocus load testing, which runs JMeter and k6 scripts.

Mocks cannot tell you when the real API changes after you ship. Scheduled checks against the live endpoint do that: LoadFocus API monitoring calls your endpoints on a schedule (every 5 minutes on the free plan), checks status code, response time and body, and alerts you when something fails. Related: API monitoring, API endpoint, regression testing.

FAQ: API mocking

What is the difference between mocking and using a staging API?

A mock is local, fast and fully under your control. A staging API is a real deployment of the service without production data. Use mocks for unit tests and development, and staging for integration and end-to-end tests.

Should I mock every external API in tests?

In unit tests, yes, so your code is tested in isolation. In integration tests, keep at least some calls against a real or staging service to catch problems a mock cannot show.

How do I mock dynamic responses?

Most tools can compute a response from the request: WireMock has response templating, Mockoon supports dynamic data, and MSW handlers are plain JavaScript functions.

Can I mock GraphQL or gRPC?

GraphQL, yes: MSW supports it. For gRPC you need a gRPC-specific mock tool, since plain HTTP mocks do not speak the protocol.

How do I keep a mock in sync with the real API?

Generate it from the OpenAPI spec where you can, and add contract tests or a scheduled check against the real endpoint so a change on the provider side fails a test instead of production.

How fast is your website?

Elevate its speed and SEO seamlessly with our Free Speed Test.

Free Website Speed Test

Analyze your website's load speed and improve its performance with our free page speed checker.