Registry / http-networking / open-api-mocker

open-api-mocker

JSON →
library2.0.0jsnpmunverified

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.

npm install open-api-mocker
INSTALL
IMPORT
SIG · OPEN-API-MOCKER
O
open-api-mocker
http-networkingjavascriptv2.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

OpenApiMocker
import { OpenApiMocker } from 'open-api-mocker';
const { OpenApiMocker } = require('open-api-mocker');
Main class for programmatic server setup. While the package is primarily a CLI tool, this allows embedding the mocker into custom Node.js applications.
run
import { run } from 'open-api-mocker';
This function is the programmatic entry point for the CLI. It accepts an array of strings representing command-line arguments. Useful for testing or embedding CLI-like behavior.

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();
open-api-mocker --version
Debug
Known issues
gotchaWhen 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.
fix
Refer to the `faker` library documentation for correct method signatures and ensure `x-faker` values match these. Example: `x-faker: name.firstName` or `x-faker: 'random.number({ "min": 1, "max": 20 })'`.
affects: >=1.0.0
breakingVersion 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.
fix
Review your programmatic usage and ensure it aligns with the officially documented `OpenApiMocker` class and its constructor options. Re-verify type definitions if using TypeScript.
affects: >=2.0.0
gotchaFor 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.
fix
Validate your OpenAPI schema using tools like `spectral` or online validators before passing it to the mocker. Simplify complex parts of the schema if response generation becomes problematic.
affects: >=1.0.0
gotchaWhen 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.
fix
Use `-v "$PWD/my-schema.yaml:/app/schema.json"` for mounting from the host, and then `docker run ... jormaechea/open-api-mocker -s /app/schema.json` to tell the mocker where to find it inside the container.
affects: >=1.0.0
Errors
Common errors & fixes
Error: Cannot find module 'open-api-mocker' or its corresponding type declarations.
The package is not installed, or the import path is incorrect, or TypeScript cannot find type definitions.
fix
Run `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]
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.
fix
Carefully 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'.
The incoming request path and HTTP method do not match any defined operation in the provided OpenAPI schema.
fix
Check 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.
The specified port for the mock server is already being used by another process on your system.
fix
Choose 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 })`).
Upgrade
Version history
2.0.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
5 hits · last 30 days
node
4
Amazon
1
Resources