You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OpenAPI 3中为字典结构设置自定义示例键名?

解决OpenAPI 3中自定义字典键示例的方法

要让Swagger生成的示例里data字段使用自定义的产品ID作为键,无需修改additionalProperties的核心定义,直接在data属性上添加example字段即可,具体操作如下:

修改后的ApiResponse Schema定义

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'
          # 新增自定义示例,指定目标产品ID作为键
          example:
            "d8467030-e737-11ed-a05b-0242ac120003":
              productDetails:
                name: "Sample prod name"
                currency: "USD"
            # 可按需添加更多自定义键示例
            "f9c21a80-e737-11ed-a05b-0242ac120004":
              productDetails:
                name: "Another product"
                currency: "EUR"
    ProductData:
      type: object
      properties:
        productDetails:
          $ref: '#/components/schemas/ProductDetails'
    ProductDetails:
      type: object
      properties:
        name:
          type: string
          example: "Sample prod name"
        currency:
          type: string
          example: "USD"

原理说明

  • OpenAPI 3允许在对象属性上直接定义example,其优先级高于additionalProperties自动生成的默认示例。
  • 该方法无需改动ProductData或ProductDetails的底层Schema,仅需在data字段上显式声明符合字典结构的示例对象,Swagger UI/Editor就会使用你指定的自定义键展示示例,替代默认的additionalProp1类命名。

修改完成后,生成的API响应示例将完全匹配你期望的格式,使用自定义产品ID作为data的键。

内容的提问来源于stack exchange,提问作者albin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 02:42:41