首页 > 解决方案 > 嵌套参考在 Swagger UI / OpenAPI 3 中不起作用

问题描述

我有这个带有嵌套引用的 OpenAPI 3.0 定义:

Student:
    properties : &BaseStudent
    id:
      type: integer
      format: int64
      description: The ID of the new account.
    name:
      type: string
      description: The human-readable description of this account.
    address:
      $ref : 'address.yaml#/Address'

Address:
    properties : 
     <<* : BaseStudent
    city:
       type: string
      description: City.
    state:
      type: string
      description: State.
    
StudentMarks:
    <<: *BaseStudent
    makr1:
       type: string
      description: Mark1.
    mark2:
      type: string
      description: Mark2.

当我在 Swagger UI 中单击请求选项卡时,它显示错误:

无法解析引用,因为:无法解析指针:/components/schemas/components/schemas/Address 在文档中不存在

实际上Address参考应该是/components/schemas/唯一的。我不确定它为什么指的是/components/schemas/components/schemas/Address.

有没有其他方法可以不同地指定路径?

标签: swagger-uiopenapi

解决方案


该问题可能是由 YAML 锚引起的。

OpenAPI 有一种内置方式来引用定义和进行模型组合 -$refallOf. 通常应该使用这些关键字来代替 YAML 锚点。

尝试如下重写模式,看看它是否解决了问题:

components:
  schemas:

    Student:
      type: object
      properties:
        id:
          type: integer
          format: int64
          description: The ID of the new account.
        name:
          type: string
          description: The human-readable description of this account.
        address:
          $ref : 'address.yaml#/Address'

    Address:
      allOf:
        - $ref: '#/components/schemas/BaseStudent'
        - properties:
            city:
              type: string
              description: City.
            state:
              type: string
              description: State.
    
    StudentMarks:
      allOf:
        - $ref: '#/components/schemas/BaseStudent'
        - properties:
            mark1:
              type: string
              description: Mark1.
            mark2:
              type: string
              description: Mark2.

推荐阅读