Setting Up Swagger 2 with a Spring REST API
If you're new here, join the next webinar: "Secure a Spring REST API with OAuth2 + JWT". 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 its web page 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 be: http://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 (DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT).
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 the github project – this is an Eclipse based project, so it should be easy to import and run as it is.
Setting Up Swagger 2 with a Spring REST API的更多相关文章
- spring boot:swagger3文档展示分页和分栏的列表数据(swagger 3.0.0 / spring boot 2.3.3)
一,什么情况下需要展示分页和分栏的数据的文档? 分页时,页面上展示的是同一类型的列表的数据,如图: 分栏时,每行都是一个列表,而且展示的数据类型也可能不同 这也是两种常用的数据返回形式 说明:刘宏缔的 ...
- Secure Spring REST API using Basic Authentication
What is Basic Authentication? Traditional authentication approaches like login pages or session iden ...
- 通过Spring Mail Api发送邮件
使用Java Mail API来发送邮件也很容易实现,但是最近公司一个同事封装的邮件API实在让我无法接受,于是便打算改用Spring Mail API来发送邮件,顺便记录下这篇文章. [Spring ...
- Spring学习十五----------Spring AOP API的Pointcut、advice及 ProxyFactoryBean相关内容
© 版权声明:本文为博主原创文章,转载请注明出处 实例: 1.项目结构 2.pom.xml <project xmlns="http://maven.apache.org/POM/4. ...
- Spring Boot API 统一返回格式封装
今天给大家带来的是Spring Boot API 统一返回格式封装,我们在做项目的时候API 接口返回是需要统一格式的,只有这样前端的同学才可对接口返回的数据做统一处理,也可以使前后端分离 模式的开发 ...
- spring boot:swagger3的安全配置(swagger 3.0.0 / spring security / spring boot 2.3.3)
一,swagger有哪些环节需要注意安全? 1,生产环境中,要关闭swagger application.properties中配置: springfox.documentation.swagger- ...
- spring boot:用swagger3生成接口文档,支持全局通用参数(swagger 3.0.0 / spring boot 2.3.2)
一,什么是swagger? 1, Swagger 是一个规范和完整的文档框架, 用于生成.描述.调用和可视化 RESTful 风格的 Web 服务文档 官方网站: https://swagger.i ...
- 什么是 Swagger?你用 Spring Boot 实现了它吗?
Swagger 广泛用于可视化 API,使用 Swagger UI 为前端开发人员提供在线沙箱.Swagger 是用于生成 RESTful Web 服务的可视化表示的工具,规范和完整框架实现.它使文档 ...
- Swagger2 生成 Spring Boot API 文档
Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.本文主要介绍了在 Spring Boot 添加 Swagger 支持, 生成可自动维护的 A ...
随机推荐
- vue 解决 打包完iE下空白
安装 npm install --save babel-polyfill 在package.json中添加依赖, devDependencies:{ … "babel-polyfill&qu ...
- MySQL安装与启动
1.MySQL安装包下载 下载地址:https://dev.mysql.com/downloads/mysql/ 这里我的电脑是WIN764位的,大家根据自己的电脑自己选择要下载的包 2.解压安装 解 ...
- jdbcTemplate的简单介绍
Spring JDBC抽象框架core包提供了JDBC模板类,其中JdbcTemplate是core包的核心类,所以其他模板类都是基于它封装完成的,JDBC模板类是第一种工作模式. JdbcTempl ...
- 服务器重新启动,ftp重新连接问题
服务器重新启动,发现FlashFXP无法连接了,估计是ftp没有启动, 1. 首先服务器要安装ftp软件,查看是否已经安装ftp软件下: #which vsftpd 如果看到有vsftpd的目 ...
- org.apache.hadoop.security.AccessControlException
在hdfs集群上,需要向Hdfs写入文件,控制台会输出以下错误信息: Caused by: org.apache.hadoop.ipc.RemoteException(org.apache.hadoo ...
- [SoapUI] 从测试套件,测试用例,测试步骤,测试数据各个级别控制是否执行
自动保存 # -*- coding: utf-8 -*- import java.awt.Color import org.apache.poi.ss.usermodel.Cell import or ...
- Netsharp总体介绍
作者:秋时 日期:2014年02月05日 转载须说明出处 Netsharp交流群:338963050(请有详细的请求说明) Netsharp系列文章目录结构 Netsharp是一款免费的基于 ...
- Python3基础知识之日期时间与字符的转换
问题:“猿类”们都知道,编程中都会涉及到日期.时间类型与字符串类型的转换.不同场景,需要将字符串格式转换为日期类型:也需要将日期类型转换为字符串格式. 目标: 学习和积累python中time和dat ...
- 2019.02.26 bzoj4311: 向量(线段树分治+凸包)
传送门 题意: 支持插入一个向量,删去某一个现有的向量,查询现有的所有向量与给出的一个向量的点积的最大值. 思路: 考虑线段树分治. 先对于每个向量处理出其有效时间放到线段树上面,然后考虑查询:对于两 ...
- Linux 第七天
软件包管理 1.软件包分类 1)源码包(脚本安装包) 优点: l 开源,如果有足够的能力,可以修改源代码 l 可以自由选择所需的功能 l 软件是编译安装,所以更加适合自己的系统,更加稳定也效率更 ...