【问题标题】:Putting arrays inside of objects using Swagger 2.0 and YAML使用 Swagger 2.0 和 YAML 将数组放入对象中
【发布时间】:2017-01-05 15:31:19
【问题描述】:

我目前正在学习如何使用 Swagger 进行记录,因为我的公司正在评估将其用作为即将进行的项目记录的标准方式。

我在网上看到使用 YAML 比使用 JSON 更容易阅读,而且由于 YAML 是 JSON 的子集,我认为它会没问题。

我正在处理 200 代码的响应,我想表示类似于以下结构的内容:

responses:
    200:
      description: OK.
      schema:
        title: response
        type: object
        items:
          properties:
            title: user
            type: array
            items:
                id:
                  type: string
                name:
                  type: string
            status:
              type: integer

基本上,我返回一个名为“response”的对象,其中包含两个变量:一个名为“user”的数组,其中包含多个字符串(为了清楚起见,我只包括了两个)和另一个变量(在“user”数组之外)称为“状态”,包含一个整数。

上面的代码不起作用,编辑器通知我它不是“有效的响应定义”。

我不确定如何解决这个问题。对于我做错的事情,我将不胜感激。

【问题讨论】:

    标签: yaml swagger swagger-2.0


    【解决方案1】:

    基本上,我返回一个名为“response”的对象,其中包含两个变量:一个名为“user”的数组,其中包含多个字符串(为了清楚起见,我只包括了两个)和另一个变量(在“user”数组之外)称为“状态”,包含一个整数。

    根据您的描述,响应应该如下(假设响应是 JSON)。基本上,您有一个带有嵌套对象的对象:

    {
      "user": {
        "id": "12345",
        "name": "Alice"
      },
      "status": 0
    }
    

    这个响应可以定义如下:

          responses:
            200:
              description: OK.
              schema:
                title: response
                type: object
                required: [user, status]
                properties:
                  user:
                    type: object
                    required: [id, name]
                    properties:
                      id:
                        type: string
                      name:
                        type: string
                  status:
                    type: integer
    

    为方便起见,可以将具有嵌套对象的复杂模式分解为单独的对象模式。模式可以写在全局definitions 部分,并通过$ref 从其他地方引用。例如,通过这种方式,您可以在多个操作/响应中重用相同的架构。

          responses:
            200:
              description: OK.
              schema:
                $ref: "#/definitions/ResponseModel"
    
    definitions:
      ResponseModel:
        title: response
        type: object
        properties:
          user:
            $ref: "#/definitions/User"
          status:
            type: integer
        required:
          - user
          - status
    
      User:
        type: object
        properties:
          id:
            type: string
          name:
            type: string
        required:
          - id
          - name
    

    【讨论】:

    • 感谢您的回答!我尝试了您建议的方式,但仍然收到 not a valid response 错误。我不明白的是,如何在字符串数组中定义键值对?我一直在使用items: {nameofkey}: type: string,但仍然出现缩进错误
    • @RolaTarola: 1) 确保您的缩进是正确的,并且responses 部分在您的操作定义下正确缩进。
    • 2) 那么users 是关联数组/字典,而不是常规字符串数组?它是否有任何固定/必需的键或所有键都是任意的?
    • 密钥总是相同的。在我的 OP 中,为了清楚起见,我只详细说明了两个键(idname),但它们将始终是固定的。
    • 成功了!谢谢!不过,使用 YAML 时确实很难确定缩进。
    猜你喜欢
    • 2020-10-09
    • 2017-03-20
    • 2019-10-02
    • 2021-06-15
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多