Mock API

A simulated API endpoint that returns predefined responses for testing and development.

A mock API is a simulated API endpoint that mimics the behavior of a real API without connecting to actual backend services. When you call a mock API, it returns predefined responses that look and feel like real data, but nothing is actually processed or stored on a real server.

Mock API vs Real API

AspectMock APIReal API
Data sourcePredefined JSON or generatedDatabase, external services
Side effectsNone - nothing changesCreates, updates, deletes real data
AvailabilityAlways worksMay be down, rate limited, slow
CostFreeMay charge per request
ConsistencySame response every timeData changes between calls

When to Use Mock APIs

During development: The backend isn't ready but you need to build the frontend. Create mock APIs that match the agreed contract and start coding immediately.

For testing: Unit tests shouldn't depend on external services. Mock APIs provide consistent, predictable responses that make tests reliable and fast.

For demos and prototypes: Show stakeholders a working prototype without building the full backend. Mock APIs let you demonstrate the user experience early.

When APIs are expensive: Payment gateways, SMS services, AI APIs charge per call. Use mock APIs during development to avoid unnecessary costs.

When APIs are unreliable: Third-party APIs go down, get slow, or change their responses. Mock APIs give you a stable development environment.

Creating Mock APIs

Option 1: Static JSON files The simplest approach - create JSON files and serve them:

  • /mocks/users.jsonGET /api/users
  • Quick to set up, but no dynamic behavior

Option 2: Mock server tools Tools like json-server, Prism, or MSW:

  • Dynamic responses based on request parameters
  • Support for different HTTP methods
  • Can simulate delays and errors

Option 3: Online mock services Platforms like Mocky, Beeceptor, or Mockoon:

  • No setup required
  • Share mock endpoints with team
  • Good for quick testing

Option 4: Code-based mocks Define mocks in your test code:

  • Full control over behavior
  • Easy to create edge cases
  • Best for unit/integration tests

What Makes a Good Mock API

Realistic data structure: The mock should return data in the exact format the real API will use. If you mock {userName} but the real API returns {user_name}, you'll have bugs later.

Proper status codes: Don't return 200 for everything. Mock 201 for creation, 404 for not found, 401 for unauthorized. Your frontend needs to handle these cases.

Realistic response times: Add small delays (50-200ms) to mock the network latency you'll experience in production. This reveals issues with loading states.

Error scenarios: Create mock endpoints that return errors. How does your app handle a 500? A timeout? A malformed response?

Edge cases: Mock empty arrays, null values, very long strings, special characters. These are where bugs hide.

Mock API Best Practices

Keep mocks in sync with specs: If you have an OpenAPI spec, generate mocks from it. Manual mocks drift from reality over time.

Use realistic fake data: Libraries like Faker.js generate realistic names, emails, addresses, and dates. {name: "John Doe"} is better than {name: "test"}.

Document your mocks: Note what each mock endpoint does and how it differs from the real API. Future developers will thank you.

Version your mocks: When the real API changes, update your mocks. Keep them in the same repo as your frontend code.

Don't mock too much: Only mock what you need. If you mock your entire application, you're not testing anything real.

Common Mistakes

1. Mocks that never fail Your mock API always returns 200 with perfect data. Then production hits you with 500 errors, empty responses, and timeouts. Mock failure cases.

2. Data structure mismatch Mock returns {id: "123"} but real API returns {id: 123}. Type mismatches cause subtle bugs.

3. Forgetting authentication Real API requires auth tokens, but your mock doesn't check them. You deploy and nothing works because auth wasn't tested.

4. Hardcoded IDs Mock always returns user with id: 1. Your code works, but only for user 1. Use dynamic data to catch these issues.

Code Examples

Creating Mock API with MSW

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

// Define mock handlers
const handlers = [
  // Successful response
  http.get('/api/products', async () => {
    await delay(100); // Simulate network latency
    return HttpResponse.json({
      data: [
        { id: 1, name: 'Widget', price: 29.99 },
        { id: 2, name: 'Gadget', price: 49.99 },
      ],
      total: 2
    });
  }),

  // Dynamic response based on params
  http.get('/api/products/:id', ({ params }) => {
    const id = Number(params.id);
    if (id === 999) {
      return HttpResponse.json(
        { error: 'Product not found' },
        { status: 404 }
      );
    }
    return HttpResponse.json({ id, name: 'Widget', price: 29.99 });
  }),

  // Simulate server error
  http.post('/api/checkout', () => {
    return HttpResponse.json(
      { error: 'Payment service unavailable' },
      { status: 503 }
    );
  }),
];

// Start mock server
const server = setupServer(...handlers);
server.listen();