Eli Lyonhart
Eli Lyonhart

Reputation: 11

OpenAPI 3.0 reuse enum values in different schemas

I have multiple request bodies that need to utilize the same enums, but am struggling to reference a single definition across multiple schemas.

Within my openapi.yaml file, I have included:

components:
  schemas:
    Widget:
      type: string
      enum:
        - THING

In the body definitions that I have for my POST/PUT requests, I include:

  widget:
    schema:
      $ref: '#/../openapi.yaml/components/schemas/Widget'
    description: Include Widgets in your API today!

but in the generated-code, what is being created is:

  @JsonProperty("widget")
  private Object widget; // expecting: `private Widget widget;`

while a separate class is created with:

@Generated(value = "org.openapitools.codegen.languages.SpringCodegen")
public enum Widget {
  
  WIDGET("WIDGET"),
  
  private String value;

  Association(String value) {
    this.value = value;
  }

  @JsonValue
  public String getValue() {
    return value;
  }
...

How can I create a reference to enum definitions across files?

Upvotes: 1

Views: 2153

Answers (1)

Helen
Helen

Reputation: 98011

The correct syntax is

  widget:
    $ref: '../openapi.yaml#/components/schemas/Widget'

That is, you don't need the schema keyword inside property definitions. Also, # goes after the file name, not before it.

The file name (../openapi.yaml) is only needed if the schema is in a separate file. If the Widget schema is in the same file as your POST/PUT request definitions, you don't need the file name:

  widget:
    $ref: '#/components/schemas/Widget'

If you want to provide a custom description alongside the $ref, you'll need to wrap the $ref into allOf (as explained here):

  widget:
    allOf:
      - $ref: '#/components/schemas/Widget'
    description: Include Widgets in your API today!

Upvotes: 4

Related Questions