Mock API Response Generator with JSON Schema Validation

May 25, 2026 · 12 min read

Building a frontend before the backend is ready is one of the most common workflows in modern development. You know the API contract, you know the data shape, but the endpoints do not exist yet. A mock API response generator solves this by letting you define exactly what the server will return: the HTTP method, status code, response headers, JSON body, and even the response delay. This tool generates the complete mock configuration, including a ready-to-paste curl command, so you can test every code path in your UI without waiting for a single backend deployment.

Beyond simple mocking, this tool includes a JSON Schema validator. Paste your schema and your response body, and the validator checks that every field matches the expected type, required properties are present, and constraints like minimum values or string patterns are satisfied. This catches contract mismatches before they reach production, where they cause silent data corruption or runtime crashes.

Interactive Mock API Generator

Configure your mock response below. Select the HTTP method and status code, define the response body in the JSON editor, add custom headers, and set a response delay. Click Generate Mock to produce the curl command and mock server configuration.

Response Configuration

// Configure your mock response and click "Generate Mock"

Pre-Built Response Templates

Click any template button above to load a complete response structure into the editor. Each template represents a common REST API pattern you will encounter in production:

Template Method Status Use Case
REST Success GET 200 Standard resource fetch with data envelope and metadata
Error Response POST 400 Validation error with field-level error messages
Paginated List GET 200 Cursor-based pagination with next_cursor and has_more
Auth Token POST 200 OAuth 2.0 token response with access_token and refresh_token

JSON Schema Validator

Paste a JSON Schema below and click Validate to check the response body against it. The validator supports JSON Schema Draft 7 features including required fields, type checking, enum constraints, minimum/maximum values, string patterns, and nested object schemas. Errors are reported with the exact JSON path that failed validation.

Schema Validation

Why Mock API Responses

Mock API responses are not a convenience. They are a fundamental requirement for professional frontend development. Without mocks, frontend teams are blocked by backend timelines, unable to test error paths, and forced to deploy code that has only been verified against the happy path. The cost of this approach is production incidents: a missing field causes a TypeError, an unexpected status code renders a blank screen, a slow response leaves the user staring at an infinite spinner.

The data is clear. Teams that mock API responses during development ship 40-60% faster because frontend and backend development happens in parallel. They catch contract mismatches during development instead of during QA or, worse, in production. They test every status code path (200, 400, 401, 403, 404, 429, 500, 503) because mocking makes it trivial to simulate each one. And they build better UX because they can prototype against realistic data shapes rather than hardcoded placeholder text.

The traditional approach of pointing your frontend at a staging server has three critical problems. First, staging environments are unreliable. They go down, they have stale data, and they do not reproduce the edge cases you need to test. Second, you cannot control what staging returns. Need to test a 429 rate limit response? You would have to actually trigger rate limiting, which may not even be configured on staging. Third, staging introduces network latency and flakiness into your development loop, turning a 50ms feedback cycle into a 500ms one. Mock responses eliminate all three problems. For rapid prototyping, Kappafy's JSON explorer pairs well with this mock generator to visualize and validate your data structures.

Anatomy of an API Response

Every HTTP API response consists of three parts: the status line, the headers, and the body. Understanding each part is essential for creating realistic mocks that exercise all the code paths in your frontend.

The status code is the single most important signal your frontend uses to decide what to do. A 200 means "process the body as data." A 201 means "resource was created, check the Location header." A 204 means "success, but there is no body." A 400 means "the request was malformed, show validation errors." A 401 means "redirect to login." A 429 means "back off and retry after the Retry-After header value." A 500 means "something broke on the server, show an error and maybe retry." Each status code triggers a completely different code path. If you only mock 200 responses, you are only testing one path.

Response headers carry metadata that your frontend may need to process. Content-Type tells the client how to parse the body. X-Request-Id enables correlating frontend errors with backend logs. Retry-After tells the client how long to wait before retrying a 429 or 503. ETag and Last-Modified enable conditional requests that save bandwidth. X-RateLimit-Remaining lets the client proactively throttle requests before hitting the limit. Realistic mocks include these headers because your code may depend on them.

The response body is typically JSON for REST APIs. The structure varies by convention: some APIs wrap data in an envelope ({"data": {...}, "meta": {...}}), while others return the resource directly. Error responses have their own structure with error codes, messages, and field-level details. Your mock bodies should match the exact shape your frontend expects, including edge cases like null values, empty arrays, and missing optional fields.

Status Codes for Mocking

When building mock API responses, you should create mocks for every status code your frontend is expected to handle. Here is the essential set, organized by category, with the specific frontend behavior each should trigger.

Code Name Frontend Behavior
200OKParse body, render data, update cache
201CreatedParse body, redirect or show success, invalidate list cache
204No ContentSuccess with no body, remove from UI (for DELETE)
400Bad RequestParse error body, show field-level validation errors
401UnauthorizedClear auth state, redirect to login
403ForbiddenShow "access denied" message, do not redirect to login
404Not FoundShow "not found" UI or redirect to parent resource
409ConflictShow "already exists" or conflict resolution UI
422UnprocessableShow semantic validation errors (valid syntax, invalid data)
429Too Many RequestsRead Retry-After, queue request, show "slow down" indicator
500Server ErrorShow generic error, offer retry button, log to error tracker
503UnavailableShow maintenance message, auto-retry with backoff

Common Mocking Patterns

Pattern 1: Data Envelope

The most widely adopted API response pattern wraps the actual data in an envelope that separates data from metadata. This makes it unambiguous where the primary content lives and provides a consistent location for pagination info, rate limit details, and request IDs.

{
  "data": {
    "id": 42,
    "name": "Project Alpha",
    "status": "active"
  },
  "meta": {
    "request_id": "req_abc123",
    "timestamp": "2026-05-25T10:30:00Z"
  }
}

Your frontend code always reads response.data for the resource and response.meta for metadata. This consistency across every endpoint eliminates guesswork and simplifies error handling because error responses follow the same envelope shape.

Pattern 2: Cursor-Based Pagination

Offset-based pagination (page=2&per_page=25) breaks when records are inserted or deleted between page requests. Cursor-based pagination uses an opaque cursor token that points to the exact position in the result set, making it reliable for real-time data.

{
  "data": [...],
  "pagination": {
    "next_cursor": "eyJpZCI6MTAwfQ==",
    "has_more": true,
    "total": 1547
  }
}

Mock both the middle pages (where has_more is true) and the last page (where has_more is false and next_cursor is null). Also mock the empty state where data is an empty array and total is 0.

Pattern 3: Error Response with Field Details

For form submissions, a generic "Bad Request" message is useless. The frontend needs to know which fields failed and why, so it can highlight the specific input and show a contextual error message.

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format",
        "code": "INVALID_FORMAT"
      },
      {
        "field": "password",
        "message": "Must be at least 8 characters",
        "code": "TOO_SHORT"
      }
    ]
  }
}

Integration with Frontend Frameworks

Once you have generated your mock response, you need to serve it to your frontend. The approach depends on your stack, but the core concept is the same: intercept HTTP requests and return your predefined responses.

MSW (Mock Service Worker)

MSW intercepts requests at the network level, so your application code does not know it is receiving mocked data. This is the gold standard for frontend mocking because you test the actual fetch/axios calls, not a mock abstraction.

import { http, HttpResponse, delay } from 'msw';

export const handlers = [
  http.get('https://api.example.com/v1/users', async () => {
    await delay(200); // simulate network latency
    return HttpResponse.json({
      data: {
        users: [
          { id: 1, name: 'Alice', email: 'alice@example.com' }
        ]
      },
      meta: { total: 1, page: 1, per_page: 25 }
    }, { status: 200 });
  })
];

json-server

For quick REST mocking without any code, json-server creates a full CRUD API from a single JSON file. Point your frontend at http://localhost:3001 and it handles GET, POST, PUT, PATCH, and DELETE automatically.

# db.json
{
  "users": [
    { "id": 1, "name": "Alice", "email": "alice@example.com" },
    { "id": 2, "name": "Bob", "email": "bob@example.com" }
  ]
}

# Run: npx json-server --watch db.json --port 3001

Fetch Wrapper

For the simplest possible mock, wrap the global fetch function to return your predefined response when the URL matches. This works anywhere JavaScript runs and requires zero dependencies.

const mockResponses = new Map([
  ['GET /api/users', {
    status: 200,
    body: { data: { users: [...] }, meta: { total: 2 } }
  }],
  ['POST /api/users', {
    status: 201,
    body: { data: { id: 3, name: 'New User' } }
  }]
]);

const originalFetch = window.fetch;
window.fetch = async (url, options = {}) => {
  const method = (options.method || 'GET').toUpperCase();
  const path = new URL(url).pathname;
  const key = method + ' ' + path;
  const mock = mockResponses.get(key);
  if (mock) {
    await new Promise(r => setTimeout(r, 200));
    return new Response(JSON.stringify(mock.body), {
      status: mock.status,
      headers: { 'Content-Type': 'application/json' }
    });
  }
  return originalFetch(url, options);
};

For visualizing the JSON structures in your mocks, use Kappafy's JSON explorer to render them as collapsible trees. If you need to prettify minified JSON from production logs before mocking it, that tool handles it in one click. Teams building webhook integrations often use this mock generator to simulate the webhook payloads they will receive.

Frequently Asked Questions

What is a mock API response generator?

A mock API response generator creates simulated HTTP responses without needing a real backend server. You define the status code, headers, and JSON body, and the tool generates the equivalent curl command or mock server configuration. This lets frontend developers build and test against realistic API contracts before the backend is ready. All processing happens in your browser with no data sent to any server.

How do I validate a JSON response against a schema?

Paste your JSON Schema into the validator panel and your API response body into the response editor. The validator checks that every required field exists, data types match (string, number, boolean, array, object), values fall within defined constraints (minLength, maximum, enum), and nested objects conform to their sub-schemas. Errors are listed with the exact JSON path that failed validation. This catches contract mismatches during development rather than in production.

What HTTP status codes should I use for mock API responses?

For success responses use 200 (OK) for reads, 201 (Created) for resource creation, or 204 (No Content) for deletes. For client errors use 400 (Bad Request) for malformed input, 401 (Unauthorized) for missing auth, 403 (Forbidden) for insufficient permissions, 404 (Not Found) for missing resources, and 422 (Unprocessable Entity) for semantic validation failures. For server errors use 500 (Internal Server Error) and 503 (Service Unavailable). Mock all of these to ensure your frontend handles every case gracefully.

Can I simulate response delay with mock APIs?

Yes. Set the response delay in milliseconds in this tool to simulate network latency. The generated curl command includes a sleep parameter, and the MSW/fetch wrapper code includes an equivalent delay call. Simulating 200-2000ms of latency helps you test loading states, skeleton screens, and timeout handling. Testing with 5000ms+ delays helps verify that your UI remains responsive and shows appropriate loading indicators during slow network conditions.

What are pre-built API response templates?

Pre-built templates are ready-made JSON response structures for common API patterns. The REST Success template gives you a standard 200 response with a data envelope and metadata. The Error Response template provides a 400 with field-level validation errors. The Paginated List template includes cursor-based pagination with next_cursor and has_more fields. The Auth Token template provides an OAuth 2.0 response with access_token, refresh_token, token_type, and expires_in. Load any template with one click and customize it for your specific API contract.

ML

Michael Lip

Solo developer building free tools at Zovo. Kappafy helps developers work with JSON and APIs faster. No tracking, no accounts, no data collection. Learn more.