Hannes
Hannes

Reputation: 5282

OpenAPI 3 - Reuse of properties

Following the example of an OpenAPI 3 definition:

components:
  schemas:
    Foo:
      properties:
        string:
          type: string
        enumField:
          type: string
          enum: ['VALUE_1', 'VALUE_2']
    Bar:
      properties:
        enumField:
          type: string
          enum: ['VALUE_1', 'VALUE_2']

Is there a way to reuse enumField or do I have to specify it every time I use it?

Upvotes: 6

Views: 5808

Answers (3)

NemesisMate
NemesisMate

Reputation: 86

The most straight-forward and direct solution to this would be to just extract the enumField format into a type: string schema, without forcing the need of any type mixing.

components:
  schemas:
    Foo:
      properties:
        string:
          type: string
        enumField:
          $ref: '#/components/schemas/EnumField'
    Bar:
      properties:
        enumField:
          $ref: '#/components/schemas/EnumField'
    EnumField:
      type: string
      enum: [ 'VALUE_1', 'VALUE_2' ]

Sources:

Upvotes: 1

Anthony Nguyen
Anthony Nguyen

Reputation: 96

You can use below structure, it works for me with OpenAPI3

components:
  schemas:
    ExtendedSchema:
      properties:
        id:
          type: string
          description: Unique identifier
      allOf:
        - $ref: '#/components/schemas/BaseSchema'
    BaseSchema:
      type: object
      properties:
        name:
          type: string
          description: Name
        phone:
          type: string
          description: Phone

Upvotes: 1

I don't know if is possible to reference a single property, but you can do it with schemas, and by spliting it.

Here is a basic structure sample of what can you do:

SchemaBase:
  type: object
  properties:
    foo:
      type: string

SchemaFull:
  allOf:
    - $ref: '#/components/schemas/SchemaBase'
    - type: object
      properties:
        bar:
          type: string

In your case could be something like this:

components:
  schemas:
    EnumField:
      properties:
        enumField:
          type: string
          enum: ['VALUE_1', 'VALUE_2']
    Foo:
      allOf:
        - $ref: '#/components/schemas/EnumField'
        - properties:
            string:
              type: string
    Bar:
      allOf:
        - $ref: '#/components/schemas/EnumField'

Upvotes: 10

Related Questions