Using @Schema(allowableValues=) for enum param using openapi in spring boot

Viewed 10370

My API has a enum field in request body. When I generate swagger UI, its showing enum with allowed value as enum names. Instead of enum names, I need to set it to enum values. For that I used @Schema(allowableValues=). This lead to a list with both values and names in swagger UI. Can I set this to values only in swagger?

My enum example :

 public enum Days{
  MON("Monday"),
  SUN("Sunday")
}

Current swagger field looks like :

day string Enum: [ MON, SUN ]

I want it has :

day string Enum: [ Monday, Sunday]

When I add @Schema(allowableValues={"Monday", "Sunday") to the enum field, Swagger becomes:

day string Enum: [ MON, SUN, Monday, Sunday]

Any solution is appreciated.

enter image description here

4 Answers

use

@Schema(type = "string", allowableValues = { "Monday", "Sunday" })

Can be achieved by overriding toString for enum. No need to use @Schema

 @Override
  public String toString() {
    return value;
  }

If you are using Jackson then swagger added support to use the values defined in the annotations @JsonProperty/@JsonValue which was included in v2.1.3 https://github.com/swagger-api/swagger-core/releases/tag/v2.1.3

So you can just write

 public enum Days{
     @JsonProperty("Monday")
     MON,
     @JsonProperty("Sunday")
     SUN
}

Let's assume your request is defined in the Request class and your request attribute is day. So what you can easily do is add swagger-ui annotation @Schema as follows.

import io.swagger.v3.oas.annotations.media.Schema;

class Request {
    @Schema(type = "string", allowableValues = { "Monday", "Sunday" })
    String day;
}
Related