or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-openapi-sampler

Tool for generation samples based on OpenAPI payload/response schema

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/openapi-sampler@1.6.x

To install, run

npx @tessl/cli install tessl/npm-openapi-sampler@1.6.0

index.mddocs/

OpenAPI Sampler

OpenAPI 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.

Package Information

  • Package Name: openapi-sampler
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install openapi-sampler

Core Imports

ES Modules:

import { sample, inferType, _registerSampler } from "openapi-sampler";

CommonJS:

const { sample, inferType, _registerSampler } = require("openapi-sampler");

Basic Usage

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);

Capabilities

Sample Generation

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:

  • Supports all JSON Schema types (object, array, string, number, integer, boolean)
  • Handles compound schemas (allOf, oneOf, anyOf, if/then/else)
  • Resolves $ref references when full spec is provided
  • Prioritizes explicit values (const, examples, enum, default)
  • Generates deterministic output for consistent testing
  • Supports XML format output with proper element naming and attributes

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 structure

Type Inference

Utility 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" }); // null

Custom Samplers

Register 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"

Supported Schema Features

String Formats

OpenAPI Sampler supports extensive string format validation and sample generation:

  • email: Generates user@example.com
  • idn-email: Generates internationalized email пошта@укр.нет
  • password: Generates pa$$word (extended to meet minLength)
  • date-time: Generates RFC 3339 datetime 2019-08-24T14:15:22.123Z
  • date: Generates date portion 2019-08-24
  • time: Generates time portion 14:15:22.123Z
  • ipv4: Generates 192.168.0.1
  • ipv6: Generates 2001:0db8:85a3:0000:0000:8a2e:0370:7334
  • hostname: Generates example.com
  • idn-hostname: Generates internationalized hostname приклад.укр
  • uri: Generates http://example.com
  • uri-reference: Generates ../dictionary
  • uri-template: Generates http://example.com/{endpoint}
  • iri: Generates http://example.com/entity/1
  • iri-reference: Generates /entity/1
  • uuid: Generates deterministic UUID based on property name
  • json-pointer: Generates /json/pointer
  • relative-json-pointer: Generates 1/relative/json/pointer
  • regex: Generates /regex/

Number Constraints

  • minimum / maximum: Numeric bounds
  • exclusiveMinimum / exclusiveMaximum: Exclusive bounds
  • multipleOf: Generates multiples of specified value
  • format: Number formats
    • float: Generates 0.1 instead of 0
    • double: Generates 0.1 instead of 0

Array Features

  • items: Schema for array items (single schema or tuple)
  • prefixItems: Tuple validation for positional items
  • contains: Schema that at least one item must match
  • minItems / maxItems: Array length constraints
  • uniqueItems: Uniqueness constraint (informational)

Object Features

  • properties: Object property definitions
  • required: Required property names
  • additionalProperties: Schema for additional properties
  • minProperties / maxProperties: Property count constraints
  • patternProperties: Property name pattern matching

Schema Composition

  • allOf: 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

Reference Resolution

  • $ref: JSON Pointer references within provided specification
  • Circular reference detection and handling
  • Caching for performance optimization

XML Support

When format: "xml" option is used:

  • xml.name: Element name override
  • xml.prefix: Namespace prefix
  • xml.namespace: XML namespace
  • xml.attribute: Render as XML attribute
  • xml.wrapped: Wrap arrays in container element

Error Handling

The library handles various error conditions gracefully:

  • Missing $ref specification: Throws error "Your schema contains $ref. You must provide full specification in the third parameter." when $ref is used without providing full spec
  • Circular references: Automatically detects and returns appropriate empty values (empty object {} for object types, empty array [] for array types, undefined for other types)
  • Schema validation warnings: Outputs warnings for inconsistent schemas (e.g., conflicting types in allOf) unless quiet: true option is set
  • Format validation: Warns when minLength/maxLength constraints conflict with format requirements
  • Depth limiting: Prevents infinite recursion with automatic depth limiting (default maximum depth: 15 levels)
  • XML format errors: Throws error "Unknown format output for building XML." when XML conversion fails due to invalid input

Example 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