首页 > 解决方案 > Open API 3 - 如何描述一个整数数组但可以是单个项目的查询参数?

问题描述

使用 Open API 3.0.1,我试图描述一个“整数”类型的查询ids参数,假设我们称之为它,它可以是单独的,也可以是一个数组。

例如:

/my-endpoint?ids=111

或者

/my-endpoint?ids=111&ids=222

我确实尝试过:

- name: ids
  in: query
  required: false
  schema:
    type: array
    items:
      type: integer

我明白这一点style: form并且explode: true 是默认的

但是当我使用实际请求验证这一点时(我使用express-openapi-validate,它是Ajv的包装器),我得到了这些错误:

/my-endpoint?ids=111

"Error while validating request: request.query.ids should be array"

/my-endpoint?ids=111&ids=222&ids=333

"Error while validating request: request.query.ids[0] should be integer"

如果我使用“字符串”而不是“整数”:

- name: ids
  in: query
  required: false
  schema:
    type: array
    items:
      type: string

/my-endpoint?ids=111

"Error while validating request: request.query.ids should be array"

/my-endpoint?ids=111&ids=222&ids=333

Valid!

我应该如何描述这个ids参数,它必须是整数值?

更新:我现在明白,任何查询参数string在被 Express 服务器(我使用)反序列化时都将是 a。但我仍然无法让单个元素数组工作!

标签: swaggerjsonschemaopenapiajv

解决方案


在@Helen 发表评论后,我确实尝试了另一个验证库express-openapi-validator,现在它适用于:

- name: ids
  in: query
  required: false
  style: form
  explode: true
  schema:
    type: array
    items:
      type: integer

使用express-openapi-validate,我能够使其工作的唯一方法是使用:

- name: ids
  in: query
  required: false
  schema:
    anyOf:
      - type: array
        items:
          type: string
          pattern: '^\d+$'
      - type: string  
        pattern: '^\d+$'

所以我建议你在 Express 服务器上使用express-openapi-validator 。


推荐阅读