OpenAPI Mocker

2.0.0 · active · verified Wed Apr 22

OpenAPI Mocker is a robust mock server designed to generate API responses based on an OpenAPI 3.x specification (both YAML and JSON formats). It provides a quick way for developers to establish a local mock API, primarily through a command-line interface (CLI) or Docker container, but also offers a programmatic API. The current stable version, 2.0.0, represents a significant rewrite in TypeScript, enhancing maintainability and type safety. Key capabilities include comprehensive request parameter and body validation, dynamic response generation derived from schema examples, flexible response selection via `Prefer` HTTP headers (e.g., `statusCode=XXX`, `example=name`), and advanced data customization through `x-faker` and `x-count` extensions for generating realistic, randomized data. Its primary differentiator is the rich support for OpenAPI 3.0 features and custom extensions, making it ideal for rapid API prototyping, frontend development, and testing in environments where a backend is not yet available or stable.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically initialize and start the OpenAPI Mocker server using an in-memory YAML schema, leveraging `x-faker` to generate dynamic response data, and then gracefully stopping it. It requires creating a temporary schema file.

import { OpenApiMocker } from 'open-api-mocker';
import * as path from 'path';
import * as fs from 'fs';

// Create a dummy OpenAPI schema file for demonstration
const schemaContent = `
openapi: '3.0.0'
info:
  title: Mock API
  version: '1.0.0'
servers:
  - url: http://localhost:8080/v1
paths:
  /items:
    get:
      summary: Get all items
      responses:
        '200':
          description: A list of items
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    id:
                      type: integer
                      format: int64
                      example: 1
                    name:
                      type: string
                      x-faker: commerce.productName
                    price:
                      type: number
                      x-faker: commerce.price
`;
const schemaPath = path.resolve(__dirname, 'mock-schema.yaml');
fs.writeFileSync(schemaPath, schemaContent);

async function startMockServer() {
  try {
    console.log(`Starting mock server with schema: ${schemaPath}`);
    const mocker = new OpenApiMocker({
      schema: schemaPath,
      port: 8080,
      watch: false, // Set to true to reload on schema changes
      log: true
    });
    await mocker.start();
    console.log('OpenAPI Mocker started on http://localhost:8080');
    console.log('Try accessing: http://localhost:8080/v1/items');

    // Keep the server running for a few seconds for demonstration
    // In a real app, you'd manage lifecycle differently.
    setTimeout(async () => {
      console.log('Stopping mock server...');
      await mocker.stop();
      console.log('Mock server stopped.');
      fs.unlinkSync(schemaPath); // Clean up the dummy schema
    }, 10000);

  } catch (error) {
    console.error('Failed to start mock server:', error);
    fs.unlinkSync(schemaPath); // Ensure cleanup even on error
  }
}

startMockServer();

view raw JSON →