Super Simple Springboot+swagger 2 Realizes Online Interface Debugging

Posted by stephenlk on Sat, 31 Aug 2019 17:24:31 +0200

Preface:

As a standard background development lion, is it necessary to prepare interface documents for front-end interaction when it provides interface to it? Is it necessary to pass the self-test before interacting with him? Is it necessary to write interface calls (such as postman) before self-testing? As a responsible and upward-looking engineer, these must be done. Everything has to be done, the way it can be done is different, and the results and efficiency are different. So let's share with you how the interface provided in springboot project can provide a convenient and fast way to self-test, or even directly test the interface tester. That's how to integrate it into seagger 2. Use the third-party plug-in you want to use. ,


Affirms that:

I don't like the complexity of the article and the pursuit of simplicity and aesthetic practicality, but in order to get the partners in place directly and absolutely usable, I paste the core code directly to make it easy for you to copy the past, which adds unfriendly complexity to the article.


Development environment:

1. Adding dependencies

Here we default to the maven project we have used. Otherwise, please download the dependency related java packages yourself. The project introduces the following dependencies:

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

2. Adding configuration classes

package cn.seally.community.config;

import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.common.base.Predicate;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @Description swagger Online Interface Plug-in Configuration Class
 * @Date 2019 31 August 2000
 * @author seallydeng
 */
@Configuration
@EnableSwagger2 //Open Online Interface Document
public class SwaggerConfig {
 
    /**
     * @Description
     * @Date 2019 31 August 2000
     * @author seallydeng
     * @return
     */
    @Bean
    public Docket controllerApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("Title: Seally Web Interface Document")//Title
                        .description("The interface of this system mainly includes xxx,yyy Functional modules")//describe
                        .contact(new Contact("dningcheng", "http://www.xxx.com/web", "dningcheng@163.com"))
                        .version("1.0.0")//version number
                        .build())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.seally.community.controller"))//Controller Class Pack Configuring Scan
                .paths(paths())//Configuring path interfaces that conform to specified rules generates online interfaces for customizing those interfaces to be displayed in the ui
                .build();
    }
   
    @SuppressWarnings("unchecked")
   private Predicate<String> paths() {
        return or(regex("/user/api/.*?"));
    }
}

3. Controller adds interface description information by annotation

package cn.seally.community.controller;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.seally.community.common.ApiResponse;
import cn.seally.community.model.base.SystemUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description Controller for demonstrating swagger online interface documents
 * @Date 2019 31 August 2000
 * @author seallydeng
 */
@Api(tags={"Hot Map Interface on Home Page of the System"}) //Annotated on the class: Used to annotate the name of the interface group
@RestController
@RequestMapping("/demo")
public class DemoController {
 
 @ApiOperation(value="Getting User Information",notes="username Is a unique property that a single user can access directly username Obtain") //Annotation in Method: Used to Note Interface Description
 @GetMapping(value="/user/query")
 public ApiResponse<String> getUserInfo(String username){
  return ApiResponse.success("Get information through");
 }
 
 @PostMapping(value="/user/save",produces="application/json")
 public ApiResponse<String> saveUserInfo(@RequestBody SystemUser user){
  return ApiResponse.success("Successful saving of user information");
 }
 
 @PutMapping(value="/user/update",produces="application/json")
 public ApiResponse<String> updateUserInfo(@RequestBody SystemUser user){
  return ApiResponse.success("Successful modification of user information");
 }
 
 @DeleteMapping(value="/user/delete/{username}",produces="application/json")
 public ApiResponse<String> deleteUserInfo(@PathVariable("username") String username){
  return ApiResponse.success("Successful deletion of user information");
 }
}

4. Start the project and visit it

Access paths can be entered in browsers and are usually used directly if the project does not have a configuration path: http://ip:port/swagger-ui.html It is accessible if springboot configures the project path such as:

The pathname of the access is:http://ip:port/seally-community-web/swagger-ui.html 

If the project is normal, you can see the following interface:

Let's look at a way:

The interface is too big, so only intercept the part. Here we just need to input the request parameters and click on the execution to see the results of Austrian execution, such as:

At the same time, there is a download button on the right to download directly to a json format return value.

Usually, all kinds of methods generate parameters for us in the interface of swagger. We can directly execute the request just by filling in the value. The following is an example of post request, which initiates the request in application/json mode:

Summary:

Whether swagger 2 works well or not, it only demonstrates the annotations that are useful, but of course it also has a series of annotations to help us specify the interfaces and parameters in detail, such as:

  • @ ApiImplicitParams: Represents a set of parameter descriptions for the method of requests

  • @ ApiImplicitParam: Used in the @ApiImplicitParams annotation to represent a specific parameter for each information description of a single parameter

  • @ ApiResponses: Used in the method of requests to represent a set of responses

  • @ ApiResponse: Used in @ApiResponses to represent a specific parameter of the response and to illustrate various aspects of the specific parameter

  • @ ApiModel: Used on response classes to represent information that returns response data

  • @ ApiModel Property: Used in conjunction with @ApiModel for describing attribute information of response classes on attributes of response classes

These annotations can be used as needed. As long as the parameters are well defined and have specific semantics, I don't think we need such detailed annotations to increase the workload of writing annotations.


Well, is it very simple? If you need some friends, try it quickly. If it's good for you, please give me a compliment and encourage me to go on the way of sharing. Never stop...................................................

Topics: Programming JSON SpringBoot Google Maven