You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenAPI如何在Schema中引用另一个Schema的单个属性?

在OpenAPI中引用Schema的单个属性是否可行?

可行,有两种主流实现方式,分别适配不同的OpenAPI版本:

方法1:单独提取属性为独立Schema(兼容所有OpenAPI版本)

最稳妥的方式是把Person的id属性单独拆成一个可复用的Schema,适配所有OpenAPI版本(包括2.0和3.x)。修改后的定义如下:

components:
  schemas:
    PersonId:
      type: number
      description: ID of the person
    Person:
      type: object
      properties:
        id:
          $ref: '#/components/schemas/PersonId'
        username:
          type: string
          description: Username of the person
        books:
          description: All books of one person
          type: array
          items:
            $ref: '#/components/schemas/Book'
    CreateBookDto:
      type: object
      properties:
        title:
          type: string
          description: The title of the book
        person_id:
          $ref: '#/components/schemas/PersonId'

方法2:直接引用对象的属性路径(仅OpenAPI 3.1+支持)

从OpenAPI 3.1开始,规范全面兼容JSON Schema 2020-12,支持直接通过$ref指向另一个Schema的具体属性路径。这种方式无需额外拆分Schema,更简洁:

components:
  schemas:
    Person:
      type: object
      properties:
        id:
          type: number
          description: ID of the person
        username:
          type: string
          description: Username of the person
        books:
          description: All books of one person
          type: array
          items:
            $ref: '#/components/schemas/Book'
    CreateBookDto:
      type: object
      properties:
        title:
          type: string
          description: The title of the book
        person_id:
          $ref: '#/components/schemas/Person/properties/id'

注意事项

  • 若项目需要支持OpenAPI 3.0及以下版本,请优先使用方法1;
  • 方法2仅在OpenAPI 3.1及更高版本中有效,使用前需确认你的API文档工具(如Swagger UI、Redoc等)支持该特性。

内容的提问来源于stack exchange,提问作者Henning

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 15:02:35