“This is the 18th day of my participation in the First Wenwen Challenge 2022.First challenge in 2022”

One, foreword

Both are now embracing front-end separation and microservices, and front-end technologies are moving further and further apart in their respective paths. The only link between the front and back ends becomes the API interface, and the API documentation becomes the link between the front and back end developers and testers. A strong Restful API documentation is crucial. At the moment, on the back end, it’s Swagger’s game.

Overview of Swagger2

Swagger is a Restful framework for automatic online document generation and functional testing. A canonical and complete framework for generating, describing, invoking, and visualizing Restful style Web services, coupled with Swagger-UI, can render well.

Swagger is a group of open source projects, of which the main projects are as follows:

  • Swagger-tools: Provides various tools to integrate and interact with Swagger. For example, pattern checking, Swagger 1.2 documents to Swagger 2.0 documents, and so on.
  • Swagger-core: The Swagger implementation for Java/Scala. With JAX-RS(Jersey, Resteasy, CXF…) , Servlets, and the Play framework.
  • Swagger-js: Swagger implementation for JavaScript.
  • Swagger- Node-Express: Swagger module, used in node.js Express Web application framework.
  • Swagger-ui: A dependency free collection of HTML, JS, and CSS that dynamically generates elegant documentation for Swagger-compatible apis.
  • Swagger-codegen: A template-driven engine that generates client-side code in various languages by analyzing user Swagger resource declarations.

What is Swagger-UI?

Swagger-UI is a Restful interface for automatically generating documents online + function testing function software. Swagger-ui official address:swagger.io/Project address on Github:Github.com/swagger-api…Official demo address:petstore.swagger.io/

2. Why swagger-UI is used in API documentation?

Nowadays, in most project development, websites and mobile terminals need to carry out data interaction and docking, which requires the use of Restful WRITING API interface scenarios. This is especially true when different development & test teams work together, with specifications and documentation as the basis for standards and collaboration. Good documentation can reduce communication costs and achieve twice the result with half the effort. Sometimes I have a vague understanding of some API instructions, and I always want to verify my own understanding directly, rather than having to write test code to verify my ideas. That is, API documentation should have direct execution capabilities that word, Wiki, etc cannot provide. Swagger-ui is one such tool, based on Html+Javascript implementation, tends to be online documentation and testing, easy to use and integration, can easily generate different modules under the API list, each API interface description and parameters, request method can be customized and directly tested to get intuitive response data.

How to use swagger-UI?

Currently, there are two ways to use Swagger-UI officially provided:

  • Integrate with different server code, embed SwaggerUI document generation code in the server code, which is automatically generated at deployment time.
  • Manually edit the corresponding Json document. The Json document has its own format and is relatively complex. Therefore, you can use the official online editing method to achieve this goal.

Integration with SpringBoot

Pom depend on the package

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

Write the configuration file SwaggerConfig

/** * add annotations@EnableSwaggerAnd the bean class that defines the Docket. * /

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    // Whether to enable Swagger, formal environment generally need to be disabled, can be set according to Springboot multi-environment configuration
    @Value(value = "${swagger.enabled}")
    Boolean swaggerEnabled;

    @Bean
    public Docket createRestApi(a) {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                // Whether to enable
                .enable(swaggerEnabled).select()
                // The scanned path package
                .apis(RequestHandlerSelectors.basePackage("com.techstar"))
                PathSelectors. Any () represents all paths
                .paths(PathSelectors.any()).build().pathMapping("/");
    }

    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                .title("Springboot-swagger2 integration and Usage Examples")
                .description("7DGroup | zuozewei")
                // Author information
                .contact(new Contact("zuozewei"."https://blog.csdn.net/zuozewei"."[email protected]"))
                .version("1.0.0") .build(); }}Copy the code

Add document content (typically annotated on Controller, request parameters) add MyGetMethod class, demonstrating two Get requests

@RestController
@RequestMapping("/")
@api (tags = "Api document ",value = "/",description =" This is all my Get methods ")
public class MyGetMethod {

    @GetMapping(value = "/getCookies")
    @apiOperation (value = "Cookies can be obtained through this method ",httpMethod = "GET")
    public String getCookies(HttpServletResponse response){
        //HttpServerletRequest holds the class that requests information
        //HttpServerletResponse holds the class for the response message
        Cookie cookie = new Cookie("login"."true");
        response.addCookie(cookie);
        return "Congratulations to Zuozewei for getting cookies.";
    }

    /** * This is a GET request that requires cookies to be accessed */
    @GetMapping(value = "/get/with/cookies")
    @apiOperation (value = "Cookies can be obtained through this method ",httpMethod = "GET")
    public String getWithCookies(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (Objects.isNull(cookies)){
            return "You must bring cookies.";
        }
        for (Cookie cookie:cookies){
            if (cookie.getName().equals("login") && cookie.getValue().equals("true")) {return "This is a GET request that requires cookies to be accessed."; }}return "You must bring cookies."; }}Copy the code

Configure the global configuration file application.properties

Port =8888 # Enable swagger Swagger. Enabled =trueCopy the code

Start the project

Swagger-UI access and use

API home page path:http://127.0.0.1:8888/swagger-ui.html Click the LIST of apis you want to access to view the interface details, and clicktry it outButton to testPerform the testThe server returns the result

@Api: used on a class to describe what that class does. @apiOperation: annotation to add method specification to the API. ApiImplicitParams: Used to include a set of parameter descriptions on a method. ApiImplicitParam: Used as an annotation to add clarification to method inputs. @apiresponses: Used in @apiresponses, usually to express an incorrect response message

  • L code: number, for example, 400
  • L message: message, such as “request parameters are not filled in”
  • L Response: The class that throws an exception

@APIModel: Describes information about a Model (typically used when request parameters cannot be described using the @APIIMPLICITParam annotation). @APIModelProperty: Describes properties of a Model

For other annotations, you can automatically Google, after all, there are a few commonly used. With Swagger, some interface requests need debugging tools like Postman to initiate, but now you can debug directly on the page, isn’t it cool? For testers, with this API document is also at a glance, there is no need to communicate with the back end how much cost, according to the API instructions for interface test script development.

Five, the summary

This paper mainly explains the simple use of Swagger and the integration of Springboot. The detailed usage can be searched for relevant materials and will not be described here. Because for more than 80 percent of the documentation requirements are basically met. Finally, be sure to turn Off Swagger in production for safety reasons.

Project source code address:

  • Github.com/zuozewei/bl…