如何在OpenAPI 3.0中复用Resources模式实现对象列表的鉴别映射
解决方案:复用OpenAPI Schema实现类型化列表响应
要实现复用Resources、Cat和Dog schema,同时为/cats端点定义仅包含猫咪的列表响应,无需创建冗余的CatList/DogList类型,可按以下方式调整架构:
1. 完善通用容器与鉴别器映射
首先修正Resources schema,为鉴别器添加类型映射,并让单个对象类型(Cat/Dog)继承基础的objectType结构,避免重复定义:
components: schemas: Resources: type: object properties: resources: type: array items: # 定义鉴别器的基础结构,要求必须包含objectType字段 type: object required: [objectType] properties: objectType: type: string # 配置鉴别器,关联objectType值与对应schema discriminator: propertyName: objectType mapping: Cat: '#/components/schemas/Cat' Dog: '#/components/schemas/Dog' Cat: type: object allOf: # 继承基础的objectType结构 - $ref: '#/components/schemas/Resources/resources/items' - properties: objectType: type: string default: "Cat" example: "Cat" # 添加Cat专属属性 name: type: string age: type: integer Dog: type: object allOf: - $ref: '#/components/schemas/Resources/resources/items' - properties: objectType: type: string default: "Dog" example: "Dog" # 添加Dog专属属性 breed: type: string
2. 在端点响应中限定列表项类型
在/cats的200响应中,通过allOf组合Resources容器与类型限定规则,明确指定列表中的项为Cat类型:
paths: /cats: get: responses: "200": description: "获取所有猫咪" content: application/json: schema: allOf: # 复用通用的Resources容器结构 - $ref: '#/components/schemas/Resources' # 覆盖resources.items的定义,限定为Cat类型 - type: object properties: resources: type: array items: $ref: '#/components/schemas/Cat'
方案优势
- 无冗余类型:无需为每个对象类型创建单独的列表schema,完全复用现有
Resources、Cat、Dog定义 - 类型安全:明确限定
/cats返回的列表仅包含Cat对象,同时保留鉴别器的类型识别能力 - 结构清晰:单个对象(
Cat/Dog)与列表容器(Resources)职责分离,符合API响应的层级结构
内容的提问来源于stack exchange,提问作者AAA
相关产品推荐
相关产品推荐

