如何用Swagger规范文档化带字符串化JSON的API响应?
可行实现方案说明
你的核心问题在于event_data是字符串化的JSON,而你尝试用oneOf引用对象类型的Schema,二者类型不匹配导致写法无效。根据是否能调整API结构,有两种可行方案:
方案一:调整API结构(推荐)
如果可以修改API,将event_data从字符串类型改为直接返回JSON对象,就能利用OpenAPI的条件校验能力,明确关联event_name和对应结构:
components: schemas: EventResponse: oneOf: - type: object required: [id, event_name, event_data] properties: id: type: integer event_name: type: string enum: [TypeA] event_data: $ref: '#/components/schemas/TypeA' - type: object required: [id, event_name, event_data] properties: id: type: integer event_name: type: string enum: [TypeB] event_data: $ref: '#/components/schemas/TypeB' - type: object required: [id, event_name, event_data] properties: id: type: integer event_name: type: string enum: [TypeC] event_data: $ref: '#/components/schemas/TypeC' TypeA: type: object properties: action: type: string enum: [Action1, Action2] value: type: string TypeB: type: object properties: # 填写TypeB的字段定义 TypeC: type: object properties: # 填写TypeC的字段定义
这种写法能让OpenAPI工具自动校验event_name和event_data的对应关系,文档展示也更清晰。
方案二:保留字符串类型,优化文档展示
如果无法修改API结构,只能通过文档优化让关联关系更直观:
- 在
event_data的描述里明确对应规则 - 给
event_data添加不同类型的示例 - 在components中定义各类型的对象Schema,方便用户参考
properties: id: type: integer event_name: type: string enum: [TypeA, TypeB, TypeC] event_data: type: string format: json description: | 字符串化的JSON对象,结构与`event_name`严格对应: - 当`event_name`为`TypeA`时,结构参考下方的`TypeA` Schema - 当`event_name`为`TypeB`时,结构参考下方的`TypeB` Schema - 当`event_name`为`TypeC`时,结构参考下方的`TypeC` Schema examples: TypeA示例: value: '{"action": "Action1", "value": "some-string"}' TypeB示例: value: '{"your_field": "sample-value"}' components: schemas: TypeA: type: object properties: action: type: string enum: [Action1, Action2] value: type: string TypeB: type: object properties: your_field: type: string TypeC: type: object properties: # 填写TypeC的字段定义
这种方式无法让工具自动校验,但能让文档读者清晰了解event_name和event_data的关联逻辑。
内容的提问来源于stack exchange,提问作者medowlock
相关产品推荐
相关产品推荐

