OpenAPI Mocker
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
-
Error: Cannot find module 'open-api-mocker' or its corresponding type declarations.
cause The package is not installed, or the import path is incorrect, or TypeScript cannot find type definitions.fixRun `npm install open-api-mocker` or `yarn add open-api-mocker`. If using TypeScript, ensure `esModuleInterop` is true in `tsconfig.json` for CommonJS imports, though named imports are preferred for this ESM-first library. -
Error: Invalid OpenAPI Schema provided. Details: [YAML parsing error] or [JSON schema validation error]
cause The provided OpenAPI schema file is either malformed (e.g., syntax errors in YAML/JSON) or does not conform to the OpenAPI 3.x specification.fixCarefully review your `schema.yaml` or `schema.json` file for syntax errors and validate it against the OpenAPI 3.x specification using an external validator (e.g., `spectral lint your-schema.yaml` or online OpenAPI validators). -
Error: No operation found for path '/your-path' and method 'GET'.
cause The incoming request path and HTTP method do not match any defined operation in the provided OpenAPI schema.fixCheck your client's request URL and method against your OpenAPI schema's `paths` section. Ensure paths match exactly, including any base paths defined in the `servers` object of your schema. -
Error: Port 5000 is already in use.
cause The specified port for the mock server is already being used by another process on your system.fixChoose a different port for the mocker using the `-p <port>` CLI option or the `port` option in the programmatic `OpenApiMocker` constructor (e.g., `open-api-mocker -p 8081` or `new OpenApiMocker({ port: 8081 })`).
Warnings
- gotcha When using `x-faker` or `x-count` extensions, ensure that `faker` (or `@faker-js/faker` for v7+) is available as a dependency or that the Mocker's internal dependencies are correctly installed. Incorrect syntax for faker methods will lead to errors in response generation.
- breaking Version 2.0.0 involved a rewrite to TypeScript. While the CLI interface aims for backward compatibility, programmatic users transitioning from older versions might encounter subtle type-related issues or changes in object structures if they were relying on internal, undocumented APIs.
- gotcha For complex schemas, especially those with circular references or deeply nested objects, the automatic response generation might encounter limitations or performance issues. Ensure your OpenAPI schema is valid and well-formed.
- gotcha When running as a Docker container, ensure the OpenAPI schema file is correctly mounted to the container's `/app/schema.json` path or specified via the `-s` argument within the container. Incorrect pathing will lead to startup failures.
Install
-
npm install open-api-mocker -
yarn add open-api-mocker -
pnpm add open-api-mocker
Imports
- OpenApiMocker
const { OpenApiMocker } = require('open-api-mocker');import { OpenApiMocker } from 'open-api-mocker'; - run
import { run } from 'open-api-mocker';
Quickstart
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();