spectral:oas error on by default

oas2-valid-media-example

Examples must be valid against their defined schema.

Applies to
schema
Selects
$..responses..[?(@ && @.schema && @.examples)]
Function
oasExample
Specs
OpenAPI 2.0
Message
{{error}}

Use it

This rule ships with OpenLint in spectral:oas. Extending the ruleset turns it on:

extends: spectral:oas
rules:
  oas2-valid-media-example: error   # or off, or another severity

Definition

As defined in @openlint/openlint-rulesets. Functions show by name.

oas2-valid-media-example:
  description: Examples must be valid against their defined schema.
  message: '{{error}}'
  severity: 0
  recommended: true
  formats:
    - OpenAPI 2.0 (Swagger)
  given: '$..responses..[?(@ && @.schema && @.examples)]'
  then:
    function: oasExample
    functionOptions:
      schemaField: schema
      oasVersion: 2
      type: media

About this rule

Examples must be valid against their defined schema. Common reasons you may see errors are:

For example, if you have a Pet object with an id property as type integer, and name and petType properties as type string, the examples properties type should match the schema:

schemas:
  Pet:
    title: Pet
    type: object
    properties:
      id:
        type: integer
      name:
        type: string
      petType:
        type: string
    required:
      - id
      - name
      - petType

Good Example

paths:
  '/pet/{petId}':
    get:
      ...
      responses:
        '200':
          description: Pet Found
          schema:
            $ref: '#/definitions/Pet'
          examples:
            Get Pet Bubbles:
              id: 123
              name: 'Bubbles'
              petType: 'dog'

Bad Example

This would throw an error since petType is an integer, not a string.

paths:
  '/pet/{petId}':
    get:
      ...
      responses:
        '200':
          description: Pet Found
          schema:
            $ref: '#/definitions/Pet'
          examples:
            Get Pet Bubbles:
              id: 123
              name: 'Bubbles'
              petType: 123

Sources