npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@wylan24/mockgen

v0.1.0-alpha.9

Published

Turn an OpenAPI spec into a running mock server with realistic, deterministic fake data — one command.

Downloads

1,826

Readme

mockgen

CI npm License: MIT

Turn an OpenAPI spec — or just a folder of sample JSON responses — into a running mock server with realistic, stable fake data. One command.

npx @wylan24/mockgen serve ./openapi.yaml
npx @wylan24/mockgen serve ./samples/

You get a server on localhost:4010 that returns schema-valid, human-looking data, returns the same data across restarts, and can be tweaked without writing code.

Status: alpha (0.x). It works and is tested against 57 real-world APIs, but options may still change before 1.0. Feedback and bug reports are very welcome.

Install

Requires Node 22.19 or later. Run it without installing:

npx @wylan24/mockgen serve ./openapi.yaml

Or add it to a project, for scripts and tests:

npm install --save-dev @wylan24/mockgen
npx mockgen serve ./openapi.yaml

Docker

No Node needed. Mount the folder with your spec at /api. By default the container serves /api/openapi.yaml:

docker run --rm -p 4010:4010 -v "$PWD:/api" ghcr.io/wylan24/mockgen

Any other command or option works as usual, for example:

docker run --rm -p 4010:4010 -v "$PWD:/api" ghcr.io/wylan24/mockgen serve /api/spec.json --seed 2
  • Platforms. Images are published for linux/amd64 and linux/arm64 (Apple silicon, Graviton), tagged by version (0.1.0-alpha.9), with latest and next matching npm's dist-tags.

  • Host. The image sets MOCKGEN_HOST=0.0.0.0, so the server is reachable from outside the container without --host.

  • Non-root. It runs as the unprivileged node user. The mounted spec only needs to be readable.

  • Docker Compose. Add it as a service next to your app:

    services:
      api:
        image: ghcr.io/wylan24/mockgen:0.1.0-alpha.9
        ports: ['4010:4010']
        volumes: ['./openapi.yaml:/api/openapi.yaml:ro']

Hot reload works when the container sees file changes on the mount. Some Docker Desktop setups don't pass them through; if edits don't show up, restart the container.

Guides and examples

Coming from another tool, or choosing one? See how mockgen compares with Prism, MSW and json-server, including when each of those is the better pick.

Example apps, each built against a mock API and checked in CI: React + Vite, Next.js and React Native (Expo).

Why

  • Realistic data. Field names drive the data: email, avatarUrl, createdAt, price, city all look like the real thing, and a record's name, username and email match each other.
  • Deterministic. Same spec + seed → byte-identical responses, so screenshots and tests stay stable. GET /users/42 always returns the same user, with id: 42.
  • Valid. Responses honor enum, min/max, pattern, minLength, minItems, uniqueItems, oneOf/anyOf/allOf, nullable, and use your spec's example values when present.
  • Zero config. CORS on, request log in the terminal, hot reload when the spec changes.

Usage

mockgen serve <spec|dir>             # Start a mock server (hot-reloads on change)
mockgen generate <spec|dir> [route]  # Print generated responses, e.g. "GET /users/1"
mockgen validate <spec|dir>          # Generate every response and check it against its schema
mockgen infer <dir> [-o openapi.yaml]  # Write the schema inferred from samples as OpenAPI 3.1

| Option | Default | | | --- | --- | --- | | -p, --port | 4010 | Port to listen on | | -H, --host | 127.0.0.1 | Host to bind | | -s, --seed | 1 | Seed for generated data | | -d, --delay | 0 | Delay every response, e.g. 300ms | | -r, --records | 50 | Records in every list endpoint's collection | | -l, --locale | en | Language and region for names, addresses and phone numbers, e.g. de, ja, pt_BR | | --stateful | off | Remember changes: POST creates, PUT/PATCH update, DELETE removes (see Stateful mode) | | --validate-requests | off | Reject requests that don't match the spec (see Request validation) | | -c, --config | mock.config.* | Config file (see Config file) | | --no-watch | | Disable hot reload | | -o, --out | stdout | infer output file (.yaml or .json) |

Simulating errors and latency

Per request, with a header or a query parameter:

curl -H 'X-Mock-Status: 404' localhost:4010/users/1   # the spec's 404 response
curl 'localhost:4010/users/1?__status=503'            # undocumented codes work too
curl -H 'X-Mock-Delay: 1500' localhost:4010/users     # slow this one down

Other languages

Names, addresses, companies and phone numbers follow --locale. It takes any of the 76 locales Faker ships, such as de, fr, ja, pt_BR or zh_CN:

mockgen serve ./openapi.yaml --locale de

The output stays deterministic per locale, and emails and usernames stay valid ASCII. Free text like description and bio is Latin placeholder text in every locale.

Lists and pagination

Every list endpoint — a bare array of objects, or an object wrapping one (data, items, results, …) — is a window onto a stable collection of 50 records (--records):

curl 'localhost:4010/users?page=2&limit=20'   # also per_page, pageSize, offset/skip
curl 'localhost:4010/users?cursor=bzoyMA'     # any cursor mockgen handed out works
  • Integer ids are sequential (1…50), so page 2 of 10 is ids 11–20, every time.
  • When the spec also has GET /users/{id}, each list item is the same record that route returns.
  • Wrapper fields are filled by name, including nested ones like meta.pagination: total, page, perPage, totalPages, hasMore, next/prev (page number, URL or cursor, and null on the last page).
  • Responses carry X-Total-Count and a Link header with next/prev.

A page past the end is empty, even if the schema sets minItems.

Stateful mode

By default every response depends only on the spec, the seed and the request, so a POST doesn't change what a GET returns. To build forms and flows that create, edit and delete things, turn on stateful mode:

mockgen serve ./openapi.yaml --stateful
curl -X POST localhost:4010/users -H 'content-type: application/json' -d '{"firstName":"Ada"}'
# 201, {"id": 51, "firstName": "Ada", ...}, Location: /users/51
curl localhost:4010/users/51            # the same record
curl -X PATCH localhost:4010/users/51 -H 'content-type: application/json' -d '{"lastName":"Lovelace"}'
curl -X DELETE localhost:4010/users/7   # then GET /users/7 is a 404, and /users has 49 records
  • Create. POST to a list path creates a record: generated from the schema, with your fields on top. It gets the next id (51, 52, … for integer ids; a fresh generated one otherwise), and appears in the detail route and at the end of the list.
  • Update and delete. PUT and PATCH merge your fields into the record. DELETE removes it. Lists, totals and paging reflect both.
  • Not found. Ids that aren't in the collection get the spec's 404, like a real API.
  • Always valid. Fields that don't fit the schema, unknown fields, read-only fields and the id are ignored, so responses stay valid. A changed name carries over to the email and username (Ada Lovelace becomes ada.lovelace@…), unless you set those too.
  • Reset. POST /__mockgen/reset (or mock.reset()) goes back to the generated data. So does a spec reload. Changes live in memory and are lost when the server stops.
  • Deterministic. The same requests in the same order give the same results. X-Mock-Status still simulates errors, without changing anything.

In tests: createMockServer({ spec, stateful: true }), and call mock.reset() in beforeEach.

Request validation

By default mockgen answers any request, which is handy while you prototype. To catch client bugs early (a missing required field, limit=500 when the max is 50, /users/abc when ids are integers), turn on request validation:

mockgen serve ./openapi.yaml --validate-requests
curl -i 'localhost:4010/tasks?limit=500'
# HTTP/1.1 400 Bad Request
# x-mock-validation: query limit: must be <= 50
  • What's checked: path, query and header parameters, and the JSON request body. Parameter text is converted to the schema's type first ("5" is the number 5, a,b is an array), and object parameters are read as filter[status]=open or as JSON. Cookies, security schemes and non-JSON bodies aren't checked.
  • What invalid requests get: the route's own 400 or 422 from the spec, if it documents one, so clients see the API's real error shape. Otherwise a 400 (parameters) or 422 (body) lists every problem: { "errors": [{ "in": "body", "path": "/title", "message": "must be string" }] }. Either way, the X-Mock-Validation header summarizes them.
  • OpenAPI rules: readOnly fields (an id, a createdAt) never have to be sent. oneOf counts as "at least one branch", because many real specs have overlapping branches, and a mock shouldn't reject a client over that.
  • X-Mock-Status skips validation, so you can still force any response.
  • Turn it on in mock.config.ts with validateRequests: true, or in code with createMockServer({ spec, validateRequests: true }).

Some real specs contradict themselves, for example a type: string parameter with enum: [true, false]. No request can satisfy those, so validation rejects them. Leave validation off for such specs, or fix the parameter.

Config file (mock.config.ts)

Generated data covers most cases. When a route needs something specific, like a fixed body, a forced field, or an error to build against, put it in mock.config.ts next to where you run mockgen:

import type { MockConfig } from '@wylan24/mockgen';

export default {
  // Defaults for the command-line options. Flags still win.
  seed: 1,
  records: 20,
  stateful: true,

  routes: {
    // Force fields; list items that mirror this route get them too.
    'GET /users/{id}': { merge: { role: 'admin', plan: { tier: 'pro' } } },
    // A fixed body…
    'GET /health': { body: { status: 'ok' } },
    // …or one computed from the request.
    'GET /search': { body: ({ query }) => ({ results: [], query: query.get('q') }) },
    // Always fail this route, slowly, while you build the error state.
    'POST /checkout': { status: 402, delay: 800, headers: { 'retry-after': '30' } },
  },
} satisfies MockConfig;
  • Route keys are METHOD /path exactly as in the spec. A key that matches no route stops mockgen with the list of real routes, so typos don't go unnoticed.
  • Each route takes status (serves the spec's response for that status, unless body is set), body (a value, or a function of { method, path, params, query, body, seed }), merge (deep-merged into the generated body), headers and delay.
  • A fixed body is checked against the spec. serve warns if it doesn't match, and validate fails.
  • Per-request headers still win. X-Mock-Status and X-Mock-Delay on a request override the config for that request.
  • Formats. mockgen looks for mock.config.ts, .mts, .js, .mjs or .json in the current folder, or takes --config <file>. TypeScript needs no build step: Node 22.18+ runs it directly. import type is erased, so the config works with npx even when mockgen isn't installed in the project.
  • Hot reload. Edits to the config are picked up like edits to the spec. A broken config keeps the previous version running.
  • Without a config file. The same overrides work in code: createMockServer({ spec, overrides: { 'GET /health': { body: { status: 'ok' } } } }).

In tests

import { createMockServer } from '@wylan24/mockgen';

const mock = await createMockServer({ spec: './openapi.yaml', seed: 1, locale: 'en' });
const url = await mock.listen(0); // random free port
// ... run tests against url ...
await mock.close();

Supported input

OpenAPI specs

  • OpenAPI 3.0 and 3.1, YAML or JSON, with local and multi-file $refs (circular refs are fine).
  • Swagger 2.0 is not supported; convert it with swagger2openapi first.

A folder of sample responses

No spec yet? Drop real responses into a folder, named after their route. mockgen infers a schema from them and generates fresh data in the same shape.

| File | Route | | --- | --- | | GET.users.json | GET /users → 200 | | GET.users.[id].json or users/GET.[id].json | GET /users/{id} (folders are path segments; {id} works too) | | GET.users.[id].404.json | the 404 response, served with X-Mock-Status: 404 | | GET.users.[id]~alice.json | another sample for the same response | | POST.users.json | POST /users → 201 | | DELETE.users.[id].json (empty file) | DELETE /users/{id} → 204, no body |

Every sample for a route is merged: keys missing from some samples become optional, null values make a field nullable, ISO dates, emails, URLs and UUIDs are detected, and a few short values repeated often (role: admin | member | viewer) become an enum. See examples/samples.

When you're ready for a real spec, mockgen infer ./samples -o openapi.yaml writes the inferred schema out so you can edit it.

Roadmap to 1.0

  • [x] OpenAPI 3.0/3.1 loader with multi-file $refs
  • [x] Deterministic, field-name-aware data generation honoring schema constraints
  • [x] Mock server: CORS, request log, status/latency simulation, hot reload
  • [x] Sample-response input (folder of JSON files → inferred schema) and mockgen infer
  • [x] List/detail consistency (/users/{id} returns the user from /users) and pagination
  • [x] Spec corpus of 50+ real-world APIs in CI: every spec loads, and every generated response validates apart from documented spec bugs
  • [x] Docker image for amd64 and arm64
  • [x] Stateful CRUD (--stateful)
  • [x] mock.config.ts: option defaults and per-route overrides

Quality: the spec corpus

mockgen is tested against 57 real-world OpenAPI specs (Stripe, GitHub, Twilio, Box, Jira, DocuSign, Plaid, Petstore variants and more from APIs.guru), pinned to commits in corpus/specs.json. Every spec must load, and every generated response is validated against its schema with Ajv.

npm run corpus:fetch        # download the specs once (~60 MB, cached in corpus/.cache)
npm run corpus              # load + generate + validate everything
npm run corpus -- stripe    # just one spec
npm run corpus:explain -- linode "GET /linode/instances" 200   # why a response fails

Validation follows OpenAPI semantics: 3.0 nullable, boolean exclusive bounds, writeOnly fields absent from responses, and discriminator choosing the oneOf branch.

Every spec's GET routes must also serve in under 20 ms at p95.

Some real specs contain schemas no value can satisfy (the same schema twice in a oneOf, allOf: [string, null], contradictory enums). corpus/baseline.json lists each one with the reason. CI runs npm run corpus -- --strict, which fails if any spec gets worse than its baseline or any failure isn't a documented spec bug.

Development

Requires Node 22.19+.

npm install
npm test
npm run serve:example     # builds, then serves examples/petstore.yaml
npm run smoke             # pack, install into an empty project, run the CLI and library

Snapshot tests in test/snapshot.test.ts pin generated output byte for byte, and CI runs them on macOS, Linux and Windows. If you change generation on purpose, review the diff and update with npx vitest run -u.

Releasing

Bump version in package.json, commit, then push a matching tag:

git tag v0.1.0-alpha.1 && git push origin v0.1.0-alpha.1

The release workflow reruns the tests, smoke test and strict corpus gate, publishes to npm with provenance, and creates the GitHub release. Pre-releases go under the next dist-tag, and also under latest until a stable version exists. To point a dist-tag at a published version later (for example, to roll latest back), run the workflow manually from the Actions tab. It publishes through npm trusted publishing, so no npm token is stored anywhere. The workflow file is registered with npm by name, so don't rename it.

Contributing

Bug reports, specs that mockgen gets wrong, and pull requests are all welcome. See CONTRIBUTING.md to get set up, and the Code of Conduct. Ask questions in Discussions. Report security problems privately, as described in SECURITY.md.

See CHANGELOG.md for what changed in each release.

License

MIT