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

如何在YAML文件中隐藏/排除响应Schema的特定属性?

OpenAPI Schema 字段过滤实现方案

针对你的需求——一个接口返回Pet全字段,另一个接口排除healty和color字段,分两种OpenAPI版本场景实现:

场景1:使用OpenAPI 3.1+(推荐,语法更简洁)

OpenAPI 3.1兼容JSON Schema 2020-12标准,支持omit关键字直接排除指定字段,无需重复定义字段规则:

修改Schema定义

在components/schemas中新增一个精简版的Pet Schema:

components:
  schemas:
    Pet:
      type: object
      properties:
        id:
          type: integer
        name: 
          type: string
        wight: 
          type: integer
        height: 
          type: integer
        weight: 
          type: integer          
        color: 
          type: string
        healty: 
          type: string
    # 新增:排除healty和color的精简版Pet
    PetWithoutHealthAndColor:
      $ref: '#/components/schemas/Pet'
      omit: [healty, color]

修改接口响应

将/pet/findByConition的响应Schema替换为新定义的精简版:

/pet/findByConition:
  get:
    tags:
      - pet
    responses:
      '200':
        description: ''
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PetWithoutHealthAndColor'

场景2:使用OpenAPI 3.0.x(兼容旧版本)

OpenAPI 3.0不支持omit,可通过以下两种方式实现:

方式A:定义独立的精简版Schema(直观易维护)

直接创建只包含所需字段的Schema,通过$ref复用原Pet的字段定义,避免重复编写类型规则:

components:
  schemas:
    Pet:
      type: object
      properties:
        id:
          type: integer
        name: 
          type: string
        wight: 
          type: integer
        height: 
          type: integer
        weight: 
          type: integer          
        color: 
          type: string
        healty: 
          type: string
    PetWithoutHealthAndColor:
      type: object
      properties:
        id:
          $ref: '#/components/schemas/Pet/properties/id'
        name:
          $ref: '#/components/schemas/Pet/properties/name'
        wight:
          $ref: '#/components/schemas/Pet/properties/wight'
        height:
          $ref: '#/components/schemas/Pet/properties/height'
        weight:
          $ref: '#/components/schemas/Pet/properties/weight'
      # 按需添加必填字段,例如id和name为必填时:
      required: [id, name]

之后在/pet/findByConition的响应中引用该新Schema即可。

方式B:用allOf+not临时过滤(适合少量字段排除)

若不想新增Schema,可直接在接口响应中用allOf引用原Pet,再通过not排除指定字段:

/pet/findByConition:
  get:
    tags:
      - pet
    responses:
      '200':
        description: ''
        content:
          application/json:
            schema:
              allOf:
                - $ref: '#/components/schemas/Pet'
              not:
                properties:
                  healty: {}
                  color: {}
              # 确保不会出现未定义字段,需OpenAPI 3.0.3+支持
              unevaluatedProperties: false

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 13:25:09