OpenAPI 3.0如何为包含嵌套对象的响应Schema添加示例?
OpenAPI 3.0 嵌套响应Schema添加示例的两种常用实现方式
方式1:顶层Schema统一配置完整嵌套示例
直接在响应的根Schema下添加单数字段example,按照Schema的嵌套结构直接写完整的示例值即可,这种方式适合单一场景的响应示例展示,优先级最高。
components: schemas: UserInfoResp: type: object properties: code: type: integer description: 响应状态码 msg: type: string description: 响应提示 data: type: object description: 用户数据 properties: user_id: type: string description: 用户ID username: type: string description: 用户昵称 address: type: object description: 收货地址 properties: province: type: string city: type: string detail: type: string order_list: type: array description: 近期订单列表 items: type: object properties: order_id: type: string amount: type: number create_time: type: string format: date-time # 直接填写完整嵌套结构的示例即可 example: code: 200 msg: "操作成功" data: user_id: "u10001" username: "张三" address: province: "广东省" city: "深圳市" detail: "南山区科技园XX路XX号" order_list: - order_id: "o2024001" amount: 299.9 create_time: "2024-05-01T12:30:00Z" - order_id: "o2024002" amount: 199 create_time: "2024-05-03T18:15:00Z"
方式2:各层级子Schema单独配置示例
如果你的嵌套子Schema是公共复用的(会被多个接口引用),可以在每个子Schema内部单独配置example字段,Swagger UI等工具会自动将各层级的示例拼接成完整的响应示例,不需要在顶层重复编写。
components: schemas: # 公共复用的地址Schema,自带示例 Address: type: object properties: province: type: string city: type: string detail: type: string example: province: "广东省" city: "深圳市" detail: "南山区科技园XX路XX号" # 公共复用的订单Schema,自带示例 Order: type: object properties: order_id: type: string amount: type: number create_time: type: string format: date-time example: order_id: "o2024001" amount: 299.9 create_time: "2024-05-01T12:30:00Z" # 根响应Schema UserInfoResp: type: object properties: code: type: integer description: 响应状态码 example: 200 msg: type: string description: 响应提示 example: "操作成功" data: type: object description: 用户数据 properties: user_id: type: string description: 用户ID example: "u10001" username: type: string description: 用户昵称 example: "张三" address: $ref: '#/components/schemas/Address' # 引用公共地址Schema order_list: type: array description: 近期订单列表 items: $ref: '#/components/schemas/Order' # 引用公共订单Schema
注意事项
- OpenAPI 3.0 中Schema层级使用的是单数
example字段,不要和响应层级的多示例字段examples、OpenAPI 3.1 新增的Schema级examples字段混淆 - 如果根Schema同时配置了顶层完整
example,各子Schema的单独示例会被覆盖,优先展示顶层配置的完整示例 - 如果需要为同一个接口配置多个不同场景的响应示例(比如参数异常、权限不足、正常返回等),可以在响应对象的
examples字段下配置多个命名示例,优先级高于Schema级的所有示例配置
内容的提问来源于stack exchange,提问作者Mayan19
相关产品推荐
相关产品推荐

