如何在OpenAPI 3中定义引用其他Schema的数组?
在OpenAPI 3中定义引用其他Schema的数组方法
嘿,这个问题其实挺直观的,在OpenAPI 3里有两种常用的方式来定义引用现有Schema的数组,我结合你已经写好的User Schema给你演示下:
1. 直接在需要的地方定义(适合单次使用场景)
如果这个用户数组只在某一个API的响应、请求体或者参数里用到,直接在对应位置定义数组类型,并通过$ref指向你的User Schema就行:
# 举个例子,在某个获取用户列表的API响应中 paths: /users: get: summary: 获取所有用户 responses: '200': description: 成功返回用户列表 content: application/json: schema: type: array items: $ref: '#/components/schemas/User' # 引用已定义的User Schema
2. 单独定义数组类型的Schema(适合复用场景)
如果这个用户数组会在多个地方被引用,建议单独把它定义成一个Schema,放在components/schemas下,这样后续直接引用这个数组Schema即可:
components: schemas: # 你已有的User Schema User: type: object required: - id - username properties: id: type: integer format: int32 readOnly: true xml: attribute: true description: 用户ID username: type: string readOnly: true description: 用户名 first_name: type: string description: 用户名字 last_name: type: string description: 用户姓氏 avatar: $ref: '#/components/schemas/Image' example: id: 10 username: jsmith first_name: Jessica last_name: Smith avatar: image goes here xml: name: user # 新增的用户数组Schema UserList: type: array description: 一组用户信息的集合 items: $ref: '#/components/schemas/User' # 引用User Schema example: - id: 10 username: jsmith first_name: Jessica last_name: Smith avatar: image goes here - id: 11 username: doe_j first_name: John last_name: Doe avatar: another image goes here xml: name: users wrapped: true # 如果需要XML格式的包裹标签,可以加上这个
之后在需要用到用户数组的地方,直接引用这个UserList就行:
responses: '200': description: 成功返回用户列表 content: application/json: schema: $ref: '#/components/schemas/UserList'
另外提一句,你还可以给数组添加额外的属性,比如minItems、maxItems来限制数组长度,或者uniqueItems确保元素唯一,按需添加就好。
内容的提问来源于stack exchange,提问作者Old Man Walter
相关产品推荐
相关产品推荐

