15

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
  • 15,954
  • 56
  • 188
  • 315

4 Answers4

23

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.

Ganesh
  • 5,977
  • 5
  • 19
  • 25
  • The 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. – chrisinmtown Mar 15 '18 at 13:55
  • 4
    Is there a way to set all fields of a model to `required` instead of writing `@ApiModelProperty(required = true)` over every single property? – oemera Mar 06 '20 at 14:13
3

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

etech
  • 2,548
  • 1
  • 27
  • 24
  • Thanks, 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? – chrisinmtown Mar 08 '19 at 13:49
  • @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. – etech Mar 08 '19 at 21:24
  • 1
    Regrettably, 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 with `required=true` as well. – dbreaux Sep 10 '20 at 21:31
  • Does this respect groups? I.e. with `@NotNull(groups = {MyClass.class})`--i.e. only showing the red asterisk MyClass is present in @Validated? – awgtek Apr 13 '21 at 22:47
2

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>

Hasson
  • 1,894
  • 1
  • 21
  • 25
  • Thanks @Hasson. In the option where I am passing a java object , how can I specify which field is mandatory / optional using this configuration? – Punter Vicky May 04 '17 at 19:05
  • Not sure if Swagger will go that deep, but you may try with '@NotEmpty' and '@NotNull' for the fields in the object you are passing. – Hasson May 04 '17 at 20:26
  • @PunterVicky As pointed out in @Ganesh's answer. You could annotate your model with `@ApiModelProperty(required=true)` Or annotate it with `@NotNull` javax annotation. – Dilip Krishnan May 05 '17 at 10:47
  • Thanks @DilipKrishnan! – Punter Vicky May 05 '17 at 17:13
  • 2
    Springfox 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 Mar 15 '18 at 13:51
  • @chrisinmtown yeah it doesn't, notnull isn't a swagger annotation, but a part of JSR – Arsalan Khalid Oct 01 '18 at 22:24
  • @chrisinmtown See my answer. You can add an additional springfox library that supports JSR annotations as of v2.3.2. – etech Mar 07 '19 at 22:33
1

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.

marisa79
  • 23
  • 1
  • 8