I'm using Spring for my REST API development. And I have some API where there are lots of endpoints. When I open up swagger ui, it looks to packed.
I just read this article and saw that we can group endpoints based on resource level.
I just want to know how that can be achieved with swagger annotations with Spring. I appreciate if someone can describe with an example.
And also I just wonder whether we can regroup (higher level grouping) the groups we have deduces in above way?
********** SOLUTION 1: (using groups) **********
Just define multiple Docket
bean for each group, and u will get logical grouping as per your need.
@Bean
public Docket api1() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("users")
.select()
.paths(PathSelectors.ant("/api/users/**"))
.build();
}
@Bean
public Docket api2() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("products")
.select()
.paths(PathSelectors.ant("/api/products/**"))
.build();
}
Now you will get two groups in your swagger ui like below.
********** SOLUTION 2: (using tags) **********
You don't need to define multiple Docket
bean just one is enough.
@Bean
public Docket api1() {
// here tags is optional, it just adds a description in the UI
// by default description is class name, so if you use same tag using
// `@Api` on different classes it will pick one of the class name as
// description, so better define your own description for them
return new Docket(DocumentationType.SWAGGER_2)
.tags(new Tag("users", "users related"),
new Tag("products", "products related"))
.select()
.apis(RequestHandlerSelectors.basePackage("com.github"))
.build();
}
After that you just need to annotate your api methods with @Api
(at class level, default for all methods) or @ApiOperation
(at method level, will override value at class level).
@RestController
@RequestMapping("/api/products")
@Api(tags = "products")
public class ProductController {
@ApiOperation(value = "", tags = "products")
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public Product createProduct(@RequestBody Product product) {
return product;
}
}
Tags in @ApiOperation
(or in @Api
) will work across controller as well, i.e. method in different controller classes (or controller itself) tagged with a given tag will be grouped together.