16. springcloud Integrates Swagger 2 to Build APIs for Restful Services

Keywords: Java Maven Spring Apache

Public number: java paradise

Spring Cloud registers services on Eureka. From Eureka's UI interface, you can see which services have been registered on Eureka Server. But if you want to see what RESTful interface methods the current service provides, you can't get them from Eureka Server. The traditional method is to sort out an interface document for developers to communicate with each other. This often leads to inconsistencies between documents and codes, such as code changes, but the interface documents have not yet been modified. Swagger 2 provides us with a perfect solution. Here's how Swagger 2 solves this problem.

1. New project sc-swagger2, corresponding pom.xml file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>spring-cloud</groupId>
    <artifactId>sc-swagger2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>sc-swagger2</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

2. New springboot Startup Class

package sc.swagger2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

}

3. New Swagger2 configuration class

package sc.swagger2.config;

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

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
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;

@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("sc.swagger2"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot Use in Swagger2 structure RESTful APIs")
                .description("More Spring Boot Pay attention to related articles: JAVA Paradise Public Number")
                .termsOfServiceUrl("https://edu.csdn.net/lecturer/995")
                .contact(new Contact("huangjinjin", //
                        "https://edu.csdn.net/lecturer/995",//
                        "happyhuangjinjin@sina.com"))
                .version("1.0")
                .build();
    }


}

4. Create a new simulated Controller

package sc.swagger2.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import sc.swagger2.model.User;

@Api(value="user management")
@Controller
public class UserController {

    @ApiResponses({ @ApiResponse(code = 000000, message = "Successful operation"),
        @ApiResponse(code = 000001, message = "Server internal exception") })
    @GetMapping(value = "/feign/user/getUser/{id}")
    @ResponseBody
    @ApiOperation(value = "Get basis Id User information",response = User.class)
    @ApiImplicitParam(name = "id", value = "user ID", required = true, dataType = "Long",example="100")
    public Map<String, Object> getUser(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", "000000");
        result.put("msg", "success");
        User u = new User();
        u.setId(1L);
        u.setAge(23);
        u.setUserName("huangjinjin");
        u.setPosition("cto");
        result.put("body", u);
        return result;
    }

    @ApiResponses({ @ApiResponse(code = 000000, message = "Successful operation"), 
        @ApiResponse(code = 000001, message = "Server internal exception") })
    @RequestMapping(value = "/feign/user/listUser", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "Get the user list")
    public Map<String, Object> listUser() {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", "000000");
        result.put("msg", "success");
        User u = new User();
        u.setId(1L);
        u.setAge(23);
        u.setUserName("huangjinjin");
        u.setPosition("cto");
        List<User> list = new ArrayList<User>();
        list.add(u);
        result.put("body", list);
        return result;
    }

    @ApiResponses({ @ApiResponse(code = 000000, message = "Successful operation"), 
        @ApiResponse(code = 000001, message = "Server internal exception") })
    @PostMapping(value = "/feign/user/addUser")
    @ResponseBody
    @ApiOperation(value = "Add user", notes = "according to User Object Creation User")
    @ApiImplicitParams({ @ApiImplicitParam(name = "userName", value = "User name", required = true, dataType = "String"),
        @ApiImplicitParam(name = "age", value = "Age", required = true, dataType = "String"),
        @ApiImplicitParam(name = "position", value = "position", required = true, dataType = "String"),
        @ApiImplicitParam(name = "id", value = "user ID", required = false, dataType = "Long",example="100")})
    public Map<String, Object> addUser(User user) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", "000000");
        result.put("msg", "success");
        result.put("body", 1);
        return result;
    }

    @ApiResponses({ @ApiResponse(code = 000000, message = "Successful operation"), 
        @ApiResponse(code = 000001, message = "Server internal exception") })
    @ApiOperation(value = "Update user")
    @PutMapping(value = "/feign/user/updateUser")
    @ResponseBody
    @ApiImplicitParams({ @ApiImplicitParam(name = "userName", value = "User name", required = true, dataType = "String"),
        @ApiImplicitParam(name = "age", value = "Age", required = true, dataType = "String"),
        @ApiImplicitParam(name = "position", value = "position", required = true, dataType = "String"),
        @ApiImplicitParam(name = "id", value = "user ID", required = true, dataType = "Long", example="100")})
    public Map<String, Object> updateUser(User user) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", "000000");
        result.put("msg", "success");
        result.put("body", 1);
        return result;
    }

    @ApiResponses({ @ApiResponse(code = 000000, message = "Successful operation"), 
        @ApiResponse(code = 000001, message = "Server internal exception") })
    @DeleteMapping(value = "/feign/user/deleteUser/{id}")
    @ResponseBody
    @ApiOperation(value = "delete user")
    @ApiImplicitParam(name = "id", value = "user ID", required = true, dataType = "Long",example="100")
    public Map<String, Object> deleteUser(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("code", "000000");
        result.put("msg", "success");
        result.put("body", 1);
        return result;
    }
    
}


5. New User Model Class

package sc.swagger2.model;

import java.io.Serializable;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel
public class User implements Serializable {

    private static final long serialVersionUID = 4639927446947303736L;

    @ApiModelProperty(name="id", dataType="Long", value="Primary key ID")
    private Long id;

    @ApiModelProperty(name="userName", dataType="String", value="Full name", required=true)
    private String userName;

    @ApiModelProperty(name="age", dataType="String", value="Age", required=true)
    private Integer age;

    @ApiModelProperty(name="position", dataType="String", value="position")
    private String position;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}

6. Start the sc-swagger 2 project and verify that it started successfully
Way 1: View logs

Mode 2: Access Address
http://127.0.0.1:9092/swagger-ui.html

Or visit http://localhost:9092/v2/api-docs

7. In the interface http://127.0.0.1 9092/swagger-ui.html click on the [user-controller] to see all the interfaces, but also to debug the interface calls.

Posted by jim.davidson on Fri, 04 Oct 2019 18:34:44 -0700