{"id":16471,"library":"open-api-mocker","title":"OpenAPI Mocker","description":"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.","status":"active","version":"2.0.0","language":"javascript","source_language":"en","source_url":"https://jormaechea@github.com/jormaechea/open-api-mocker","tags":["javascript","api","openapi","schema","mock","mocking","mock-server"],"install":[{"cmd":"npm install open-api-mocker","lang":"bash","label":"npm"},{"cmd":"yarn add open-api-mocker","lang":"bash","label":"yarn"},{"cmd":"pnpm add open-api-mocker","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Main class for programmatic server setup. While the package is primarily a CLI tool, this allows embedding the mocker into custom Node.js applications.","wrong":"const { OpenApiMocker } = require('open-api-mocker');","symbol":"OpenApiMocker","correct":"import { OpenApiMocker } from 'open-api-mocker';"},{"note":"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.","symbol":"run","correct":"import { run } from 'open-api-mocker';"}],"quickstart":{"code":"import { OpenApiMocker } from 'open-api-mocker';\nimport * as path from 'path';\nimport * as fs from 'fs';\n\n// Create a dummy OpenAPI schema file for demonstration\nconst schemaContent = `\nopenapi: '3.0.0'\ninfo:\n  title: Mock API\n  version: '1.0.0'\nservers:\n  - url: http://localhost:8080/v1\npaths:\n  /items:\n    get:\n      summary: Get all items\n      responses:\n        '200':\n          description: A list of items\n          content:\n            application/json:\n              schema:\n                type: array\n                items:\n                  type: object\n                  properties:\n                    id:\n                      type: integer\n                      format: int64\n                      example: 1\n                    name:\n                      type: string\n                      x-faker: commerce.productName\n                    price:\n                      type: number\n                      x-faker: commerce.price\n`;\nconst schemaPath = path.resolve(__dirname, 'mock-schema.yaml');\nfs.writeFileSync(schemaPath, schemaContent);\n\nasync function startMockServer() {\n  try {\n    console.log(`Starting mock server with schema: ${schemaPath}`);\n    const mocker = new OpenApiMocker({\n      schema: schemaPath,\n      port: 8080,\n      watch: false, // Set to true to reload on schema changes\n      log: true\n    });\n    await mocker.start();\n    console.log('OpenAPI Mocker started on http://localhost:8080');\n    console.log('Try accessing: http://localhost:8080/v1/items');\n\n    // Keep the server running for a few seconds for demonstration\n    // In a real app, you'd manage lifecycle differently.\n    setTimeout(async () => {\n      console.log('Stopping mock server...');\n      await mocker.stop();\n      console.log('Mock server stopped.');\n      fs.unlinkSync(schemaPath); // Clean up the dummy schema\n    }, 10000);\n\n  } catch (error) {\n    console.error('Failed to start mock server:', error);\n    fs.unlinkSync(schemaPath); // Ensure cleanup even on error\n  }\n}\n\nstartMockServer();","lang":"typescript","description":"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."},"warnings":[{"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 })'`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"breaking","affected_versions":">=2.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"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.","cause":"The package is not installed, or the import path is incorrect, or TypeScript cannot find type definitions.","error":"Error: Cannot find module 'open-api-mocker' or its corresponding type declarations."},{"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).","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.","error":"Error: Invalid OpenAPI Schema provided. Details: [YAML parsing error] or [JSON schema validation error]"},{"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.","cause":"The incoming request path and HTTP method do not match any defined operation in the provided OpenAPI schema.","error":"Error: No operation found for path '/your-path' and method 'GET'."},{"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 })`).","cause":"The specified port for the mock server is already being used by another process on your system.","error":"Error: Port 5000 is already in use."}],"ecosystem":"npm"}