Enum in swagger

爷,独闯天下 提交于 2019-11-30 10:55:52

In case of swagger-maven-plugin 3.1.0 this might be a minimal documentation:

@ApiModel
public class Input {
    @ApiModelProperty
    public Day day;
}

@ApiModel
public enum Day {
    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday;
}

Then this is the generated json model:

"definitions" : {
  "Input" : {
    "type" : "object",
    "properties" : {
      "day" : {
        "type" : "string",
        "enum" : [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]
      }
    }
  }
}

And this is how the model is presented in the SwaggerUI:

Input {
day (string, optional) = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
}

According to the doc you pointed:

The dataType. See the documentation for the supported datatypes. If the data type is a custom object, set it's name, or nothing. In case of an enum use 'string' and allowableValues for the enum constants.

I think you should add the enum values manually:

@ApiModel
public class Input {

    @ApiModelProperty(dataType = "string", allowableValues = "Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday", value = "description", notes = "notes")
    public Day day;
}

Custom Springfox Plugin solution:

swagger.io recommends: "If you need to specify descriptions for enum items, you can do this in the description of the parameter or property"

I implemented this recommendation based on a proprietary @ApiEnum annotation. The library is available here: https://github.com/hoereth/springfox-enum-plugin

In OpenApi version Swagger 2.x you need to use new annotations described here: https://github.com/swagger-api/swagger-core/wiki/Swagger-2.X---Annotations

@Schema(description = "Shuttle shipment action")
public class ShuttleShipmentAction {

   @Schema(required = true, description = "Id of a shuttle shipments")
   private long id;

   @Schema(required = true, description = "Action to be performed on shuttle shipments", allowableValues = { "SEND",
        "AUTHORIZE", "REJECT", "FIX_TRAINRUN", "UNFIX_TRAINRUN", "DELETE" })
   private String action;
   ...
   ...

Resulting in something like this:

You may use responseContainer with your @ApiOperation annotation:

@ApiOperation(value = "Brief description of your operation.", response = YourEnum.class, responseContainer = "List")
sadhana

Thanks for this help.

I have used to this type in my code.

private String date;
@ApiModelProperty(dataType = "string", allowableValues = "FirstValue,   SecondValue", value = "description", notes = "notes")
private CarrierType carrierName;


public enum CarrierType {
    FirstValue,
    SecondValue
}

It is working fine for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!