How to reuse swagger definitions and remove some o

2020-04-20 12:14发布

问题:

This is my code:

definitions:
  User:
    type: object
    properties:
      id:
        type: integer
      username:
        type: string
      first_name:
        type: string
      last_name:
        type: string
      password:
        type: string
      created_at:
        type: string
        format: date-time
      updated_at:
        type: string
        format: date-time
    required:
      - username
      - first_name
      - last_name
      - password

/api/users:
  post:
    description: Add a new user
    operationId: store
    parameters:
      - name: user
        description: User object
        in: body
        required: true
        type: string
        schema:
          $ref: '#/definitions/User'
    produces:
      - application/json
    responses:
      "200":
        description: Success
        properties:
          success:
            type: boolean
          data:
            $ref: '#/definitions/User'

As you can see, in the post key under /api/users I used the User definition as my schema on it.

I want to lessen my code so I reused the User definition as my schema. The problem here is that I do not need the id, created_at and updated_at fields.

Is there a way to just inherit some of the fields except the fields mentioned? Also, I would love some suggestions to make it better since I'm trying to learn swagger. Thank you.

回答1:

As explained in this answer to a similar question:

You would have to define the models separately.

However, you have options for the cases of exclusion and difference.

If you're looking to exclude, which is the easy case, create a model of with the excluded property, say ModelA. Then define ModelB as ModelA plus the additional property:

ModelB:
  allOf:
    - $ref: "#/definitions/ModelA"
    - type: object
      properties:
        id:
          type: string

If you're looking to define the difference, follow the same method above, and exclude the id from ModelA. Then define ModelB and ModelC as extending ModelA and add the id property to them, each with its own restrictions. Mind you, JSON Schema can allow you to follow the original example above for some cases to "override" a definition. However, since it is not really overriding, and one needs to understand the concepts of JSON Schema better to not make simple mistakes, I'd recommend going this path for now.