Search code examples
javaspring-bootswaggerspringfox

How can I specify a case-insensitive enum in Swagger?


I have an enum in Java and I want to use it as parameter in a GET request in my REST API - where the swagger docs are generated from annotations in the Java controller.

The enum itself has the ability to use case-insensitive values, but is defined with upper case values per Java conventions.

public enum SortDirection {

  ASC, DESC;

  public static SortDirection fromString(String value) { 
    try {
      return SortDirection.valueOf(value.toUpperCase(Locale.US));
    } catch(Exception e) {
      throw new IllegalArgumentException("Invalid value " + value + ". Valid values are 'asc' or 'desc' (case insensitive).", e);
    }
  }
}

The fromString allows lower case to be passed as a valid option as it is more common for URLs to use lower case.

If I use a default value of asc swagger will throw a validation error:

Default values must be present in enum

How can I specify that both lowercase and uppercase are valid options and set a default value of asc?


Solution

  • You can try using io.swagger.annotations.ApiParam in method signature:

    public void controllerMethod(
           @ApiParam(allowableValues="asc,desc") @RequestParam SortDirection sortDirection);