Soulmate of RESTful API - Swagger

Always start with something general!

 

    Swagger is a real-time generation and testing tool for documentation of RESTful interfaces. If you have not been exposed to similar tools, you may have no concept of this sentence. Don't worry, I will explain it slowly.

    One of the reasons for using REST is to facilitate the separation of front-end and back-end development. Back-end developers write back-end logic, front-end developers write front-end logic, and then everyone agrees on an API style, using HTTP get, post, put, delete. The CURD of the corresponding resource. This situation is avoided: front-end developers look up the thick API documentation provided by the back-end while developing indignantly. Each business logic corresponds to an interface specification, which is chaotic. Then one day the back end changed the logic, deleted a few interfaces and added a few more interfaces, and the front end had to change the code on a large scale, and then the front end and the back end started fighting.

    In order to avoid fights, the design of the API is standardized, and a lighter RESTful style is used. And Swagger plays a icing on the cake, it makes the front-end and back-end collaboration more efficient. After the back-end developer defines the interface, Swagger will automatically generate and update the document. The document will record the usage of the interface in detail, which parameters need to be passed in, and what kind of result will be returned, which saves the time of writing the document. It also improves the synchronization speed of documents and improves development efficiency. In addition, Swagger has more than these functions. It also has a powerful function, which is to test the interface directly in the document. We can use Swagger to simulate the real operation of the user and send a request to the background to verify whether the interface meets the requirements. Having said so much, maybe you still don't quite understand, so let me post a picture directly. The following picture is the document generated by Swagger:

 

 

 

 

 

    Forget it, no screenshots, just give a link: http://petstore.swagger.io/?_ga=2.151670393.1145939008.1514200525-1067691787.1514200525

    This is a demo document provided by the official, you can simply operate it, you should be enlightened suddenly!

 

    Well, Swagger has been introduced, I believe everyone already knows him. Below I will describe how to embed Swagger in a spring mvc project:

    This article uses springfox-swagger to implement Swagger integration. It's easy, just a few steps away! 

Step ↓:

  1. Introduce jar package, here I use maven to directly introduce dependencies:
    		<!-- swagger RestfulAPI documentation tool -->
    		<dependency>
    			<groupId>io.springfox</groupId>
    			<artifactId>springfox-swagger2</artifactId>
    			<version>${springfox.version}</version>
    		</dependency>
    		<dependency>
    			<groupId>io.springfox</groupId>
    			<artifactId>springfox-swagger-ui</artifactId>
    			<version>${springfox.version}</version>
    		</dependency>
     The version used here is springfox.version=2.6.1
  2. Rewrite Swagger's configuration class and declare it as a bean:
    package com.ds.core.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
    
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    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;
    
    @EnableWebMvc
    @EnableSwagger2
    @ComponentScan("com.ds.literary.controller")//Configure the package to be scanned by Swagger
    @Configuration
    public class SwaggerConfig extends WebMvcConfigurationSupport {
    
    	@Bean
    	public Docket docket() {
    		return new Docket(DocumentationType.SWAGGER_2)
    				.apiInfo (apiInfo ())
    				.groupName("Du")
    				.select()
    //				.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
    //				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
    				.paths(PathSelectors.any())
    				.build();
    	}
    
    //	@Bean
    //	public Docket xxx() {
    //		return new Docket(DocumentationType.SWAGGER_2)
    // .apiInfo (apiInfo ())
    //				.groupName("xxx")
    //				.select()
    //				.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
    //				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
    //				.paths(PathSelectors.ant("/xxx/**"))
    //				.build();
    //	}
    
    	private ApiInfo apiInfo() {
    		return new ApiInfoBuilder()
    				.title("Ds")
    				.contact(new Contact("Du", "", "[email protected]"))
    				.version("0.0.1")
    				.build();
    	}
    }
     
  3. Just add some annotations when writing the controller:
    @RestController
    @RequestMapping("/blog")
    @Api(value = "Manage blogs, articles, log interfaces published by users", description = "Manage blogs, articles, and log interfaces published by users")
    public class BlogController extends BaseController<Blog>{
    	public String getService() {
    		return "blogService";
    	}
    
    	@PutMapping
    	@ApiOperation(value = "Modify blogs, articles, logs published by users", produces = MediaType.APPLICATION_JSON_VALUE)
    	public Object update(HttpServletRequest request, @RequestBody Blog param) {
                    ModelMap modelMap = new ModelMap();
                    long authorId=getCurrUser();
                    param.setAuthorId(authorId);
    		return super.update(modelMap, param);
    	}
    
    	@DeleteMapping
    	@ApiOperation(value = "Delete blogs, articles, logs published by users", produces = MediaType.APPLICATION_JSON_VALUE)
    	public Object delete(HttpServletRequest request, @RequestBody Blog param) {
                    ModelMap modelMap = new ModelMap();
    		return super.delete(modelMap, param);
    	}
    }
     
  4. Configure a resource redirection in spring:
    <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
     
  5. Start the project and open the default document interface http://localhost:8080/ds-sys-web/swagger-ui.html, this path is modified according to your actual situation. If you think this interface is ugly, you can customize it yourself. The specific method will not be introduced in this article.

Here is the screenshot after success:

 

 

Get it!cool

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326307592&siteId=291194637