Swagger - How to write an example for a Free-Form Object?

Viewed 580

We have a response type "Error" that may contain a field "extraInfo".

Error:
  type: object
  properties:
    code:
      type: string
    message:
      type: string
    extraInfo:
      description: any complementary information
      type: object
      // how to provide examples here?

One example for it can be :

 "extraInfo": {
    "doors": {
      "frontLeftClosed": false,
      "frontRightClosed": true,
      "rearLeftClosed": true,
      "rearRightClosed": true,
      "trunkClosed": true
    },
    "windows": {
      "frontLeftClosed": false,
      "rearLeftClosed": true,
      "trunkClosed": false
    }
  }

another could be :

"extraInfo": {
   "transactionId": "77812783001"
}

Since it s a free form object, is there a way to provide examples for it in Swagger?

Couldn't find it in the spec : https://swagger.io/docs/specification/data-models/data-types/

1 Answers

Use the example keyword and specify the example value using the YAML or JSON object syntax:

    extraInfo:
      description: any complementary information
      type: object
      example:   # <-------
        doors:
          frontLeftClosed: false
          frontRightClosed: true
          rearLeftClosed: true
          rearRightClosed: true
          trunkClosed: true
        windows:
          frontLeftClosed: false
          rearLeftClosed: true
          trunkClosed: false

OpenAPI 3.1 (which is compatible with JSON Schema 2020-12) also supports multiple examples for schemas and properties.

# openapi: 3.1.0

    extraInfo:
      description: any complementary information
      type: object
      # A list of examples
      examples:
        # Example 1
        - transactionId: '77812783001'
        # Example 2
        - doors:
            frontLeftClosed: false
            frontRightClosed: true
            rearLeftClosed: true
            rearRightClosed: true
            trunkClosed: true
          windows:
            frontLeftClosed: false
            rearLeftClosed: true
            trunkClosed: false
Related