API Response Mocker
Define status code, headers, and body — generate a fetch mock, MSW handler, or JSON fixture in one click
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:
- Develop UI components before the API is ready
- Write deterministic unit and integration tests without network calls
- Simulate error states (429 rate limit, 500 server error, 401 unauthorized) that are hard to reproduce reliably
- Test edge cases like empty lists, very large payloads, or malformed bodies
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
- Choose a preset (or start blank) from the Presets panel — REST CRUD, auth, pagination, and error templates are included
- Set the HTTP method and URL path — used in the MSW handler output
- Pick a status code from the dropdown (200 OK, 201 Created, 404 Not Found, etc.)
- Add response headers — use the Quick Add menu for common headers like
Content-Type,Access-Control-Allow-Origin, orCache-Control - Write the response body in JSON, text, or XML (or choose “None” for 204/304 responses)
- Select the output format: JavaScript fetch mock, MSW handler, or plain JSON
- 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
| Header | Purpose |
|---|---|
Content-Type: application/json | Body is JSON-encoded |
Content-Type: text/plain; charset=utf-8 | Body is plain text |
Access-Control-Allow-Origin: * | Allow all origins (CORS) |
Cache-Control: no-cache | Disable caching |
Cache-Control: public, max-age=3600 | Cache for 1 hour |
X-Total-Count: 42 | Total items across all pages |
X-RateLimit-Remaining: 0 | Rate limit exhausted |
Retry-After: 3600 | Wait 3600 seconds before retrying |
Location: /api/items/124 | URL 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
| Range | Category | Common Codes |
|---|---|---|
| 2xx | Success | 200 OK, 201 Created, 204 No Content |
| 3xx | Redirect | 301 Moved Permanently, 304 Not Modified |
| 4xx | Client Error | 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 422 Unprocessable Entity, 429 Too Many Requests |
| 5xx | Server Error | 500 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:
- GET List — paginated collection with
X-Total-Countheader - GET Single — one resource by ID
- POST Create — 201 response with
Locationheader - PUT Update — 200 with updated fields
- DELETE — 204 No Content (empty body)
Auth Endpoints
- Login Success — access token, refresh token, user object
- Login Failed — 401 with
error+message - Token Refresh — new access token
- GET Current User — authenticated user profile
Pagination
- Cursor Pagination — GitHub/Relay style with
cursor.nextandhasMore - Offset Pagination — page/perPage with
X-Total-CountandX-Pageheaders
Error Responses
- 422 Validation Error — field-level errors object
- 404 Not Found — standard error body
- 429 Rate Limit — with
X-RateLimit-*andRetry-Afterheaders - 500 Server Error — with
requestIdfor tracing
CORS
- Preflight (204) — full CORS headers for
OPTIONSresponses includingAccess-Control-Max-Age
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.