“This is my 21 days in the Gwen Challenge. For more details, see Gwen Challenge.”

preface

Recently, when I was sorting out the Github warehouse, I saw a demo of SpringBoot and Swagger written in my college days, and finally decided to write an article to record it.

Introduction of Swagger

Swagger is a canonical and complete framework for generating, describing, invoking, and visualizing RESTful Web services.

The overall goal is to have clients and file systems update at the same rate as servers. File methods, parameters, and models are tightly integrated into server-side code, allowing the API to always be synchronized. Swagger makes deployment management and using powerful apis easier than ever.

Create a project

SpringBoot is 2.0.8 and Swagger is 2.9.2

	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>Mid-atlantic moved. RELEASE</version>
        <relativePath/> <! -- lookup parent from repository -->
    </parent>
	<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
Copy the code

Swagger configuration

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(a) {
        // The main API configuration mechanism is initialized to the Swagger specification 2.0
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.msr.demo.swagger.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(a) {
        Contact contact = new Contact("msr"."www.baidu,com"."[email protected]");
        return new ApiInfoBuilder()
                / / title
                .title("Build RESTful apis with Swagger2 in Spring Boot")
                // Description
                .description("Rest API Document Building Tools")
                // Service url
                .termsOfServiceUrl("http://localhost:8080")
                / / version number
                .version("1.0") .contact(contact) .build(); }}Copy the code

The Controller control layer

Swagger is primarily used at the control layer, with annotations to provide API documentation for the interface. The main annotations used in the following code are @ApiOperation and @ApiIMPLicitParam. The @ApiOperation annotation adds instructions to the API and the @ApiIMPLicitParams annotation adds instructions to parameters

Here are some of Swagger’s common notes, check out the official documentation for more details.

  • @API: Mark the class as a Swagger resource
  • @APIIMPLICITParam: represents a single parameter in an API operation
  • ApiImplicitParams: a wrapper that allows listing of multiple ApiImplicitParam objects
  • @APIModel: Provides additional information about the Swagger model, such as describing POJO objects
  • @APIModelProperty: Adds and manipulates data for model properties
  • @APIOperation: Describes operations or usually HTTP methods for a particular path
  • @APIParam: Add additional metadata for operation parameters
  • @apiResponse: Describes possible responses to an operation
  • @APIresponses: A wrapper that allows listing of multiple ApiResponse objects
  • @authorization: Specifies the Authorization scheme to be used for resources or operations
  • AuthorizationScope: Describes the OAuth2 authorization template
  • ResponseHeader: Represents a header that can be provided as part of the response.
  • @APIProperty: Describes property values in POJO objects
  • @APIError: Information returned by an interface error
  • .
@Slf4j
@API (tags = "User related Api ")
@RestController
public class UserController {

    @apiOperation (value =" get user information ",notes=" add user information ")
    @PostMapping("/user")
    public String addUser(@RequestBody User user) {
        log.info("POST request, received parameter :{}", user.toString());
        return user.toString();
    }

    @apiOperation (value = "update User ", notes =" update User based on User object ")
    @APIIMPLICITParam (name = "user", value = "user entity user", Required = true, dataType = "user")
    @PutMapping("/user")
    public boolean updateUser(@RequestBody User user) {
        log.info("UPDATE request, request parameter :{}", user);
        return true;
    }

    @apiOperation (value = "delete User ", notes =" delete User based on User object ")
    @APIIMPLICITParam (name = "user", value = "user entity user", Required = true, dataType = "user")
    @DeleteMapping("/user")
    public boolean deleteUser(@RequestBody User user) {
        log.info("DELETE request, request parameter :{}", user);
        return true;
    }


    @apiOperation (value = "get User list ", notes =" query User information from User object ")
    @APIIMPLICITParam (name = "user", value = "user entity user", Required = true, dataType = "user")
    @GetMapping("/user")
    public User findByUser(User user) {
        log.info("GET request, request parameter :{}", user);
        return User.builder()
                .id(1)
                .age(18)
                .name("Xiao Ming") .build(); }}Copy the code

Entity class

@apiModel (" user entity ")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
	@ ApiModelProperty (" user ID ")
    private Integer id;
    @apiModelProperty (" username ")
    private String name;
    @apiModelProperty (" Login password ")
    private String password;
    @ ApiModelProperty (" age ")
    private Integer age;
}
Copy the code

Start the class

@SpringBootApplication
public class SwaggerDemoApplication {

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

test

Start the program, the browser to http://localhost:8080/swagger-ui.html

Click on UserController and Models to see the configuration in the code

Select the interface you want to test and click Try It Out. Input parameter,

conclusion

In fact, Swagger has a lot of annotations, when an API is described, you will find a lot of annotations on the method. It was a little uncomfortable for me personally, a little aggressive feeling. For API documentation, there are currently many projects, feel good to use.