用于值验证的远程枚举列表-在OpenAPI规范中

时间:2018-12-07 15:02:55

标签: swagger api-design openapi

我正在尝试在OpenAPI 3.0.2规范中定义架构。 我希望其中一个属性可以针对值列表进行验证。

通常,我可以使用枚举来实现。

components:
  schemas:
    catalog:
      title: title here
      description: describing it here
      properties:
        catalogitemid:
          description: catalog identifier
          type: string
          enum: 
            - item1347
            - item9081
            - item5720
        catalogitemname:
          description: catalog item name
          type: string
      required:
        - catalogitemid
        - catalogitemname
      additionalProperties: false

但是我希望此枚举列表改为远程YAML / JSON。

原因:该列表需要定期更新(2000多个值)。而且我想避免这种情况会导致更新此API。

以下$ ref方法失败:

components:
  schemas:
    catalog:
      title: title here
      description: describing it here
      properties:
        catalogitemid:
          description: catalog identifier
          type: string
          enum:
            $ref: 'https://remote/path/to/catalog/list.yaml#/components/schemas/catalogitemid/enum'
        catalogitemname:
          description: catalog item name
          type: string
      required:
        - catalogitemid
        - catalogitemname
      additionalProperties: false

错误:

catalog行的原因

should have required property '$ref'

missingProperty: $ref

should match exactly one schema in oneOf

enum行的原因

should be array

该怎么做?

1 个答案:

答案 0 :(得分:1)

“香草” OpenAPI

OpenAPI规范仅在特定上下文中允许$ref,而不是在所有地方。不可能仅$ref值列表来enum,但是您可以$ref整个属性模式:

      properties:
        catalogitemid:
          $ref: 'https://remote/path/to/catalog/list.yaml#/components/schemas/catalogitemid'

以上假设list.yaml文件包含:

components:
  schemas:
    catalogitemid:
      description: catalog identifier
      type: string
      enum: 
        - item1347
        - item9081
        - item5720
        ...

使用预处理器

也就是说,有json-refsopenapi-preprocessor之类的工具可以在文档的任何位置解析JSON引用和JSON指针。您可以使用它们对问题的原始规范进行预处理,从而生成有效的解析OpenAPI定义,然后将其与兼容OpenAPI的工具一起使用。