Search code examples
javaspring-bootswaggerswagger-uispringfox

How to exclude fields from RequestBody - Swagger


I have this DTO:

public class UserTo extends AbstractBaseTo {

@NotBlank(message = "Name must not be blank")
@Size(min = 2, max = 100, message = "Name length must be between 2 and 100 characters")
private String name;

@Email(message = "Email must accord email pattern")
@NotBlank(message = "Email must not be blank")
@Size(max = 100, message = "Email length must be 100 characters max")
private String email;

@NotBlank(message = "Password must not be blank")
@Size(min = 5, max = 32, message = "Password length must be between 5 and 32 characters")
private String password;
.......

I use this DTO in many methods of my UserController, but, for example, in Login method i use only two fields of that: email and password.

When i use Swagger to create documentation to my API, it shows all fields of UserTo in documentation for Login method. I want that it shows only two fields. How can i do this? I do not want to create additional DTOs (with 2 or 3 fields, you know). I tried to use @RequestBody annotation from Swagger for create some example of needed RequestBody, but it doesn't work.

I use Spring Boot and springfox 3.0.0.


Solution

  • You can hide parameters from swagger ui, by using

    @ApiModelProperty(hidden = true)
    

    with the fields you do not want to show. But the hidden fields will be hidden for every api in your swagger ui.

    There is another way which requires you to create another dto. You can create another Dto and ask springfox show the new alternate dto instead of the original one.

        @PostMapping(value = "/someapi")
        @ApiImplicitParams({
                @ApiImplicitParam(
                        name = "request",
                        dataTypeClass = AdditionalModel.class
                )
        })
        public Response hello(@RequestBody Request request){
            return new Response();
        }
    

    This approach will not make you change your code, but you will be required to create another dto. Also you also need to register the AdditionalModel in your Docket Bean.

        @Bean
        public Docket petApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build()
                    .pathMapping("/")
               .additionalModels(typeResolver.resolve(AdditionalModel.class));
        }