foreword
Whether you are engaged in front-end or back-end development, it is inevitable that you will be tortured by interface documentation. If you are a front-end developer, you may often find that the interface documentation given by the back-end is different from the actual code. And if you are a back-end developer, you may feel that developing the back-end interface by yourself is boring enough, and you have to spend a lot of energy to write and maintain the interface documentation, so it is inevitable that sometimes it will not be updated in time. This may cause the front and back ends to not understand each other, and even quarrel in the end, hahaha🤪.
At this time, we will wonder if there is a tool that allows us to quickly write interface documents. This tool can not only ensure that our interface documentation is updated in real time, but also ensure that we do not spend too much time on maintenance, as simple as writing comments.
Since this is a major pain point for most front-end and back-end programmers, there must be a solution. And this solution has been used by many people, and it has gradually become a norm. Everyone uses this solution by default, so as to solve the problem of asynchrony between front-end and back-end interface documents, and this is the origin of our protagonist today - Swagger.
By using Swagger, we only need to define the interface and related information of the interface according to a series of specifications given by it, and then it can help us automatically generate interface documents in various formats, which is convenient for front-end and back-end developers to conduct front-end and back-end joint debugging . At the same time, if our code interface changes, we only need to update the description of Swagger, and it can be updated in real time to achieve consistency between the actual code and the interface document.
Introduction to Swagger
What is Swagger
Swagger is an interface description language, which is mainly used to generate, describe, invoke and visualize RESTful style web service interface documents. In previous projects, the front-end and back-end may not be developed separately, so the interface documentation may not be so important. But now the mainstream projects are basically separated from the front and back ends. If the front and back ends are not well communicated, it may cause the interface documents to be updated untimely, causing some unnecessary troubles. In layman's terms, Swagger is to help us write interface documents. It can not only automatically generate real-time interface documents, but also generate test cases to facilitate our testing.
Swagger mainly provides the following open source tools:
- Swagger Editor
The editor provided by Swagger is mainly used to edit the Swagger description file, and supports real-time preview of the updated effect of the description file. Similar to our Markdown editor, you can write the source code on the left and preview it in real time on the right. The editor not only provides online use, but also supports local deployment.
- Swagger UI
Provides a visual UI page for displaying Swagger description files. The caller and tester of the interface can check the relevant information of the interface through this page, and perform simple interface request testing.
- Swagger Codegen
By using this tool, Swagger description files can be generated into HTML and CWIKI interface documents, and can also generate server and client code for many different languages.
Swagger UI
The tool we usually deal with the most is Swagger UI, which is mainly used to display interface documents. According to the description set in our code according to the Swagger specification, the interface description document is automatically generated. A simple example is as follows:
Spring Boot integrates Swagger
Create a Spring Boot project
After a brief introduction to Swagger above, let's take a look at how to use Swagger in a Spring Boot project.
First, you need to create a simple Spring Boot project. If you don't know how to create it, you can refer to my previous article 3 ways to create a Spring Boot project .
The project interface after creation is as follows:
import dependencies
After creating the Spring Boot project, you need to configure the project pom.xml
file and introduce Swagger-related dependencies into it.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
Build the Swagger configuration class
After introducing dependencies, the next step is to build the configuration class of Swagger.
package com.cunyu.springbootswaggerdemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
*
* @author : 村雨遥
* @version : 1.0
* @project : springboot-swagger-demo
* @package : com.cunyu.springbootswaggerdemo.config
* @className : Swagger2Configuration
* @createTime : 2022/1/5 22:21
* @email : 747731461@qq.com
* @微信 : cunyu1024
* @公众号 : 村雨遥
* @网站 : https://cunyu1943.github.io
* @description :
*/
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
/**
* 配置 Swagger 2
* 注册一个 Bean 属性
* enable():是否启用 Swagger,启用后才能在浏览器中进行访问
* groupName():用于配置 API 文档的分组
*/
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(true)
.groupName("v1")
.select()
// 过滤路径
//.paths(PathSelectors.ant())
// 指定扫描的包
.apis(RequestHandlerSelectors.basePackage("com.cunyu.springbootswaggerdemo.controller"))
.build();
}
private ApiInfo apiInfo() {
/*作者信息*/
Contact contact = new Contact("村雨遥", "https://cunyu1943.github.io", "747731461@qq.com");
return new ApiInfo(
"Swagger 测试接口文档",
"Spring Boot 集成 Swagger 测试接口文档",
"v1.0",
"https://cunyu1943.github.io",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
);
}
}
write interface
After configuring Swagger, add a simple interface to our project. Here we take a simple interface with and without parameters as an example.
package com.cunyu.springbootswaggerdemo.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created with IntelliJ IDEA.
*
* @author : 村雨遥
* @version : 1.0
* @project : springboot-swagger-demo
* @package : com.cunyu.springbootswaggerdemo.controller
* @className : SwaggerDemoController
* @createTime : 2022/1/5 22:21
* @email : 747731461@qq.com
* @微信 : cunyu1024
* @公众号 : 村雨遥
* @网站 : https://cunyu1943.github.io
* @description :
*/
@Api
@RestController
public class SwaggerDemoController {
@ApiOperation(value = "hello world 接口")
@GetMapping("hello")
public String hello() {
return "hello world";
}
@ApiOperation(value = "有参接口")
@PostMapping("demo")
public String demo(@ApiParam(name = "name", value = "村雨遥", required = true) String name) {
return "hello," + name;
}
}
View and test the interface
After completing the above steps, we start the project, and then visit the following address in the browser to access the interface documentation of our project.
http://localhost:8080/swagger-ui.html
After accessing the above address, if the following interface appears, it means that our Spring Boot integration of Swagger2 has been successful.
Click on a specific interface, there will be some detailed information of this interface, as shown in the following figure, generally including:
- interface request method
- interface request path and description
- interface request parameter
- interface responds with
If we want to perform a simple test, click Try it out
upper right of the above figure, and then we can edit the value of the request parameter. After editing, click Execute
below to view the interface return value.
Taking the interface I gave as an example, I passed in a parameter name
, then executed the demo
interface, and finally returned hello,name
the result of name
, of which 061de362b6d24a is the parameter value I passed in, here I passed in the village Yuyao, so the result You should get hello, Murakami, you can see that the Swagger test also returned the corresponding result to me, indicating that our interface test was successful!
Notice
If the following error occurs during the integration process:
org.springframework.context.ApplicationContextException:Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
There may be due to the Spring Boot version is too high cause, when I write this article, start using SpringBoot 2.6.2
version, so the error occurred, and when I SpringBoot
downgraded to 2.5.6
when the error no longer occurs. So if you also have this problem, you can also try to reduce the SpringBoot
version to solve it.
Summarize
The above is all the content of this article. It mainly introduces Swagger briefly, integrates Swagger with Spring Boot, and conducts simple tests. As for the sample code in the article, I have uploaded it to Github. If you need it, you can pick it up yourself.
Portal: https://github.com/cunyu1943/java-learning-demos
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。