API Mocking

Simulating API behavior to enable development and testing without real backend services.

API mocking is the practice of creating simulated versions of APIs that mimic the behavior of real services. It enables teams to develop and test applications independently of actual backend systems.

Why Mock APIs?

  • Faster Development: No waiting for backend teams to finish
  • Reliable Testing: Consistent responses without network issues
  • Cost Reduction: Avoid third-party API charges during development
  • Edge Case Testing: Easily simulate errors and unusual scenarios

Mocking Approaches

ApproachDescriptionBest For
Static MocksFixed JSON responsesSimple testing
Dynamic MocksGenerated based on requestRealistic scenarios
Record & ReplayCapture real responsesIntegration testing
Contract-BasedFrom OpenAPI/Swagger specsAPI-first development

Popular Tools

  • MSW - Mock Service Worker for browser/Node
  • Nock - HTTP mocking for Node.js
  • Mirage JS - Client-side API mocking
  • Prism - OpenAPI-based mock server

Code Examples

MSW Handler

import { http, HttpResponse } from "msw";

export const handlers = [
  http.get("/api/users", () => {
    return HttpResponse.json([
      { id: 1, name: "John" },
      { id: 2, name: "Jane" }
    ]);
  })
];