@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
Maintainers
Readme
mockgen
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.yamlOr add it to a project, for scripts and tests:
npm install --save-dev @wylan24/mockgen
npx mockgen serve ./openapi.yamlDocker
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/mockgenAny 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 2Platforms. Images are published for
linux/amd64andlinux/arm64(Apple silicon, Graviton), tagged by version (0.1.0-alpha.9), withlatestandnextmatching 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
nodeuser. 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
- Getting started: from a spec to a running mock in five minutes
- No spec yet? Start from sample responses
- Building loading, error and empty states
- Testing with mockgen: unit, integration and Playwright tests
- mockgen in CI: validate specs on every pull request, and run end-to-end tests against the mock
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,cityall 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/42always returns the same user, withid: 42. - Valid. Responses honor
enum,min/max,pattern,minLength,minItems,uniqueItems,oneOf/anyOf/allOf, nullable, and use your spec'sexamplevalues 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 downOther 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 deThe 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, andnullon the last page). - Responses carry
X-Total-Countand aLinkheader withnext/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 --statefulcurl -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(ormock.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-Statusstill 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-requestscurl -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,bis an array), and object parameters are read asfilter[status]=openor 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, theX-Mock-Validationheader summarizes them. - OpenAPI rules:
readOnlyfields (anid, acreatedAt) never have to be sent.oneOfcounts as "at least one branch", because many real specs have overlapping branches, and a mock shouldn't reject a client over that. X-Mock-Statusskips validation, so you can still force any response.- Turn it on in
mock.config.tswithvalidateRequests: true, or in code withcreateMockServer({ 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 /pathexactly 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, unlessbodyis set),body(a value, or a function of{ method, path, params, query, body, seed }),merge(deep-merged into the generated body),headersanddelay. - A fixed
bodyis checked against the spec.servewarns if it doesn't match, andvalidatefails. - Per-request headers still win.
X-Mock-StatusandX-Mock-Delayon a request override the config for that request. - Formats. mockgen looks for
mock.config.ts,.mts,.js,.mjsor.jsonin the current folder, or takes--config <file>. TypeScript needs no build step: Node 22.18+ runs it directly.import typeis erased, so the config works withnpxeven 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 failsValidation 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 librarySnapshot 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.1The 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.
