preface

Whether you’re working on front-end or back-end development, you’ve probably been plagued by interface documentation. If you are a front-end developer, you may often find that the interface documentation from the back end is different from the actual code. If you’re a back-end developer, you might feel like you’re tired of developing your own back-end interfaces, and spend a lot of effort writing and maintaining the interface documentation, so it’s inevitable that sometimes the updates aren’t timely. This may cause the front and back end do not understand each other, and finally even quarrel, hahaha ðŸĪŠ.

At this point, we wondered if there was a tool that would allow us to quickly document our interfaces. This tool allows us to keep our interface documentation up to date and not spend a lot of time maintaining it, as simple as writing comments.

Since this is a major pain point for most front and back end programmers, there must be a solution. And this scheme is used by many people, and gradually becomes a standard, everyone uses this scheme by default, so as to solve the problem of the front and back end interface documents are not synchronized, and this is the origin of our hero today – Swagger.

By using Swagger, we define interfaces and information about interfaces according to a given set of specifications, and then it automatically generates interface documentation in various formats for front-end and back-end developers. At the same time, if our code interface changes, we just need to update the description of Swagger, it can be updated in real time, to achieve the consistency of the actual code and interface document.

Introduction of Swagger

What is the Swagger

Swagger is an interface description language used to generate, describe, invoke, and visualize RESTful Web service interface documents. Previous projects may have been more developed on both the front and back ends, so interface documentation may not have been as important. However, the mainstream projects are basically separated from the front and back ends. If the front and back ends do not communicate well, the interface documents may not be updated in time, causing some unnecessary trouble. In layman’s terms, Swagger writes interface documentation for us. It can not only automatically generate real-time interface documentation, but also generate test cases for us to test.

Swagger provides the following open source tools:

  1. Swagger Editor

The editor provided by Swagger is mainly used for editing Swagger description files and supports real-time preview of the updated effect of description files, similar to our Markdown editor. The source code can be compiled on the left side and real-time preview can be carried out on the right side. The editor is not only available online, but also supports local deployment.

  1. Swagger UI

Provides a visual UI page for displaying Swagger’s description file. The interface callers and testers can check the interface information and perform simple interface request tests on this page.

  1. Swagger Codegen

Using this tool, Swagger’s description files can be generated into interface documentation in HTML and CWIKI form, as well as server-side and client-side code for many different languages.

Swagger UI

The Swagger UI tool we deal with most is probably the Swagger UI tool, which is used to display interface documents. Automatically generate interface documentation according to the description set in our code according to the Swagger specification. A simple example is as follows:

Spring Boot integrates Swagger

Create a Spring Boot project

With this brief introduction to Swagger, let’s look at how to use Swagger in Spring Boot projects.

First, you need to create a simple Spring Boot project. If you don’t know how to do that, refer to my previous article on 3 ways to create a Spring Boot project.

The created project interface is as follows:

Introduction of depend on

After the Spring Boot project is created, you need to configure the project POM.xml file to import Swagger dependencies.

<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>
Copy the code

Build the Swagger configuration class

With the dependency introduced, it’s time to build the Configuration class for 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: Village yu Yao *@version : 1.0
 * @project : springboot-swagger-demo
 * @package : com.cunyu.springbootswaggerdemo.config
 * @className : Swagger2Configuration
 * @createTime: 2022/1/5 you *@email: 747731461 @qq.com * @ WeChat: cunyu1024 number: * @ the public village rain away * @ website: https://cunyu1943.github.io@description: * /
@Configuration
@EnableSwagger2
public class Swagger2Configuration {

    /** * Configure Swagger 2 * Register a Bean property * enable() : Whether to enable Swagger so that it can be accessed in the browser * groupName() : used to configure grouping of API documents */
    @Bean
    public Docket docket(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(true)
                .groupName("v1")
                .select()
                // Filter paths
                //.paths(PathSelectors.ant())
                // Specify the packet to scan
                .apis(RequestHandlerSelectors.basePackage("com.cunyu.springbootswaggerdemo.controller"))
                .build();
    }

    private ApiInfo apiInfo(a) {
        /* Author information */
        Contact contact = new Contact("Village Rain Yao"."https://cunyu1943.github.io"."[email protected]");
        return new ApiInfo(
                "Swagger Test Interface Documentation"."Spring Boot integrated Swagger Test Interface document"."v1.0"."https://cunyu1943.github.io",
                contact,
                "Apache 2.0"."http://www.apache.org/licenses/LICENSE-2.0".newArrayList() ); }}Copy the code

Write the interface

After Swagger is configured, 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: Village yu Yao *@version : 1.0
 * @project : springboot-swagger-demo
 * @package : com.cunyu.springbootswaggerdemo.controller
 * @className : SwaggerDemoController
 * @createTime: 2022/1/5 you *@email: 747731461 @qq.com * @ WeChat: cunyu1024 number: * @ the public village rain away * @ website: https://cunyu1943.github.io@description: * /

@Api
@RestController
public class SwaggerDemoController {
    @apiOperation (value = "Hello world interface ")
    @GetMapping("hello")
    public String hello(a) {
        return "hello world";
    }

    @apiOperation (value = "parameter interface ")
    @PostMapping("demo")
    public String demo(@apiParam (name = "name", value = "villageyuyuan ", Required = true) String name) {
        return "hello,"+ name; }}Copy the code

View and test the interface

After completing the above steps, we started the project and then accessed the following address in the browser to access the interface document for our project.

http://localhost:8080/swagger-ui.html

After accessing the above address, if the following interface appears, it means that Spring Boot has successfully integrated Swagger2.

Click on a specific interface, and there will be some detailed information about the interface, as shown in the following figure, generally including:

  1. Interface request mode
  2. Interface request path and description
  3. Interface request parameters
  4. The interface response

If we want to do a simple test, click Try It Out in the upper right of the image above, then we can edit the value of the request parameter, and then click Execute below to see the interface return value.

Take the interface I gave, for example, I pass in a parameter name, and then execute the demo interface, and it will return me hello,name, where name is the parameter value I passed in, and here I passed in Village yuyao, so the result should be Hello village Yuyao, It can be seen that the Swagger test also returned corresponding results to me, indicating that our interface test was successful!

Pay attention to

If the following error occurs during integration:

org.springframework.context.ApplicationContextException:Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
Copy the code

This may be due to an excessively high version of SpringBoot. I started with SpringBoot version 2.6.2 when WRITING this article, so this error occurs, and when I demoted SpringBoot to 2.5.6, the error no longer occurs. So if you have this problem, try lowering the SpringBoot version to fix it.

conclusion

That’s all for this article, which mainly introduces Swagger, integrates Swagger with Spring Boot, and performs simple tests. As for the sample code in the article, I have uploaded it to Github. If you need it, you can take it yourself.

🎉 🎉 🎉 portal