Mastering Swagger: Configuring allowableValues in @ApiModelProperty
This guide explains how to use the Swagger @ApiModelProperty annotation's allowableValues attribute to define fixed lists, numeric ranges, or open-ended limits for API parameters, with clear Java code examples and the resulting documentation output.
When generating API documentation with Swagger, the @ApiModelProperty annotation can describe a field's allowed values via its allowableValues attribute, which is a String. There are three ways to specify these values:
Provide a comma‑separated list, e.g., "first, second, third".
Define a numeric range using the range keyword with square brackets for inclusive bounds or parentheses for exclusive bounds, e.g., "range[1,5]", "range(1,5)", "range[1,5)".
Set a minimum or maximum using range with infinity (or -infinity) as one bound, e.g., "range[1,infinity]" meaning the minimum is 1.
The annotation definition looks like this:
public @interface ApiModelProperty {
/**
* Limits the acceptable values for this parameter.
* <p>
* There are three ways to describe the allowable values:
* <ol>
* <li>To set a list of values, provide a comma‑separated list.</li>
* <li>To set a range of values, start the value with "range" and use square or round brackets.</li>
* <li>To set a minimum/maximum value, use the same format with "infinity" or "-infinity".</li>
* </ol>
*/
String allowableValues() default "";
...
}In practice you can apply it as follows:
public class Filter {
@ApiModelProperty(allowableValues = "range[1,5]")
Integer order;
@ApiModelProperty(allowableValues = "111, 222")
String code;
}After rebuilding the project, the Swagger UI correctly displays the configured allowed values. The screenshot below shows the result.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
