openapi-sampler

repository·main·Indexed 42 days ago

https://github.com/redocly/openapi-sampler

A tool for generating deterministic sample payloads based on OpenAPI or JSON Schema Draft 7 definitions. It supports compound keywords (allOf, oneOf, anyOf), schema constraints, and various string formats. Version 1.7.6 provides the OpenAPISampler.sample() method to produce realistic data in JSON or XML formats, with options to skip readOnly, writeOnly, or non-required properties.

Tokens
2K
Snippets
8
Records
15
Agent score
52%

What's inside openapi-sampler

  1. Features of openapi-sampler

    main

    The openapi-sampler tool provides several advanced features for generating deterministic OpenAPI samples:

    • Deterministic Output: Given the same input, it always produces the same output.
    • Compound Keyword Support: Supports allOf, oneOf, anyOf, and if/then/else.
    • Property Handling: Supports additionalProperties with the x-additionalPropertiesName extension.
    • Value Prioritization: Uses const, examples, enum, and default in that specific order of precedence.
    • Array Support: Supports contains, minItems, maxItems, and tuples (using items as an array).
    • Constraint Support: Supports minLength, maxLength, min, max, exclusiveMinimum, exclusiveMaximum, and pattern (regex).
    • String Formats: Supports a wide range of formats including email, password, date-time, ipv4, uuid, uri, and more.
    • Schema Resolution: Supports $ref resolving when the full specification is provided.
  2. Example: Sampling with property filtering

    main

    This example demonstrates how to use OpenAPISampler.sample with an options object to skip readOnly properties during generation.

    const OpenAPISampler = require('.');
    OpenAPISampler.sample({
      type: 'object',
      properties: {
        a: {type: 'integer', minimum: 10},
        b: {type: 'string', format: 'password', minLength: 10},
        c: {type: 'boolean', readOnly: true}
      }
    }, {skipReadOnly: true});
    // Output: { a: 10, b: 'pa$$word_q' }
  3. Generate samples with OpenAPISampler.sample()

    main

    Use the OpenAPISampler.sample(schema, [options], [spec]) method to generate a sample payload based on an OpenAPI Schema Object or a JSON Schema Draft 7 document.

    Parameters

    • schema (required): An object representing the OpenAPI Schema Object or JSON Schema Draft 7 document.
    • options (optional): An object to configure sampling behavior.
    • spec (optional): The full specification object. This is required if your schema contains $ref pointers. Note that spec must not contain any external references.

    Options

    • skipNonRequired (boolean): If true, the sampler will not include object properties that are not listed in the schema's required array.
    • skipReadOnly (boolean): If true, readOnly properties will be omitted from the generated sample.
    • skipWriteOnly (boolean): If true, writeOnly properties will be omitted from the generated sample.
    • quiet (boolean): If true, prevents the sampler from logging warning messages to the console.
    const OpenAPISampler = require('openapi-sampler');
    
    const sample = OpenAPISampler.sample(
      { type: 'object', properties: { id: { type: 'string' } } }, // schema
      { skipReadOnly: true },                                   // options
      { components: { schemas: { ... } } }                     // spec
    );
  4. Register custom samplers with _registerSampler()

    main

    You can extend the sampler's capabilities by registering custom sampler functions for specific OpenAPI types using _registerSampler(type, sampler).

    • type: The string name of the type to register (e.g., 'string', 'integer').
    • sampler: A function responsible for generating the sample value for that type.

    Note that the library comes with built-in samplers for array, boolean, integer, number, object, and string.

    import { _registerSampler } from 'openapi-sampler';
    
    const myCustomStringSampler = (schema, options, spec) => {
      return 'custom-value';
    };
    
    _registerSampler('string', myCustomStringSampler);
  5. Use the sample() function to generate data from an OpenAPI schema

    main

    The sample() function takes an OpenAPI/JSON Schema and generates a sample object based on that schema. It accepts three arguments:

    1. schema: A JSONSchema7 object representing the schema to sample from.
    2. options (optional): An Options object to configure the sampling behavior.
    3. document (optional): An object representing the full OpenAPI document, which can be used to resolve references.

    Returns: unknown (the generated sample object).

    import { sample } from 'openapi-sampler';
    
    const schema = { type: 'object', properties: { name: { type: 'string' } } };
    const result = sample(schema);
  6. Use the openapi-sampler public API

    main

    The openapi-sampler package provides specialized sampling functions for different OpenAPI data types. You can import these functions to generate sample data that conforms to specific types (arrays, booleans, numbers, objects, and strings).

    import { 
      sampleArray, 
      sampleBoolean, 
      sampleNumber, 
      sampleObject, 
      sampleString 
    } from 'openapi-sampler';
  7. Generate OpenAPI samples with sample()

    main

    The sample function generates a sample data object based on an OpenAPI schema. It accepts a schema, an optional configuration object, and the full OpenAPI specification.

    By default, it uses the following settings:

    • skipReadOnly: false
    • maxSampleDepth: 15

    If the options.format is set to 'xml', the function will return an XML string instead of a JSON object. The XML generation uses the schema.xml.name property to determine the root element name, defaulting to 'root' if not provided.

    import { sample } from 'openapi-sampler';
    
    const schema = { type: 'string', example: 'hello' };
    const result = sample(schema, { format: 'json' });
  8. Configure sampling behavior with Options

    main

    The Options object allows you to fine-tune how the sample() function generates data. Use these keys to control which schema properties are included or how the output is formatted:

    • skipNonRequired: If true, properties that are not marked as required in the schema will be omitted from the sample.
    • skipReadOnly: If true, properties marked as readOnly: true will be omitted.
    • skipWriteOnly: If true, properties marked as writeOnly: true will be omitted.
    • quiet: If true, suppresses output/logging (if applicable).
    • enablePatterns: If true, enables the use of regex patterns for generating string values.
    • format: Specifies the output format. Supported values are 'json' or 'xml'.
    const options: Options = {
      skipNonRequired: true,
      skipReadOnly: true,
      skipWriteOnly: true,
      quiet: false,
      enablePatterns: true,
      format: 'json' // or 'xml'
    };