Swagger adding description to enums
Asked Answered
I

2

15

I have a class that looks like this:

public class Rule {

    private RuleType type; //enum
    private String value;
}

The enum is:

public enum RuleType {
    TYPE_A, TYPE_B, TYPE_C;
}

Now each rule type the values are different. TYPE_A requires a number 1 through 10, TYPE_B is true or false, and TYPE_C is a string. I am trying to add swagger annotations to the enum so that the documentation can show this, something like this:

public enum RuleType {
    @ApiModelProperty(value = "1 - 10")
    TYPE_A, 
    @ApiModelProperty(value = "True or False")
    TYPE_B, 
    @ApiModelProperty(value = "String")
    TYPE_C;
}

But this doesn't work. The swagger produced just ignores the properties on the enums. Is there a way to create documentation like this?

Inhospitable answered 31/7, 2018 at 15:21 Comment(4)
How can an enum value itself have multiple values? If the enum is TYPE_A, it would always be TYPE_A itself right? If it can have multiple values, it should be of a different data type and not an enum. For eg, if TYPE_B can be true or false, you should be using a boolean instead right? I believe you need to change your class design.Sigurd
OpenAPI Specification (and, by extension, Swagger tools) does not support descriptions for individual enum values (here's a related feature request). You'll probably need to specify these descriptions in the annotations for RuleType.Coheir
Any update on this? I use SpringDoc 1.4.3 and am facing the same issue.Windward
There is a github project that apparently solves this: github.com/hoereth/springfox-enum-plugin.Pastelki
R
0

You cannot do this as you like. But there is another simple solution which you want.

public class Rule {

    @ApiModelProperty(value = 
            "TYPE_A must be 1 - 10\n" +
            "TYPE_B must be True or False\n" +
            "TYPE_C must be String")
    private RuleType type; //enum
    private String value;
}

You can see final result of this code with this link: https://i.sstatic.net/pMA6N.png

Roxyroy answered 4/8, 2023 at 13:23 Comment(0)
C
0

As @Helen mentioned, it's currently not possible to set a description for enums. However, you can assign a description to the property, as @Azamat suggested. Here's a similar approach using Microprofile OpenAPI annotations.

import org.eclipse.microprofile.openapi.annotations.media.Schema;

public class Foobar {
  private String value;

  @Schema(
      name = "type",
      description = "TYPE_A - [1 - 10], TYPE_B - [True or False], TYPE_C - [String]")
  private RuleType type;
}

Swagger UI

Foobar{
value   string
type    string
TYPE_A - [1 - 10], TYPE_B - [True or False], TYPE_C - [String]

Enum:
[ TYPE_A, TYPE_B, TYPE_C ]
}

enter image description here

Congresswoman answered 26/9, 2023 at 8:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.