• preface
  • First, environmental preparation
  • Add Spring Boot class — add Swagger2 dependency — create Swagger2 configuration class — add API and document description — 5
  • Third, summary

preface

With the popularity of RESTful programming model, more and more teams start to build their API interfaces based on RESTful, whether it is large enterprise gateway API, or small inter-department and inter-group service invocation, RESTful is becoming more and more popular.

We typically build apis to accommodate multiple devices (e.g., IOS, Android, H5 Web), and usually one or more teams are responsible for this, which requires us to write an interface document and synchronize it to different teams. This is one of the most common methods we use, but at this point, we have to face two problems:

  1. There are too many interfaces and too many types of interfaces (HTTP, TCP, and other technical details need to be considered), resulting in the output of a high-quality interface document requires a lot of manpower and time.
  2. Over time, changing the interface will inevitably require modifying the document, and when it comes to synchronizing information to different teams, inconsistencies can easily occur without a synchronization guarantee mechanism.

In order to solve the above problems, this article will introduce Swagger, a good companion of RESTful APIS, which can be easily integrated into the Spring Web system (Spring MVC and Spring Boot), and organize strong RESTful API documents. One of its best features is the integration of maintaining documentation and modifying code (which is one of the most popular methods among programmers), allowing us to modify the documentation as well as the code logic. The specific effect is shown in the picture below:

First, environmental preparation

  • A computer
  • Demo full address: github.com/mickjoust10…

Second, the actual combat

1. Add the Spring Boot class

Create a new class: TestController, as shown below, and add the simplest Boot code. You can also refer to the boot_start project in Spring Boot Practice to start a Restful API project.

@EnableAutoConfiguration
@RestController
public class TestController {

    public static void main(String[] args) { SpringApplication.run(TestController.class,args); }}Copy the code

Define a User object as follows:

public class User {

    private int id;

    private String name;
    private String phone;
    private String address;

    public User(a) {}// omit get and set
}
Copy the code

Add Swagger2 dependency

Add Swagger2 dependencies to POM.xml, using the latest version 2.8.0.

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8. 0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8. 0</version>
</dependency>
Copy the code

Create Swagger2 configuration class

Create the configuration class ConfigSwagger2 for Swagger2.

@Configuration
@EnableSwagger2
public class ConfigSwagger2 {

    @Bean
    public Docket writeRestApi(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.hjf.boot.demo.swagger"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                .title("Automatically build RESTful APIs in Spring Boot with Swagger")
                .description("Examples from: http://blog.csdn.net/mickjoust")
                .termsOfServiceUrl("")
                .contact("mickjoust")
                .version("1.0") .build(); }}Copy the code

As shown in the code above, we have Spring Boot load this Configuration via the @Configuration annotation. EnableSwagger2 with the @enableswagger2 annotation.

Use the @Bean annotation to have the writeRestApi function create a Bean of type Docket (that is, the return object that Swagger will use and added to Spring’s IoC container for management).

The apiInfo() method is used to create the basic information for the API, which is eventually displayed in the documentation page.

The select() function returns an instance of ApiSelectorBuilder that controls which interfaces are exposed to Swagger for presentation. This example is defined by the package path specified for scanning — Swagger scans all Controller defined apis in that package. And produce document content (except for requests specified by @apiIgnore).

4. Add apis and documentation

After completed the configuration, then have been able to generate an empty interface documentation, start the boot process, visit: http://localhost:8080/swagger-ui.html, as shown below:



Swagger uses Jacson’s data-bind dependency.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.94.</version>
</dependency>
Copy the code

Next, we need to add our own API interfaces and corresponding descriptions. As shown below, we add instructions to the API with the @ApiOperation annotation, and to the parameters with the @ApiIMPLICITParams and @ApiIMPLicitParam annotations.

@EnableAutoConfiguration
@RestController
@RequestMapping("/use")
@ComponentScan
public class TestController {

    public static void main(String[] args) {
        SpringApplication.run(TestController.class,args);
    }

    // Emulation saves user information
    static Map<Integer, User> users = new HashMap<>();

    static
    {
        User user1 = new User(1."john"."18012345678"."cd");
        User user2 = new User(2."marry"."18012345678"."bj");
        User user3 = new User(3."jack"."18012345678"."sz");
        users.put(1,user1);
        users.put(2,user2);
        users.put(3,user3);
    }


    @apiOperation (value=" create user ", notes=" pass a form data ")
    @APIIMPLICITParam (name = "User", value = "User detail entity User", Required = true, dataType = "User")
    @RequestMapping(value="", method=RequestMethod.POST)
    public String postUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @apiOperation (value=" get user ", notes=" query information by id ")
    @APIIMPLICITParam (name = "ID", value =" user ID", Required = true, dataType = "Integer")
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    @apiOperation (value=" update user ", notes=" specify update object by ID ")
    @APIIMPLICITParams ({@APIIMPLICITParam (name = "id", value = "user ID", Required = true, dataType = "Long"), @APIIMPLICITParam (name = "User", value = "User detail entity User", Required = true, dataType = "User")})
    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    public String putUser(@PathVariable Integer id, @RequestBody User user) {
        User user$ = users.get(id);
        user$.setName(user.getName());
        users.put(id, user$);
        return "success";
    }

    @apiOperation (value=" delete user by id ", notes=" delete user by ID ")
    @APIIMPLICITParam (name = "id", value = "user ID", Required = true, dataType = "Long")
    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public String deleteUser(@PathVariable Integer id) {
        users.remove(id);
        return "success"; }}Copy the code

Start the program, then we can see the four defined interfaces and the corresponding interface description. Click on the controller to see the specific interfaces, as well as more specific information, such as the API to get user information, as shown in the figure below.



5. API debugging

In the request page above, we see an input box in the Parameter field.

Yes, Swagger provides debugging tests in addition to viewing interface functions, click “Try it out!” Click the “Excute” button to edit the parameters. Then click the “Excute” button to complete a request call!

Therefore, it is a good idea to add Swagger to manage API documentation while building RESTful apis.

Consider this question: If you were designing an API gateway, how would you make your API automatically published to the gateway?

That’s what we’ll try to solve next time.

summary

This article shows how to integrate Swagger’s capabilities by building a simple API.

Some students may wonder why they want to expose the API to others. In fact, the reason is very simple, in order to maintain the consistency of communication constraints. That is to quickly reach a consensus on development and improve development efficiency.

Students with practical experience know that in the real r&d process, there will be communication problems of one kind or another in interface invocation between different departments, either because of misunderstanding of the protocol, or because they are completely confused about the definition of interface and keep trying. In the final analysis, they do not have a clear and consistent understanding of the definition of interface.

A gateway may involve hundreds or thousands of interface calls, and it is expensive to maintain it manually. If swagger is used well, it can help.


Full Demo address: github.com/mickjoust10…


The resources

2. Spring Boot