Swagger Validator抱怨看似格式正确的请求

时间:2018-09-05 11:24:46

标签: rest validation express swagger swagger-2.0

我正在使用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 /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']

您对验证器为何抱怨该请求有任何想法吗?对我来说很好。

1 个答案:

答案 0 :(得分:2)

您的请求正文与定义不匹配。根据定义,必须解开请求正文中的数组:

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

["abcd12345"]

如果需要将数组包装到ids包装器属性中,则请求正文应定义为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"