首页 > 解决方案 > 用于值验证的远程枚举列表 - 在 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

这样做的方法是什么?

标签: swaggerapi-designopenapi

解决方案


“香草”OpenAPI

OpenAPI 规范只允许$ref在某些情况下,而不是在任何地方。不可能$refenum列出值列表,但您可以$ref使用整个属性模式:

# This won't work
enum:
  $ref: 'https://...'

# This will work
properties:
  catalogitemid:
    $ref: 'https://remote/path/to/enums/catalog-list.yaml'

上面的示例假设list.yaml文件包含:

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

使用预处理器

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


推荐阅读