使用discriminator的oneOf时生成多组OpenAPI示例的方法
解决OpenAPI多态Schema自动生成双示例的问题
问题背景
我定义了一个带多态结构的响应Schema:
PersonResourceAbstract: type: object properties: id: description: blah type: string oneOf: - $ref: '#/components/schemas/PersonResourceSummary' - $ref: '#/components/schemas/PersonResourceDetail' discriminator: propertyName: discriminatorView mapping: summary: '#/components/schemas/PersonResourceSummary' detail: '#/components/schemas/PersonResourceDetail'
其中PersonResourceSummary和PersonResourceDetail仅细节粒度不同,希望接口返回PersonResourceAbstract时,文档生成工具能自动生成这两种类型的示例,无需手动编写,就像单个对象时自动生成带默认值的JSON示例那样。
解决方法
1. 给子Schema添加默认值(通用前提)
不管用什么文档生成工具,先给两个子类型的字段加上default属性,让工具能自动填充生成示例。示例配置如下:
PersonResourceSummary: type: object allOf: - $ref: '#/components/schemas/PersonResourceAbstract' properties: discriminatorView: type: string default: "summary" name: type: string default: "张三" age: type: integer default: 25 PersonResourceDetail: type: object allOf: - $ref: '#/components/schemas/PersonResourceAbstract' properties: discriminatorView: type: string default: "detail" name: type: string default: "张三" age: type: integer default: 25 address: type: string default: "北京市朝阳区" phone: type: string default: "13800138000"
2. Swagger UI / OpenAPI Generator 适配
- 确保你的OpenAPI文档版本为3.0+,
discriminator是3.0版本才引入的特性 - Swagger UI初始化时,配置参数确保多态模型展开:
const ui = SwaggerUIBundle({ url: "/openapi.yaml", defaultModelsExpandDepth: -1, // 展开所有模型 defaultModelExpandDepth: 2, // 展开模型层级 // 其他配置... }); - 使用OpenAPI Generator时,添加
--enable-post-process-file参数,保证生成的文档包含多态示例
3. Redoc 适配
Redoc对多态支持友好,只要discriminator配置正确且子Schema带默认值,默认会自动生成两种示例。如果需要优化展示,可添加Redoc配置:
redoc: expandDefaultServerVariables: true schemaExpansionLevel: 2
4. 通用增强方案(避免手动写示例)
如果部分工具默认不生成双示例,可在父Schema里通过$ref引用子类型的自动生成示例,无需手动编写重复内容:
PersonResourceAbstract: type: object properties: id: description: blah type: string oneOf: - $ref: '#/components/schemas/PersonResourceSummary' - $ref: '#/components/schemas/PersonResourceDetail' discriminator: propertyName: discriminatorView mapping: summary: '#/components/schemas/PersonResourceSummary' detail: '#/components/schemas/PersonResourceDetail' examples: summaryExample: $ref: '#/components/examples/PersonResourceSummaryExample' detailExample: $ref: '#/components/examples/PersonResourceDetailExample'
然后在components/examples中定义子类型示例框架,工具会自动填充默认值:
components: examples: PersonResourceSummaryExample: summary: 摘要视图示例 value: {} # 工具自动填充默认值 PersonResourceDetailExample: summary: 详情视图示例 value: {} # 工具自动填充默认值
内容的提问来源于stack exchange,提问作者dublintech
相关产品推荐
相关产品推荐

