swaggeropenapi

How to hide/exclude certain properties of schema for response in yaml file?


For example I have schema, described below. In the first case I want to return all fields, in the second case I want to return all except "healty" and "color". For some reason I do not need them for the second request. How do I do that?

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

Solution

  • You need two schemas:

    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
    

    Then update your operations so that each references its relevant schema:

    paths:
      /pet:
        get:
              ...
              content:
                application/json:
                  schema:
                    $ref: '#/components/schemas/BasePet'   # <-----
            
      /pet/findByConition:
        get:
                ...
                content:
                  application/json:
                    schema:
                      $ref: '#/components/schemas/Pet'     # <-----