Swagger is a restful-interface, YAML, JSON language based online automatic document generation, code generation tool

Swagger official address

swagger.io/

Making address:

github.com/swagger-api

Integration of swagger

Import the repository in POM.xml

      <dependency>
            <groupId>io.springfox</groupId>
             <artifactId>springfoxswagger2</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>
Copy the code

Swagger can scan annotations to get a JSON document, and display it on the page through swagger-UI. The springfox-Swagger-UI introduced above will load the page, and the access link launched by Springboot is: http://localhost:8080/swagger-ui.html

Static resources can also be obtained from https://github.com/swagger-api/swagger-ui, and all of its dist directory things in need to be integrated, but need to change the dist directory index. The HTML page to access the url, such as modified url: “http://localhost:8080/v2/api-docs”

<script>
    window.onload = function () {
        // Begin Swagger UI call region
        const ui = SwaggerUIBundle({
            url: "http://localhost:8080/v2/api-docs",
            // apisSorter: "alpha", // can also be a function// operationsSorter:function(a, b) {// // Custom sort specifications, sort according to method instructions, convert content to numbers, and then compare //return parseFloat(a.summary) - (parseFloat(b.summary));
            // } ,
            dom_id: '#swagger-ui',
            deepLinking: true,
            presets: [
                SwaggerUIBundle.presets.apis,
                SwaggerUIStandalonePreset
            ],
            plugins: [
                SwaggerUIBundle.plugins.DownloadUrl
            ],
            layout: "StandaloneLayout"
        })
        // End Swagger UI call region

        window.ui = ui
    }
</script>
Copy the code

Configuration file in SpringBoot

/ * * *@author yuan
 */
@Configuration
@EnableSwagger2
@ConditionalOnProperty(prefix = "swagger", value = {"enable"}, havingValue = "true")
public class Swagger2 {
    @Bean
    public Docket createRestApi(a) {
        /** *.host(" domain name ") if you want to access the document by domain name, you need to add this in case the document request fails due to cross-domain problems */
        return new Docket(DocumentationType.SWAGGER_2)/ / host (" domain name ")
                .apiInfo(apiInfo()).select()
                // Scan for swagger annotations in the specified package
                .apis(RequestHandlerSelectors.basePackage("com.yuan.redis.controller"))
                // Scan all annotated apis for more flexibility
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .build().securitySchemes(security());
    }

    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                .title("Base Platform API Documentation")
                .version("1.0.0")
                .build();
    }

    /** * permission control, add sessionId to request parameter, **@return* /
    private List<ApiKey> security(a) {
        List<ApiKey> apiKeyList = new ArrayList();
        ApiKey apiKey = new ApiKey("sessionId"."sessionId"."query");
        apiKeyList.add(apiKey);
        returnapiKeyList; }}Copy the code

ConditionalOnProperty @conditionalonProperty (prefix = “swagger”, value = {“enable”}, havingValue = “true”) You can add it to application.properties

# Swagger enabled or not
swagger.enable=false 
Copy the code

Swagger notes introduction

1. @Api() : used on the requested class to indicate that the class is the resource of Swagger2

Parameters:

Tags: indicates the function of this class. The parameter is an array. Value =" This parameter is meaningless and will not be displayed on the UI, so you do not need to configure "description =" Basic user information operation".Copy the code

2, @apiOperation () : used for a method, representing an HTTP request to access the operation of the method

Parameters:

Value =" Method purpose and function "Notes =" method notes and remarks" tags: describes the function of this method. Format: tags={" effect 1"," effect 2"}Copy the code

3, @apiModel () : used in response to the entity class, used to explain the role of the entity

Parameters:

Description =" Describe the function of the entity"Copy the code

4. @APIModelProperty: Used on attributes to describe the attributes of the entity class

Parameters:

Value =" User name" Description Parameter Meaning Name = Variable name of the parameter required=true Specifies whether this parameter is mandatoryCopy the code

5. @ApiIMPLICITParams: used in the request method, including @apiIMPLicitParam

6. @apiIMPLICITParam: Used for methods that represent separate request parameters

Parameters:

Name =" parameter Ming "value=" parameter description" dataType=" dataType "paramType="query" specifies where the parameters are stored. @requestParam · Path (for restful interfaces) Request parameters: @pathvariable · body (not used) · form (not used) defaultValue=" the defaultValue of the parameter "required="true" indicates whether the parameter must be passedCopy the code

7, @apiparam () : used for methods and parameters. Field description indicates the requirements and description of parameters

Parameters:

Name =" parameter name "value=" brief description of the parameter" defaultValue=" parameter defaultValue "required="true" indicates whether the attribute is mandatory. The default is falseCopy the code

8. @ApiResponses: Used in the method of request to represent different responses according to the response code

An @ApiResponses contains multiple @ApiResponses

9, @apiResponse: used in the request method to indicate different responses

Parameters:

Code ="404" indicates the response code (int). You can customize message=" response message corresponding to the status code ".Copy the code

@apiignore () : used on classes or methods and not displayed on the page

11, @profile ({“dev”, “test”}) : used on configuration classes, indicating only useful for development and test environments

Code comment examples

/** * Swagger */
@RestController
@RequestMapping("/api/common")
@Api(value = "Swagger demonstration", tags = "Some notes to demonstrate Swagger.")
public class TestController {


    @ApiOperation(value = "Change user password", notes = "Change password based on user ID", authorizations = {@Authorization("sessionId")})
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "password", value = "Old password", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "newPassword", value = "New password", required = true, dataType = "String")})@RequestMapping(value = "/updatePassword.json", method = RequestMethod.POST)
    public String updatePassword(HttpServletRequest request, String password, String newPassword) {

        if (password.equals(newPassword)) {
            return "Old and new passwords cannot be the same.";
        }
        return "Password changed successfully!";
    }

    @ApiOperation(value = "Save user information", notes = "Save user information")
    @RequestMapping(value = "/test.json", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 5000001, message = "Parameter error")})
    public Result<String> saveUserInfo(Test test) {
        Test t = new Test();
        Paramap t1 = Paramap.create().put("t", t);
        returnResult.jsonStringOk(t); }}Copy the code
@ApiModel(description = "Test data")
public class Test {
    / * * name * /
    @ApiModelProperty(value = "Name", required = true)
    private String name;

    /** Contact mobile */
    @ApiModelProperty(value = "Contact cell phone", required = true)
    private String telephone;

    /** 头像 */
    @ApiModelProperty(value = "Avatar", required = true)
    private String avatar;

    /** Gender 1, male 2, female */
    @ApiModelProperty(value = "Sex 1, male 2, female", required = true)
    private Integer sex;
}
Copy the code

Generate PDF or HTML documents from JSON data

Step (Method 1)

1. Modify the swaggerJSON data access path under swaggerInput in POM. XML

2. Run the plug-in Swagger2Markup to generate asciidoc documents and run the plug-in Asciidoctor to generate PDF documents

Document preview

Generate github links for documents

Learn Swagger’s Github link