PureDevTools

API Response Mocker

Define status code, headers, and body — generate a fetch mock, MSW handler, or JSON fixture in one click

All processing happens in your browser. No data is sent to any server.
200OK

Response Headers

Response Body

vi.fn() / jest.fn() — replaces global fetch

// Vitest / Jest — mock global fetch
global.fetch = vi.fn().mockResolvedValue({
  status: 200,
  statusText: "OK",
  ok: true,
  headers: new Headers({
    "Content-Type": "application/json",
    "X-Total-Count": "42",
  }),
    json: async () => ({
      "data": [
        {
          "id": 1,
          "name": "Item 1",
          "createdAt": "2024-01-01T00:00:00Z"
        },
        {
          "id": 2,
          "name": "Item 2",
          "createdAt": "2024-01-02T00:00:00Z"
        }
      ],
      "pagination": {
        "page": 1,
        "perPage": 20,
        "total": 42,
        "totalPages": 3
      }
    }),
  text: async () => JSON.stringify({
      "data": [
        {
          "id": 1,
          "name": "Item 1",
          "createdAt": "2024-01-01T00:00:00Z"
        },
        {
          "id": 2,
          "name": "Item 2",
          "createdAt": "2024-01-02T00:00:00Z"
        }
      ],
      "pagination": {
        "page": 1,
        "perPage": 20,
        "total": 42,
        "totalPages": 3
      }
    }),
} as Response);

You’re building a login form. The backend isn’t ready yet, but you need to test what happens when the server returns a 401. Or you’re writing a Jest test for a paginated list component and need a consistent mock response every time. That’s exactly what this tool is for — define the response you need, copy the generated code, and move on.

What Is API Response Mocking?

API response mocking means creating a fake HTTP response that your frontend or test suite uses instead of hitting a real backend. It lets you:

Why This Tool

Most mock generators only output one format. This tool generates three — a vi.fn() / jest.fn() fetch mock, an MSW v2 handler, and a plain JSON fixture — from the same configuration. It also ships with 15 preset templates covering the patterns you actually encounter: REST CRUD, auth flows, cursor and offset pagination, rate limit errors, and CORS preflight. No other free online tool covers all three output formats with built-in presets.

How to Use This Tool

  1. Choose a preset (or start blank) from the Presets panel — REST CRUD, auth, pagination, and error templates are included
  2. Set the HTTP method and URL path — used in the MSW handler output
  3. Pick a status code from the dropdown (200 OK, 201 Created, 404 Not Found, etc.)
  4. Add response headers — use the Quick Add menu for common headers like Content-Type, Access-Control-Allow-Origin, or Cache-Control
  5. Write the response body in JSON, text, or XML (or choose “None” for 204/304 responses)
  6. Select the output format: JavaScript fetch mock, MSW handler, or plain JSON
  7. Copy the generated code directly into your test file

Output Formats Explained

JavaScript Fetch Mock (Vitest / Jest)

Generates a vi.fn() (or jest.fn()) that replaces the global fetch. Useful for unit tests that call fetch directly:

global.fetch = vi.fn().mockResolvedValue({
  status: 200,
  statusText: "OK",
  ok: true,
  headers: new Headers({ "Content-Type": "application/json" }),
  json: async () => ({ id: 1, name: "Example" }),
  text: async () => '{"id":1,"name":"Example"}',
} as Response);

MSW Handler (Mock Service Worker)

Generates an MSW v2 handler using http and HttpResponse. MSW intercepts requests at the network level — works in both browsers (service worker) and Node.js (test environments):

import { http, HttpResponse } from 'msw'

export const handlers = [
  http.get('/api/items', () => {
    return HttpResponse.json({ data: [] }, { status: 200 })
  }),
]

Plain JSON

Generates a JSON object representing the full mock response. Useful as a fixture file, or as input to custom mock adapters (Axios, ky, etc.). You can format and validate the body with the JSON Formatter before pasting it in.

{
  "status": 200,
  "statusText": "OK",
  "ok": true,
  "headers": { "Content-Type": "application/json" },
  "body": { "id": 1, "name": "Example" }
}

Common Response Headers Reference

HeaderPurpose
Content-Type: application/jsonBody is JSON-encoded
Content-Type: text/plain; charset=utf-8Body is plain text
Access-Control-Allow-Origin: *Allow all origins (CORS)
Cache-Control: no-cacheDisable caching
Cache-Control: public, max-age=3600Cache for 1 hour
X-Total-Count: 42Total items across all pages
X-RateLimit-Remaining: 0Rate limit exhausted
Retry-After: 3600Wait 3600 seconds before retrying
Location: /api/items/124URL of newly created resource
ETag: "abc123"Cache validation token

If you need to generate the CORS headers themselves, use the CORS Header Generator.

HTTP Status Code Cheat Sheet

RangeCategoryCommon Codes
2xxSuccess200 OK, 201 Created, 204 No Content
3xxRedirect301 Moved Permanently, 304 Not Modified
4xxClient Error400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 422 Unprocessable Entity, 429 Too Many Requests
5xxServer Error500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable

For a full reference with descriptions and use cases, see the HTTP Status Codes reference.

Preset Template Categories

REST CRUD

The five standard REST operations:

Auth Endpoints

Pagination

Error Responses

CORS

Privacy and Security

All mock generation happens in your browser. Nothing is sent to any server. No API tokens, response bodies, or header values are stored or logged.

Frequently Asked Questions

What is MSW and when should I use it? Mock Service Worker (MSW) intercepts requests at the network layer using a service worker in the browser or @mswjs/interceptors in Node. It is the most realistic mocking approach because your production code runs unchanged — only the network response is swapped. Use it for integration tests and Storybook.

When should I use vi.fn() / jest.fn() over MSW? vi.fn() is simpler and works for pure unit tests that call fetch directly in isolation. MSW is better for component and integration tests where you want the full request/response cycle.

Can I mock a 204 No Content response? Yes. Set the status to 204 and body type to “None”. The generated fetch mock returns text: async () => "" and the MSW handler returns new HttpResponse(null, { status: 204 }).

How do I mock multiple endpoints? Run the tool once per endpoint and copy each handler. In your MSW setup, add all handlers to the same handlers array.

Does the tool validate my JSON body? Yes. If you select JSON as the body type and enter invalid JSON, the generated output will treat the raw string as a fallback. For best results, use valid JSON so the output includes the parsed object rather than a raw string.

Related Tools

More DevOps & Networking Tools