How to reuse swagger definitions and remove some of the parameters in it? [duplicate]
Asked Answered
L

1

10

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.

Leash answered 3/8, 2019 at 14:17 Comment(1)
It looks like id, created_at and updated_at are read-only and/or autogenerated properties. In this case you can just mark them as readOnly: true - as explained in the linked Q&A.Marciamarciano
R
11

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.

Rhynd answered 3/8, 2019 at 14:29 Comment(3)
As seen in #30896444Rhynd
Cool. I would not have seen that post without your suggestion. So that's the only way to do then. Thank you.Leash
You're welcome sir. I'm glad I could helpRhynd

© 2022 - 2024 — McMap. All rights reserved.