Tool for generation samples based on OpenAPI payload/response schema
npx @tessl/cli install tessl/npm-openapi-sampler@1.6.0OpenAPI Sampler is a tool for generating sample data based on OpenAPI payload and response schemas. It provides deterministic sample generation with comprehensive support for JSON Schema features including compound keywords (allOf, oneOf, anyOf, if/then/else), additionalProperties, array operations, string validation, number constraints, and various string formats. The library prioritizes using const, examples, enum, and default values where available, supports $ref resolving for complex schemas, and includes basic JSON Schema draft 7 compatibility.
npm install openapi-samplerES Modules:
import { sample, inferType, _registerSampler } from "openapi-sampler";CommonJS:
const { sample, inferType, _registerSampler } = require("openapi-sampler");import { sample } from "openapi-sampler";
// Simple schema sampling
const schema = {
type: "object",
properties: {
name: { type: "string", minLength: 5 },
age: { type: "integer", minimum: 18 },
email: { type: "string", format: "email" }
},
required: ["name", "age"]
};
const sampleData = sample(schema);
// Result: { name: "string", age: 18, email: "user@example.com" }
// With options
const options = {
skipNonRequired: true,
format: "json"
};
const sampleDataMinimal = sample(schema, options);
// Result: { name: "string", age: 18 }
// With $ref resolution
const spec = {
components: {
schemas: {
User: {
type: "object",
properties: {
id: { type: "string", format: "uuid" },
profile: { $ref: "#/components/schemas/Profile" }
}
},
Profile: {
type: "object",
properties: {
name: { type: "string" },
bio: { type: "string", maxLength: 100 }
}
}
}
}
};
const userSchema = { $ref: "#/components/schemas/User" };
const userData = sample(userSchema, {}, spec);Main function for generating sample data from JSON Schema or OpenAPI schemas.
/**
* Generate sample data from a JSON Schema
* @param schema - JSON Schema object to generate sample from
* @param options - Optional configuration options
* @param document - Optional full OpenAPI specification for $ref resolution
* @returns Generated sample data (object, array, or primitive)
*/
function sample(schema: JSONSchema7, options?: Options, document?: object): unknown;
/**
* Register a custom sampler for a specific type
* @param type - The JSON Schema type to register a sampler for
* @param sampler - The sampler function to use for this type
*/
function _registerSampler(type: string, sampler: Function): void;
interface Options {
readonly skipNonRequired?: boolean; // Don't include non-required object properties not specified in required array
readonly skipReadOnly?: boolean; // Don't include readOnly object properties
readonly skipWriteOnly?: boolean; // Don't include writeOnly object properties
readonly quiet?: boolean; // Don't log console warning messages
readonly enablePatterns?: boolean; // Enable regex pattern sampling for strings
readonly format?: 'json' | 'xml'; // Output format (defaults to 'json')
}
type JSONSchema7 = import('@types/json-schema').JSONSchema7;Key Features:
Usage Examples:
// Array schema
const arraySchema = {
type: "array",
items: { type: "string", format: "email" },
minItems: 2,
maxItems: 3
};
const emails = sample(arraySchema);
// Result: ["user@example.com", "user@example.com"]
// AllOf composition
const compositeSchema = {
allOf: [
{ type: "object", properties: { name: { type: "string" } } },
{ type: "object", properties: { age: { type: "integer" } } }
]
};
const person = sample(compositeSchema);
// Result: { name: "string", age: 0 }
// XML format
const xmlSchema = {
type: "object",
properties: {
name: { type: "string" },
items: {
type: "array",
items: { type: "string" },
xml: { wrapped: true }
}
},
xml: { name: "root" }
};
const xmlData = sample(xmlSchema, { format: "xml" });
// Result: XML string with proper element structureUtility function for inferring JSON Schema types from schema objects.
/**
* Infer the type of a schema based on its properties and keywords
* @param schema - JSON Schema object to analyze
* @returns Inferred type (object, array, string, number, integer, boolean) or null
*/
function inferType(schema: object): string | null;Usage Examples:
import { inferType } from "openapi-sampler";
// Explicit type
inferType({ type: "string" }); // "string"
// Inferred from keywords
inferType({ properties: {} }); // "object"
inferType({ items: {} }); // "array"
inferType({ minLength: 5 }); // "string"
inferType({ minimum: 0 }); // "number"
// Array type (takes first)
inferType({ type: ["string", "null"] }); // "string"
// No inference possible
inferType({ description: "Some value" }); // nullRegister custom sampling functions for specific JSON Schema types.
/**
* Register a custom sampler for a specific type
* @param type - The JSON Schema type to register a sampler for ('string', 'number', 'object', etc.)
* @param sampler - The sampler function that generates values for this type
*/
function _registerSampler(type: string, sampler: Function): void;Usage Examples:
import { _registerSampler } from "openapi-sampler";
// Register a custom string sampler
_registerSampler('string', (schema, options, spec, context) => {
if (schema.format === 'custom-id') {
return 'CUSTOM_' + Math.random().toString(36).substr(2, 9);
}
// Fallback to default behavior
return 'string';
});
// Now schemas with format: 'custom-id' will use the custom sampler
const result = sample({
type: 'string',
format: 'custom-id'
});
// Result: "CUSTOM_abc123def"OpenAPI Sampler supports extensive string format validation and sample generation:
email: Generates user@example.comidn-email: Generates internationalized email пошта@укр.нетpassword: Generates pa$$word (extended to meet minLength)date-time: Generates RFC 3339 datetime 2019-08-24T14:15:22.123Zdate: Generates date portion 2019-08-24time: Generates time portion 14:15:22.123Zipv4: Generates 192.168.0.1ipv6: Generates 2001:0db8:85a3:0000:0000:8a2e:0370:7334hostname: Generates example.comidn-hostname: Generates internationalized hostname приклад.укрuri: Generates http://example.comuri-reference: Generates ../dictionaryuri-template: Generates http://example.com/{endpoint}iri: Generates http://example.com/entity/1iri-reference: Generates /entity/1uuid: Generates deterministic UUID based on property namejson-pointer: Generates /json/pointerrelative-json-pointer: Generates 1/relative/json/pointerregex: Generates /regex/minimum / maximum: Numeric boundsexclusiveMinimum / exclusiveMaximum: Exclusive boundsmultipleOf: Generates multiples of specified valueformat: Number formats
float: Generates 0.1 instead of 0double: Generates 0.1 instead of 0items: Schema for array items (single schema or tuple)prefixItems: Tuple validation for positional itemscontains: Schema that at least one item must matchminItems / maxItems: Array length constraintsuniqueItems: Uniqueness constraint (informational)properties: Object property definitionsrequired: Required property namesadditionalProperties: Schema for additional propertiesminProperties / maxProperties: Property count constraintspatternProperties: Property name pattern matchingallOf: Merge all schemas (deep merge for objects)oneOf: Use first schema (with parent property inheritance)anyOf: Use first schema (with parent property inheritance)if / then / else: Conditional schema application$ref: JSON Pointer references within provided specificationWhen format: "xml" option is used:
xml.name: Element name overridexml.prefix: Namespace prefixxml.namespace: XML namespacexml.attribute: Render as XML attributexml.wrapped: Wrap arrays in container elementThe library handles various error conditions gracefully:
{} for object types, empty array [] for array types, undefined for other types)quiet: true option is setExample Error Handling:
try {
// This will throw an error because $ref is used without spec
const result = sample({ $ref: "#/components/schemas/User" });
} catch (error) {
console.error(error.message);
// "Your schema contains $ref. You must provide full specification in the third parameter."
}
// Circular reference handling
const circularSchema = {
type: 'object',
properties: {
self: { $ref: '#' } // Self-reference
}
};
const spec = { ...circularSchema };
const result = sample(circularSchema, {}, spec);
// Result: { self: {} } - circular reference resolved to empty object