Skip to content

examples in schema object property are ignored when anyOf used #2726

@steciuk

Description

@steciuk

Context

When using Prism to mock a server based on an OpenAPI schema, properties defined with anyOf that include examples do not use those examples when generating mock responses in static mode.

Current Behavior

For a schema property using anyOf with examples:

properties:
  title:
    anyOf:
      - type: string
      - type: "null"
    title: Title
    examples:
      - Some kind of title

The mock response returns: {title: "string"} instead of {title: "Some kind of title"}.

This occurs because Prism uses json-schema-sampler for response generation, which prioritizes traversing anyOf schemas without checking for examples at the property level.

Expected Behavior

Mock responses should respect examples values even when the property uses anyOf. The generated response should be: {title: "Some kind of title"}.

Possible Workaround/Solution

The json-schema-sampler seems to have originated as a fork of openapi-sampler, which, when used in place of json-schema-sampler causes prism to yield expected results.

My uninformed suggestion would be to modify Prism to use openapi-sampler for response generation instead of json-schema-sampler, which, as an additional benefit, appears to be more actively maintained.

This, however, seems to have two complications:

  1. json-schema-sampler has an additional mechanism of stopping schema parsing after options.ticks number of recursive traverse calls, which is not present in openapi-sampler.
  2. openapi-sampler prioritizes examples over default, whereas json-schema-sampler does the opposite. Prioritizing examples seems more correct in my opinion (and not only mine), but this may be a breaking change for some users.

Steps to Reproduce

StackBlitz example

Environment

  • Version used: 5.14.2
  • Environment name and version: node 24.1.0
  • Operating System and version: Ubuntu 24.04.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions