Search code examples
swaggerswagger-uiopenapi

Add example keys when defining maps through OpenAPI 3


This is the json format I have in response:

{
    "status": "success",
    "error": null,
    "data": {
        "<product_id>": {
            "productDetails": {
                "name": "Name of product",
                "currency": "USD",
                ...
            },
            ...
        }
    }
}

While defining the product map, I've added the below in OpenAPI 3.

components:
  schemas:
    ApiResponse:
      type: object
      properties:
        status:
          type: string
          default: success
          enum:
            - success
            - failure
        error:
          type: string
          example: "Internal error"
        data:
          type: object
          additionalProperties:
            $ref: '#/components/schemas/ProductData'
    ProductData:
      type: object
      properties:
        productDetails:
          type: object
          $ref: '#/components/schemas/ProductDetails'
    ProductDetails:
      type: object
      properties:
        name:
          type: string
          example: "Sample prod name"
        currency:
          type: string
          example: "USD"

In swagger, this generates the example as below:

{
  "status": "success",
  "error": "Internal error",
  "data": {
    "additionalProp1": {
      "productDetails": {
        "name": "Sample prod name",
        "currency": "USD"
      }
    },
    "additionalProp2": {
      "productDetails": {
        "name": "Sample prod name",
        "currency": "USD"
      }
    },
    "additionalProp3": {
      "productDetails": {
        "name": "Sample prod name",
        "currency": "USD"
      }
    }
  }
}

However, I'd like to pass a custom example as the key name(say, "d8467030-e737-11ed-a05b-0242ac120003") instead of swagger populating the keys(like "additionalProp1", "additionalProp2", etc). How is this possible?

I checked the OpenAPI 3.0 documentation from swagger, but could not find a way to do this.


Solution

  • In OpenAPI v3.1 you can use the propertyNames keyword - https://json-schema.org/understanding-json-schema/reference/object.html#property-names