SpringFox Swagger - Optional and Mandatory fields in model
Solution 1
Yes by default All the fields will be optional. To mark a field as required you can use following annotation.
@ApiModelProperty(required = true)
On the getter method of the field which should be required. This won't show the field as "mandatory". But the optional tag will be removed for this field in the documentation.
Hope this helps.
Solution 2
Support for bean validation annotations was added, specifically for @NotNull, @Min, @Max, and @Size in Springfox v2.3.2.
You can place those annotations on any of your API models.
In order to use it add the springfox-bean-validators dependency:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
</dependency>
Add to your application's configuration class:
@Import({springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class})
See: https://springfox.github.io/springfox/docs/current/#springfox-support-for-jsr-303
Solution 3
Try the a similar code in Swagger Configuration:
@Bean
public Docket api() {
List<ResponseMessage> list = new java.util.ArrayList<>();
list.add(new ResponseMessageBuilder().code(500).message("500 message")
.responseModel(new ModelRef("JSONResult«string»")).build());
list.add(new ResponseMessageBuilder().code(401).message("Unauthorized")
.responseModel(new ModelRef("JSONResult«string»")).build());
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any()).build().securitySchemes(Collections.singletonList(securitySchema()))
.securityContexts(Collections.singletonList(securityContext())).pathMapping("/")
.directModelSubstitute(LocalDate.class, String.class).genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(newRule(
typeResolver.resolve(DeferredResult.class,
typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
typeResolver.resolve(WildcardType.class)))
.useDefaultResponseMessages(false).apiInfo(apiInfo()).globalResponseMessage(RequestMethod.GET, list)
.globalResponseMessage(RequestMethod.POST, list);
}
And in the controller mapping add @RequestBody @Valid MyRequestClass req
for example if you are passing objects in the request body, and if you are passing parameters add something like @RequestParam(value = "email", required = true, defaultValue = "") String email
Also, see how in the config code how to reference a class with generic type, i.e "JSONResult«string»"
which is referencing JSONResult<String>
Solution 4
I was with the same problem but with @etech tips I was able to see the required fields marked in swagger. All I did was upgrading springfox-swagger.version to 2.9.2 (from 2.4.0) and guava.version to 20.0 (from 15) plus the import at the application configuration class. Thank you.
Punter Vicky
Updated on June 06, 2022Comments
-
Punter Vicky almost 2 years
I used SpringFox library for rest documentation of my spring boot app. When I click on model , all the elements are being returned as optional. Is there a way to display required elements as mandatory? Is there any additional configuration that needs to be added?
-
Punter Vicky almost 7 yearsThanks @Hasson. In the option where I am passing a java object , how can I specify which field is mandatory / optional using this configuration?
-
Hasson almost 7 yearsNot sure if Swagger will go that deep, but you may try with '@NotEmpty' and '@NotNull' for the fields in the object you are passing.
-
Dilip Krishnan almost 7 years@PunterVicky As pointed out in @Ganesh's answer. You could annotate your model with
@ApiModelProperty(required=true)
Or annotate it with@NotNull
javax annotation. -
Punter Vicky almost 7 yearsThanks @DilipKrishnan!
-
chrisinmtown about 6 yearsSpringfox swagger v 2.8.0 doesn't seem to pick up on the @NotNull annotations; the model in the HTML page shows no difference for fields with/without that.
-
chrisinmtown about 6 yearsThe annotation also works on the field. The "model" tab in the generated Swagger documentation then shows an asterisk to indicate required, and additionally shows "allowEmptyValue: false" on a new line after the field.
-
Arsalan Khalid over 5 years@chrisinmtown yeah it doesn't, notnull isn't a swagger annotation, but a part of JSR
-
etech about 5 years@chrisinmtown See my answer. You can add an additional springfox library that supports JSR annotations as of v2.3.2.
-
chrisinmtown about 5 yearsThanks, after adding dep & import the generated Swagger UI for the model shows min and max lengths for Strings, cool. But I don't see any change on an Integer field annotated @NotNull, am I blind?
-
etech about 5 years@chrisinmtown Putting @ NotNull on an int or Integer in my dto works fine for me: a red star shows up next to the parameter in the model for the swagger docs. If you're having an issue, I'd open a new question either on stackoverflow or at the springfox github.
-
oemera about 4 yearsIs there a way to set all fields of a model to
required
instead of writing@ApiModelProperty(required = true)
over every single property? -
dbreaux over 3 yearsRegrettably, I've found that this works until you also try to customize
@ApiModelProperty
as well. Then at least here on SpringFox 2.9.2, the required aspect of@NotNull
is lost, and and I had to duplicate that information withrequired=true
as well. -
awgtek about 3 yearsDoes this respect groups? I.e. with
@NotNull(groups = {MyClass.class})
--i.e. only showing the red asterisk MyClass is present in @Validated?