Generate Sample JSON From a Schema for API Tests
If you already have the schema and need a mock API response, use a fixture generator. It takes the schema as input and returns a sample JSON value. The example generates a synthetic booking record without using any real customer data.
Worked example
Generate one synthetic booking record
import { generate } from "json-schema-faker";
const schema = {
type: "object",
properties: {
bookingId: { const: "demo-booking" },
seats: { type: "integer", minimum: 1, maximum: 4 }
},
required: ["bookingId", "seats"],
additionalProperties: false
};
console.log(JSON.stringify(await generate(schema, { seed: 27 }), null, 2));Steps
- In a Node.js project for your test fixtures, install json-schema-faker. Save the example as fixture.mjs and run node fixture.mjs.
- Use a fixed seed and keep the package version locked if a test needs the same data each time. Start with a schema that declares every field the fixture must contain as required.
- Put the generated stdout in the validator's JSON document box and the schema in its schema box. Check for zero errors before using the fixture in a test.
What to check
- The result should have bookingId set to demo-booking and seats set to an integer from 1 to 4. To run the web validator, paste the schema as strict JSON with quoted keys, which can be printed with JSON.stringify(schema).
- A generated fixture covers one valid case. Make a separate failure fixture with seats set to 0 and add explicit boundary cases if your test depends on them.