2

Suppose that I have this definition in a yaml OpenApi definition

definitions:
  User:
    description: "User"
    type: "object"
    properties:
      firstname:
        type: "string"
      lastname:
        type: "string"
      password:
        type: "string"
      email:
        type: "string"
      username:
        type: "string"

If in a parameters specification I need specific fields of a definition how can I refer them without defining another model as below?

definitions:
  UserLogin:
    description: "User"
    type: "object"
    properties:
      password:
        type: "string"
      email:
        type: "string"

1 Answers1

2

In your question, you are using definitions keyword what hints that your question is about OpenAPI v2 aka. Swagger. For OpenAPI v3, definitions provided below should be defined inside appropriate Components Object sections.

In order to achieve this, you have to use Composition with keyword allOf. There is a great example that relates to your question here. First, you have to define a smaller object and then include it into the definition of a larger as follows:

definitions:
  UserLogin:
    description: User Login
    type: object
    properties:
      password:
        type: string
      email:
        type: string
  User:
    allOf:
    - $ref: '#/definitions/UserLogin'
    - description: User
      type: object
      properties:
        firstname:
          type: string
        lastname:
          type: string
        username:
          type: string

It is worth noting that:

  • Some lighter implementations may not support allOf keyword.
  • Using composition may increase or decrease the readability of the documentation, depending on the complexity and choice of words used to name the schemas.