如何在Swagger Editor中编辑YAML响应实现嵌套user对象的返回结构
可直接使用的调整后YAML(内联写法,无需额外定义)
responses: 200: description: User credentials. schema: properties: message: type: string example: User Information & already exist user: type: object properties: id: type: string example: 2386d9c5-5530-4950-b8fe- email: type: string example: saad.arshad@yahoo.com authentication_token: type: string example: kagHmoRSmPiu2R
复用结构的规范写法(适合多接口共用用户模型)
如果其他接口也会返回用户结构体,可以把用户定义抽到全局definitions下,解开你之前注释的$ref引用即可:
# 文件根级新增全局定义区,和paths节点同级 definitions: User: type: object properties: id: type: string example: 2386d9c5-5530-4950-b8fe- email: type: string example: saad.arshad@yahoo.com authentication_token: type: string example: kagHmoRSmPiu2R # 原接口响应配置修改为 responses: 200: description: User credentials. schema: properties: message: type: string example: User Information & already exist user: $ref: '#/definitions/User'
调整说明
- 先在
schema.properties下新增外层message字段,类型设为字符串,示例直接用线上返回的实际值 - 把原有三个用户属性全部下移到
user的属性下,同时给user加type: object声明为嵌套对象 - 所有示例值和线上返回完全对齐,Swagger渲染的响应样例就会和实际接口一致
- 注意嵌套属性的缩进必须统一,否则Swagger Editor会抛出结构校验错误
- 如果需要标记字段为必返,可在对应层级新增
required数组,比如外层加required: [message, user],User定义内部加required: [id, email, authentication_token]
内容的提问来源于stack exchange,提问作者Humayun Naseer
相关产品推荐
相关产品推荐

