【问题标题】:How to add multiple example values in swagger properties?如何在招摇属性中添加多个示例值?
【发布时间】:2017-10-05 04:56:44
【问题描述】:

我正在使用 Swagger OpenAPI 规范工具,我在以下定义之一中有一个字符串数组属性:

cities:
        type: array
        items:
          type: string
          example: "Pune"

我的 API 生成 JSON 结果,因此对于上述对象,响应中会出现以下结果:

{
  "cities": [
    "Pune"
  ]
}

尝试使用逗号分隔的字符串,如下所示:

cities:
            type: array
            items:
              type: string
              example: "Pune", "Mumbai", "Bangaluru"

预期结果为:

{
      "cities": [
        "Pune",
        "Mumbai",
        "Bangaluru"
      ]
    }

但编辑器显示错误。 “错误的缩进”

我想给示例标签赋予多个值有什么办法吗?

更新

下面的用户 Helen 给出了正确答案我有缩进问题,因此存在嵌套数组(二维数组)

正确方法:

cities:
        type: array
        items:
          type: string
        example: 
        - Pune
        - Mumbai

我的方式(这是错误的)

cities:
        type: array
        items:
          type: string
          example: 
          - Pune
          - Mumbai

在以上两种情况下寻找example标签的缩进会有所不同,它的YAML缩进很重要。

【问题讨论】:

    标签: yaml swagger openapi


    【解决方案1】:

    要显示包含多个项目的数组示例,请在数组级别而不是项目级别添加example

    cities:
      type: array
      items:
        type: string
      example:
        - Pune
        - Mumbai
        - Bangaluru
    
      # or
      # example: [Pune, Mumbai, Bangaluru]
    

    如果是对象数组,example 将如下所示:

    type: array
    items:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
    example:
      - id: 1
        name: Prashant
      - id: 2
        name: Helen
    

    【讨论】:

    • 您给出的解决方案输出 "cities": [ [ "Pune", "Mumbai" ] ] this,这是两个嵌套数组,我不希望我希望单个数组将这些名称保存为数组元素不是新数组,谢谢回复
    • 你在哪里看到嵌套数组?它在 Swagger 编辑器中运行良好:i.stack.imgur.com/uT85I.png
    • 嘿,谢谢 Helen 缩进是问题,请参阅更新的问题。
    • @Prashant 是对的,这种方法显示为数组(Swagger Editor 和 Swagger UI)。有一个examples 选项,但仍不清楚如何在components/schemas 中使用它。请参阅 viralpatel.net/openapi-multiple-examplesswagger.io/docs/specification/adding-examples
    【解决方案2】:

    对于 openapi 版本 - 3.0.0+

      major:
          type: array
          items:
            type: string
            enum:
              - Accounting
              - Business Contacts
              - Economy
              - Finance
              - Graphic Design
              - International Business Administration
              - International Relations
              - Law
              - Marketing
              - others
              - Political Science
              - Statistics
    

    【讨论】:

    • 这不是问题所在。您的答案显示了一个枚举数组,而问题是询问如何将多值数组指定为数组模式的 示例值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2017-08-16
    • 1970-01-01
    相关资源
    最近更新 更多