API mocking

Also known as: mock API

On this page 7

API mocking is the practice of replacing a real application programming interface with a simulated service that returns predefined or generated responses, so that client code can be built and tested without calling the live system. In the field of APIs within programming, a mock API stands in for a dependency that is unfinished, unstable, expensive or unsafe to call.

The technique decouples teams and test suites from external availability. A frontend can be built against a mock while the backend is still in design, and a test suite can reproduce rare errors on demand, such as a timeout or a malformed payload, that the real service would produce only occasionally.

How API mocking intercepts requests

Every mock works by intercepting a request before it reaches the real service and answering it with a controlled response. The interception point determines how realistic the simulation is and how much of the client stack is exercised.

The most common interception layers are listed below, from the closest to the application code to the closest to the network.

Interception layerMechanismWhat is still exercised
In-process function stubReplace the client method in the testBusiness logic only
HTTP client interceptorHook into the HTTP librarySerialization and request building
Service worker in the browserCapture fetch calls at the network boundaryFull frontend request flow
Standalone mock serverRun a separate process on a local portReal network stack and configuration
Proxy with record and replayCapture real traffic, replay it laterRealistic payloads and headers
Where a mock can intercept API calls

A response definition usually matches on method, path, query parameters, headers or body, and returns a status code, headers and a body. Advanced tools add stateful behavior, so that a POST followed by a GET returns the created resource, as well as configurable latency and fault injection.

Mocks, stubs, fakes and virtualized services

The term mocking is often used loosely, but testing literature distinguishes several kinds of test doubles. The differences matter because they decide whether a test checks outcomes or checks interactions.

TypeBehaviorTypical purpose
StubReturns fixed canned answersFeed known data into the code under test
MockRecords calls and verifies expectationsAssert that a request was sent correctly
FakeSimplified working implementationRealistic flows without the real backend
SpyWraps a real or stubbed client and logs callsInspect interactions after the fact
Service virtualizationFull simulated service with state and rulesIntegration and performance environments
Kinds of API test doubles

In everyday API work, a mock API usually means a stub server that returns realistic responses, whereas in unit testing a mock is an object that verifies expected calls. Clear naming inside a team prevents confusion during code review.

Contract-driven mocks and their sources

The most reliable mocks are generated from a machine-readable API contract rather than written by hand. An OpenAPI document describes paths, parameters, schemas and example responses, so a tool can start a mock server directly from it and keep the simulation aligned with the specification.

The same idea applies to other styles. GraphQL mocks can be produced from the schema definition language, gRPC mocks from Protocol Buffers definitions, and event-driven mocks from AsyncAPI documents. Schema-based generators can also create random but valid data, which helps uncover assumptions about field lengths, optional values and empty arrays.

Generated mocks still drift if the contract itself is outdated. Consumer-driven contract testing closes that gap: the client records the interactions it expects, and the provider runs those recorded expectations against its real implementation in its own pipeline, so that both sides verify the same contract.

When to mock an API and when not to

Mocking is most valuable where the real dependency slows down, blocks or endangers development. It is a poor substitute for verifying the actual integration, which still requires tests against a real or production-like service.

SituationRecommended approachReason
Backend not built yetContract-generated mock serverParallel frontend and backend work
Third-party payment or SMS APIStub with sandbox-like responsesAvoid real charges and messages
Rare error conditionsMock with fault injectionReproducible timeouts and 5xx codes
Rate-limited external serviceRecorded responses replayed locallyFast tests without quota use
Final release verificationReal staging integrationMocks cannot prove compatibility
Decision guide for API mocking

A practical rule is to mock at the boundary you do not own. Internal modules are often better tested together, while external services, especially those with costs, quotas or side effects, are strong candidates for simulation.

Risks and common mistakes in API mocking

The central risk is mock drift: the simulation keeps answering in the old way while the real API changes, and tests stay green even though production breaks. Over-mocking adds a second problem, because tests become tightly coupled to implementation details and fail after harmless refactoring.

  • Unrealistic happy paths: mocks that never return errors, slow responses or pagination hide real failure handling gaps.
  • Hand-written payloads: invented examples often miss required fields, nullable values or real date formats.
  • Mocks leaking into production: a misconfigured base URL or feature flag can route live traffic to a simulator.
  • Ignoring authentication: skipping API key or token checks in the mock leaves authorization logic untested.
  • No ownership: shared mock definitions without a maintainer go stale quickly.

Mitigations include generating mocks from the current contract, running contract tests in both repositories, refreshing recorded fixtures on a schedule and keeping a small set of end-to-end tests against the real service.

The idea in brief

Software often depends on other services, such as a payment system or a weather feed. API mocking means building a stand-in that answers like the real service but runs under the team’s full control.

It works like a flight simulator. Pilots can practice engine failures safely, and developers can practice outages, slow answers and odd data without touching the real system. The stand-in is excellent for practice but never replaces a real test flight.

A practical scenario

A team building a mobile banking app needs the new transfers screen ready in six weeks, but the backend team will deliver the transfer API only in week four. Both teams agree on an OpenAPI contract in the first week, and the mobile developers start a mock server generated from it, adding examples for insufficient funds, daily limit errors and a three-second delay.

By week four, the screen already handles eleven distinct response cases, including two error states the backend team had not yet documented. Switching to the real staging API reveals only one mismatch, a date field in a different format, which a contract test catches before release. The project ships on time with no integration surprises in production.