OpenAPI 3 - Reuse of properties
Asked Answered
C

3

6

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?

Chanukah answered 15/4, 2019 at 8:29 Comment(3)
Possible duplicate of Property reference to Model on swagger 2.0 (nesting)Regularly
You need to define a schema for that enum, then you can $ref the enum schema in the enumField property. See the ^^ linked question for the $ref syntax.Regularly
Related: Swagger: Reusing an enum definition as query parameterRegularly
B
10

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'
Baseman answered 5/6, 2020 at 10:50 Comment(0)
E
1

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
Estreat answered 4/3 at 3:52 Comment(0)
W
0

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:

Wed answered 3/7 at 11:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.