如何在 yaml 文件中隐藏/排除响应模式的某些属性?

问题描述 投票:0回答:1

例如,我有架构,如下所述。在第一种情况下,我想返回所有字段,在第二种情况下,我想返回除“healty”和“color”之外的所有字段。由于某种原因,我第二次请求不需要它们。我该怎么做?

paths:
  /pet:
    get:
      tags:
        - pet
      responses:
        '200':
          description: ''
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Pet'          
  /pet/findByConition:
    get:
        tags:
          - pet
        responses:
          '200':
            description: ''
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/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
swagger openapi
1个回答
0
投票

您需要两个模式:

  • 仅具有公共属性的基本架构,
  • 另一个模式,使用
    allOf
    通过附加属性扩展基本模式。
components:
  schemas:
    BasePet:
      type: object
      properties:
        id:
          type: integer
        name: 
          type: string
        wight: 
          type: integer
        height: 
          type: integer
        weight: 
          type: integer          

    Pet:
      allOf:
        - $ref: '#/components/schemas/BasePet'
        - properties:
            color: 
              type: string
            healty: 
              type: string

然后更新您的操作,以便每个操作都引用其相关架构:

paths:
  /pet:
    get:
          ...
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BasePet'   # <-----
        
  /pet/findByConition:
    get:
            ...
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/Pet'     # <-----
© www.soinside.com 2019 - 2024. All rights reserved.