Setting up Spring REST API with Swagger2

Overview

When creating a RESTful API, good documentation is instrumental.

Moreover, every change in the API should be simultaneously described in the reference documentation. Accomplishing this manually is a tedious exercise, so automation of the process was inevitable.

If you are not familiar with Swagger, you should visit its web page to learn more before continuing with this article.

Target Project

The creation of the REST service I use is my own project–amazingxu.xyz. Source code are available on my Github.

Adding the Maven Dependency

To add it to our Maven project, we need to add dependencies in the pom.xml file.

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>

Integrating Swagger 2 into the Project

Java Configuration

The configuration of Swagger mainly centers around the Docket bean.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Bean
public Docket createRestApi() {
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
tokenPar.name("Authorization")
.description("Token")
.modelRef(new ModelRef("string"))
.defaultValue("Bearer ")
.parameterType("header")
.required(false).build();
pars.add(tokenPar.build());

return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.build()
.globalOperationParameters(pars)
.apiInfo(apiInfo());
}

Swagger 2 is enabled through the@EnableSwagger2 annotation.

By adding @Api(value="VALUE",description="DESC") , @RestController and @RequestMapping("ReqMap") annotation to the controller in the Spring Boot project, RESTful API UI can be seen by visiting http://amazingxu.xyz/swagger-ui.html



References:

http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2018-2022 James Wang
  • Visitors: | Views:

Buy me a coffee~

支付宝
微信