如何在OpenAPI 3中复用数组项示例?实现单模型与数组共享示例
复用示例内容在单个模型和数组模型中
嘿,我刚好遇到过类似的需求,想要在单个联系人模型和联系人数组模型里复用同一个示例内容,避免重复编写对吧?没问题,根据你使用的OpenAPI/Swagger版本,这里有两种靠谱的实现方式:
方案一:OpenAPI 3.1+ 官方推荐的示例复用方式
如果你的项目使用OpenAPI 3.1及以上版本,可以利用components/examples来定义可复用的示例片段,然后在需要的地方引用它,这是官方支持的标准方式:
openapi: 3.1.0 info: title: Contact API version: 1.0.0 components: # 定义可复用的示例片段 examples: SherlockHolmesContact: summary: Sherlock Holmes的联系信息示例 value: id: 1 firstName: Sherlock lastName: Holmes schemas: ContactModel1: type: object properties: id: type: integer firstName: type: string lastName: type: string # 引用刚才定义的示例作为单个模型的示例 example: $ref: '#/components/examples/SherlockHolmesContact/value' AllContacts: type: array items: $ref: '#/components/schemas/ContactModel1' # 数组示例里复用同一个Sherlock示例,加上Watson的内容 example: - $ref: '#/components/examples/SherlockHolmesContact/value' - id: 2 firstName: John lastName: Watson
这样修改后,ContactModel1的示例就是Sherlock的完整信息,AllContacts的数组示例也会直接复用这个片段,不用重复编写相同的内容,维护起来也更方便。
方案二:Swagger 2.0 或兼容工具用YAML锚点复用
如果你的项目还在使用Swagger 2.0,或者部分工具不支持示例中的$ref,可以用YAML原生的**锚点(&)和别名(*)**特性来实现复用,这是一种轻量化的方式:
swagger: '2.0' info: title: Contact API version: 1.0.0 definitions: ContactModel1: type: object properties: id: type: integer firstName: type: string lastName: type: string # 给示例打一个锚点,方便后续引用 example: &sherlockExample id: 1 firstName: Sherlock lastName: Holmes schemas: AllContacts: type: array items: $ref: '#/definitions/ContactModel1' # 使用别名引用刚才定义的锚点内容 example: - *sherlockExample - id: 2 firstName: John lastName: Watson
这里通过&sherlockExample给单个模型的示例标记一个锚点,然后在数组示例里用*sherlockExample直接调用这个锚点对应的内容,同样能实现复用效果,而且不需要额外的组件定义。
内容的提问来源于stack exchange,提问作者Old Man Walter
相关产品推荐
相关产品推荐

