博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Setting Up Swagger 2 with a Spring REST API
阅读量:5871 次
发布时间:2019-06-19

本文共 7745 字,大约阅读时间需要 25 分钟。

If you're new here, . Thanks for visiting!

The Master Class of "Learn Spring Security" is out: 

1. Overview

When creating a REST 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.

In this tutorial we will look at Swagger 2 for a Spring REST web service. For the purposes of this article, we will use the Springfox implementation of the Swagger 2 specification.

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

2. Target Project

The creation of the REST service we will use in our examples is not within the scope of this article. If you already have a suitable project, use it. If not, the following links are a good place to start:

  • .

3. Adding the Maven Dependency

As mentioned above, we will use the Springfox implementation of the Swagger specification. To add it to our Maven project, we need a dependency in the pom.xml file.

1
2
3
4
5
<
dependency
>
    
<
groupId
>io.springfox</
groupId
>
    
<
artifactId
>springfox-swagger2</
artifactId
>
    
<
version
>2.4.0</
version
>
</
dependency
>

4. Integrating Swagger 2 into the Project

4.1. Java Configuration

Configuration of Swagger mainly centers around the Docket bean.

1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
@EnableSwagger2
public
class
SwaggerConfig {                                   
    
@Bean
    
public
Docket api() {
        
return
new
Docket(DocumentationType.SWAGGER_2) 
          
.select()                                 
          
.apis(RequestHandlerSelectors.any())             
          
.paths(PathSelectors.any())                         
          
.build();                                          
    
}
}

Swagger 2 is enabled through the @EnableSwagger2 annotation.

After the Docket bean is defined, its select() method returns an instance of ApiSelectorBuilder, which provides a way to control the endpoints exposed by Swagger.

Predicates for selection of RequestHandlers can be configured with the help of RequestHandlerSelectors and PathSelectors. Using any() for both will make documentation for your entire API available through Swagger.

This configuration is enough to integrate Swagger 2 into existing Spring Boot project. For other Spring projects, some additional tuning is required.

4.2. Configuration Without Spring Boot

Without Spring Boot, you don’t have the luxury of auto-configuration of your resource handlers. Swagger UI adds a set of resources which you must configure as part of a class that extends WebMvcConfigurerAdapter, and is annotated with @EnableWebMvc.

1
2
3
4
5
6
7
8
@Override
public
void
addResourceHandlers(ResourceHandlerRegistry registry) {
    
registry.addResourceHandler(
"swagger-ui.html"
)
      
.addResourceLocations(
"classpath:/META-INF/resources/"
);
 
    
registry.addResourceHandler(
"/webjars/**"
)
      
.addResourceLocations(
"classpath:/META-INF/resources/webjars/"
);
}

4.3. Verification

To verify that Springfox is working, you can visit the following URL in your browser:

http://localhost:8080/spring-security-rest/api/v2/api-docs

The result is a JSON response with large number of key-value pairs, which is not very human-readable. Fortunately, Swagger provides Swagger UI for this purpose.

5. Swagger UI

Swagger UI is a built-in solution which makes user interaction with the Swagger-generated API documentation much easier.

5.1. Enabling Springfox’s Swagger UI

To use Swagger UI, one additional Maven dependency is required:

1
2
3
4
5
<
dependency
>
    
<
groupId
>io.springfox</
groupId
>
    
<
artifactId
>springfox-swagger-ui</
artifactId
>
    
<
version
>2.4.0</
version
>
</
dependency
>

Now you can test it in your browser by visiting http://localhost:8080/your-app-root/swagger-ui.html

In our case by the way, the exact URL will behttp://localhost:8080/spring-security-rest/api/swagger-ui.html

The result should look something like this:

5.2. Exploring Swagger Documentation

Within Swagger’s response is a list of all controllers defined in your application. Clicking on any of them will list the valid HTTP methods (DELETEGETHEADOPTIONSPATCHPOSTPUT).

Expanding each method provides additional useful data, such as response status, content type, and a list of parameters. It is also possible to try each method using the UI.

Swagger’s ability to be synchronized with your code base is very important. To demonstrate this, you can add a new controller to your application.

1
2
3
4
5
6
7
8
@RestController
public
class
CustomController {
 
    
@RequestMapping
(value =
"/custom"
, method = RequestMethod.POST)
    
public
String custom() {
        
return
"custom"
;
    
}
}

Now, if you refresh the Swagger documentation, you will see custom-controller in the list of controllers. As you can see, there is only one method (POST) shown in Swagger’s response.

6. Advanced Configuration

The Docket bean of your application can be configured to give you more control over the API documentation generation process.

6.1. Filtering API for Swagger’s Response

It is not always desirable to expose the documentation for your entire API. You can restrict Swagger’s response by passing parameters to the apis() and paths() methods of the Docket class.

As seen above, RequestHandlerSelectors allows using the any or none predicates, but can also be used to filter the API according to base package, class annotation, and method annotations.

PathSelectors provides additional filtering with predicates which scan the request paths of your application. You can use any()none(), regex(), or ant().

In the example below we will instruct Swagger to include only controllers from a specific package, with specific paths, using the ant() predicate.

1
2
3
4
5
6
7
8
@Bean
public
Docket api() {               
    
return
new
Docket(DocumentationType.SWAGGER_2)         
      
.select()                                      
      
.apis(RequestHandlerSelectors.basePackage(
"org.baeldung.web.controller"
))
      
.paths(PathSelectors.ant(
"/foos/*"
))                    
      
.build();
}

6.2. Custom Information

Swagger also provides some default values in its response which you can customize, such as “Api Documentation”, “Created by Contact Email”, “Apache 2.0”.

To change these values, you can use the apiInfo(ApiInfo apiInfo) method. The ApiInfo class that contains custom information about the API.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Bean
public
Docket api() {               
    
return
new
Docket(DocumentationType.SWAGGER_2)         
      
.select()
      
.apis(RequestHandlerSelectors.basePackage(
"com.example.controller"
))
      
.paths(PathSelectors.ant(
"/foos/*"
))
      
.build()
      
.apiInfo(apiInfo());
}
 
private
ApiInfo apiInfo() {
    
ApiInfo apiInfo =
new
ApiInfo(
      
"My REST API"
,
     
"Some custom description of API."
,
     
"API TOS"
,
     
"Terms of service"
,
     
"myeaddress@company.com"
,
     
"License of API"
,
     
"API license URL"
);
    
return
apiInfo;
}

6.3. Custom Methods Response Messages

Swagger allows globally overriding response messages of HTTP methodsthrough Docket’s globalResponseMessage() method. First, you must instruct Swagger not to use default response messages.

Suppose you wish to override 500 and 403 response messages for all GET methods. To achieve this, some code must be added to the Docket’s initialization block (initial code is excluded for clarity):

1
2
3
4
5
6
7
8
9
10
11
.useDefaultResponseMessages(
false
)                                  
.globalResponseMessage(RequestMethod.GET,                    
  
newArrayList(
new
ResponseMessageBuilder()  
    
.code(
500
)
    
.message(
"500 message"
)
    
.responseModel(
new
ModelRef(
"Error"
))
    
.build(),
    
new
ResponseMessageBuilder()
      
.code(
403
)
      
.message(
"Forbidden!"
)
      
.build()));

7. Conclusion

In this tutorial we set up Swagger 2 to generate documentation for a Spring REST API. We also have explored ways to visualize and customize Swagger’s output.

The full implementation of this tutorial can be found in  – this is an Eclipse based project, so it should be easy to import and run as it is.

 
 

转载于:https://www.cnblogs.com/ygjlch/p/6050667.html

你可能感兴趣的文章
开发进度——4
查看>>
JS里验证信息
查看>>
Akka actor tell, ask 函数的实现
查看>>
windows10 chrome 调试 ios safari 方法
查看>>
Netty 4.1.35.Final 发布,经典开源 Java 网络服务框架
查看>>
详解Microsoft.AspNetCore.CookiePolicy
查看>>
SCDPM2012 R2实战一:基于SQL 2008 R2集群的SCDPM2012 R2的安装
查看>>
SQL SERVER中字段类型与C#数据类型的对应关系
查看>>
Linux lsof命令详解
查看>>
SVG path
查看>>
js判断checkbox是否选中
查看>>
多系统盘挂载
查看>>
MySQL函数怎么加锁_MYSQL 函数调用导致自动生成共享锁问题
查看>>
MR1和MR2的工作原理
查看>>
Eclipse中修改代码格式
查看>>
GRUB Legacy
查看>>
关于 error: LINK1123: failure during conversion to COFF: file invalid or corrupt 错误的解决方案...
查看>>
hexo博客解决不蒜子统计无法显示问题
查看>>
python实现链表
查看>>
java查找string1和string2是不是含有相同的字母种类和数量(string1是否是string2的重新组合)...
查看>>