API mocking is a technique used to simulate the behavior of real APIs during testing. It helps isolate your system under test, test edge cases, and avoid dependencies on external services.

Tools for API Mocking

Choose a tool based on your tech stack:

Setup Steps

1. Define Mock Endpoints

Specify

Example (WireMock JSON config)

{
  "request": {
    "method": "GET",
    "url": "/api/users/123"
  },
  "response": {
    "status": 200,
    "body": "{\"id\":123,\"name\":\"Pratik\"}",
    "headers": {
      "Content-Type": "application/json"
    }
  }
}

2. Integrate with Your Test Framework

JavaScript (MSW Example)

import { setupServer } from 'msw/node';
import { rest } from 'msw';

const server = setupServer(
  rest.get('/api/users/:id', (req, res, ctx) => {
    return res(ctx.status(200), ctx.json({ id: req.params.id, name: 'Pratik' }));
  })
);

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

Python (responses Example)

import responses
import requests

@responses.activate
def test_api_mock():
    responses.add(
        responses.GET,
        'http://example.com/api/users/123',
        json={'id': 123, 'name': 'Pratik'},
        status=200
    )
    resp = requests.get('http://example.com/api/users/123')
    assert resp.json() == {'id': 123, 'name': 'Pratik'}

Best Practices