Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add a common parameter for swagger api

I my project there are lots of controllers with such annotation

    @ApiOperation(value = "description")
    @RequestMapping(value = "/{param1}", method = RequestMethod.POST)
    public @ResponseBody Response<Map<String, Object>> someMethod(
       @ApiParam(name = "param1", value = "about param1", required = true)
       @PathVariable("param1") int param1,

       @ApiParam(name = "param2", value = "about param2", required = false, defaultValue = "default)
       @RequestParam(value = "param2", defaultValue = "default") String param2
    ){
           // ..
    }

almost every method accept common parameter like access_token. It will bad solution if we add description about it to all methods. Maybe there is other solution?

I found that i can define json file with such configuration like here https://github.com/OAI/OpenAPI-Specification/blob/master/fixtures/v2.0/json/resources/reusableParameters.json, but as i understood i can use either json or annotation. Or maybe i can combine them somehow?

like image 203
Oleh Kurpiak Avatar asked May 27 '16 04:05

Oleh Kurpiak


1 Answers

If someone will be search for something like this. I found next solution. In project we configure swagger like this

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(commonParameters())
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfo(/* params here */);
        return apiInfo;
    }


    private List<Parameter> commonParameters(){
        List<Parameter> parameters = new ArrayList<Parameter>();
        parameters.add(new ParameterBuilder()
                .name("access_token")
                .description("token for authorization")
                .modelRef(new ModelRef("string"))
                .parameterType("query")
                .required(false)
                .build());

        return parameters;
    }
}

You should call globalOperationParameters method and pass there list of global paramets(i create it in commonParameters method).

Solution i found here http://springfox.github.io/springfox/docs/current/

Thats all.

like image 188
Oleh Kurpiak Avatar answered Nov 15 '22 05:11

Oleh Kurpiak