openapiswagger-ui

Swagger UI and OpenAPI 3 - Switch request body examples by example $ref


I have 2 schemas with an example. I want to change the request body with the dropdown.

Actually everything is working. I have the list with examples displayed and the values in RequestBody change only if I write them as "value". If I specify examples as ref, the first example is loaded, but the second example is not shown when the value in the dropdown list changes.

Is this just not implemented, is this a bug or have I done something/configured something wrong?

Screenshot: enter image description here

And Config examples:

"requestBody": {
  "content": {
    "application/json": {
      "schema": {
        "oneOf": [
          {"$ref": "#/components/schemas/reportexample1"},
          {"$ref": "#/components/schemas/reportexample2"}
        ]
      },
      "examples": {
        "reportexample1": {
          "summary": "reportexample1",
          "$ref": "#/components/schemas/reportexample1"
        },
        "reportexample2": {
          "summary": "reportexample2",
          "$ref": "#/components/schemas/reportexample2"
        }
      }
    }
  }
},

......

  "components": {
    "schemas": {
      "reportexample1": {
        "type": "object",
        "properties": { .... }
      },
      "reportexample2": {
        "type": "object",
        "properties": { .... }
      }
    }
  }

Solution

  • To use $ref in examples, the references examples must be defined in the components/examples section and use the Example Object syntax.

    examples cannot reference schemas (#/components/schemas/...) - this is why your original snippet does not work.

    Try this:

          "examples": {
            "reportexample1": {
              "$ref": "#/components/examples/reportexample1"
            },
            "reportexample2": {
              "$ref": "#/components/examples/reportexample2"
            }
          }
          ...
    
      "components": {
        "examples": {
          "reportexample1": {
            "summary": "Example of reportexample1",
            "value": {
              "prop1": "value1",
              "prop2": 123
            }
          },
          "reportexample2": {
            "summary": "Example of reportexample2",
            "value": {
              "prop3": true,
              "prop4": [5, 6, 7]
            }
          }
        }
      }
    

    The inline example approach suggested in Artur May's answer will also work.