如何使用OpenAPI 3.0.3实现接口参数间的依赖校验规则
你要的字段依赖规则可以通过OpenAPI 3.0.3原生语法实现,无需依赖第三方扩展,Swagger、Stoplight、Readme.io等主流工具全兼容,具体方案如下:
方案1:oneOf + const约束(兼容性最优)
该写法直接在单个schema内完成规则定义,无需拆分多个子组件,适配所有支持OpenAPI 3.0的工具:
components: schemas: # 会话创建接口请求体 CreateConversationRequest: type: object required: - messages properties: messages: type: array items: $ref: '#/components/schemas/Message' # 消息对象schema Message: type: object # 所有类型的消息都必填type字段 required: - type # 枚举所有允许的type取值 properties: type: type: string enum: [text, text_with_attachments, interactive] text: type: string description: 消息文本内容 attachments: type: array description: 附件列表 items: type: object # 此处可继续定义附件的结构 # interactive类型的专属字段可在此补充 # 按type值匹配对应的字段校验规则 oneOf: # type=text时必填text字段 - properties: type: const: text required: - text # type=text_with_attachments时必填text和attachments字段 - properties: type: const: text_with_attachments required: - text - attachments # interactive类型可在此自定义规则,无特殊必填规则可留空 - properties: type: const: interactive
方案2:discriminator多态写法(可读性最优)
如果后续消息类型的字段差异较大,建议用多态写法拆分子组件,维护成本更低:
components: schemas: CreateConversationRequest: type: object required: - messages properties: messages: type: array items: $ref: '#/components/schemas/BaseMessage' # 消息基础schema BaseMessage: type: object required: - type discriminator: propertyName: type mapping: text: TextMessage text_with_attachments: TextWithAttachmentsMessage interactive: InteractiveMessage properties: type: type: string enum: [text, text_with_attachments, interactive] # 纯文本消息schema TextMessage: allOf: - $ref: '#/components/schemas/BaseMessage' - type: object required: - text properties: text: type: string # 带附件的文本消息schema TextWithAttachmentsMessage: allOf: - $ref: '#/components/schemas/BaseMessage' - type: object required: - text - attachments properties: text: type: string attachments: type: array items: type: object # 交互型消息schema InteractiveMessage: allOf: - $ref: '#/components/schemas/BaseMessage' - type: object # 此处补充交互型消息的字段规则
以上两种写法均完全符合OpenAPI 3.0.3官方规范,支持工具端渲染和接口校验逻辑自动生成,之前测试不通过大概率是使用了非标准的第三方扩展规则,替换为上述写法即可。
内容的提问来源于stack exchange,提问作者Kartik Subramanian
相关产品推荐
相关产品推荐

