【问题标题】:Swagger Validator complaining about seemingly well-formed requestSwagger Validator 抱怨看似格式正确的请求
【发布时间】:2018-09-05 11:24:45
【问题描述】:

我正在使用swagger-express-validator 来验证小型 API 服务器的输入(使用 Swagger 2 格式)

我的path定义如下

/api/v1/users:
  post:
    produces:
      - "application/json"
    parameters:
      - in: body
        name: ids
        description: Array of user ids to be processed
        required: true
        schema:
          $ref: "#/definitions/ArrayOfIds"
    responses:
      200:
        description: success

ArrayOfIds定义如下

Id:
  type: string
ArrayOfIds:
  type: array
  items:
    $ref: "#/definitions/Id"

向服务器发送post请求如下:

POST /api/v1/users HTTP/1.1
Content-Type: application/json
Accept: application/json
Host: localhost:3000
Connection: close
User-Agent: Paw/3.1.7 (Macintosh; OS X/10.13.6) GCDHTTPRequest
Content-Length: 35

{
  "ids": ["abcd12345"]
}

导致错误

Request Invalid: POST /api/v1/users
 [ { keyword: 'type',
    dataPath: '',
    schemaPath: '#/type',
    params: { type: 'array' },
    message: 'should be array' } ]

但是,我可以在我的 Express 路由控制器代码中访问 req.body.ids,它包含正确的值 ['1234abc']

您知道验证者为何抱怨该请求吗?我觉得很好。

【问题讨论】:

标签: rest validation express swagger swagger-2.0


【解决方案1】:

您的请求正文与定义不符。根据定义,请求体中的数组必须解包:

POST /api/v1/users HTTP/1.1
Content-Type: application/json
...

["abcd12345"]

如果需要将数组包装到ids wrapper 属性中,则请求正文应定义为type: object,其中包含该数组的属性ids

    parameters:
      - in: body
        name: ids
        description: Array of user ids to be processed
        required: true
        schema:
          type: object
          properties:
            ids:
              $ref: "#/definitions/ArrayOfIds"

【讨论】:

  • 有趣。所以namebody 参数的情况下被忽略/冗余。谢谢,所以我将代码更改为直接从body 中提取数组,而不是更改swagger defn。
猜你喜欢
  • 1970-01-01
  • 2018-07-28
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 2017-04-05
  • 2013-02-05
  • 2015-01-14
  • 2018-06-13
相关资源
最近更新 更多