Swagger is briefly

Swagger is a normative 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 in sync

Spring Boot integrates Swagger

Project involved in this article: Swagger

Pom.xml Swagger requires the following JAR to be imported

<! Springfox </groupId> <artifactId> Springfox - Swagger2 </artifactId> < version > 2.2.2 < / version > < / dependency > < the dependency > < groupId >. IO springfox < / groupId > < artifactId > springfox swagger - UI < / artifactId > < version > 2.2.2 < / version > < / dependency >Copy the code

@enablesWagger2 Use the @enablesWagger2 annotation to swagger functionality on the Control class

@restController @enablesWagger2 // Start Swagger annotation // api-value: Defines the name, if not defined, the default display class name @api (value ="Swagger Test Control", description = "Control class to demonstrate Swagger usage", tags = "Swagger Test Control Tag")
public class SwaggerTestCtl {
..
}
Copy the code

Start as an executive director start class, visit the following link http://127.0.0.1:8080/swagger-ui.html#/ you can enter the page of swagger, testing of interface, the interface is as follows:

ApiInfo class

We create ApiInfo instances, and we configure more interface specifications for Swagger

@Bean
public Docket api() {
	return new Docket(DocumentationType.SWAGGER_2)
		.apiInfo(getApiInfo())
		// .pathMapping("/"Select () //.paths(Predicates. Or (PathSelectors. Regex)"/api/.*"))) / / filter interface. The apis (RequestHandlerSelectors. BasePackage ("com.hry.swagger.ctl"Paths (PathSelectors. Any ()).build(); } private ApiInfogetApiInfo() {// Define Contact information Contact Contact = new Contact("hryou0922"."https://github.com/hryou0922"."[email protected]");
	return new ApiInfoBuilder()
		.title("Demonstrate Swagger."// title.description ("Demonstrate the use of various notes in Swagger.") // Description.version(1.1.2 ""// // version. license("Apache 2.0")
		.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
		.contact(contact)
		.build();
}
Copy the code

To restart the service, the following interface is displayed:

Swagger annotations

An overview of Swagger’s notes

We can use Swagger to define a more detailed interface specification

@Api: used on a class to indicate that this class is Swagger resource Value: Interface description Tags: interface description, which can be displayed on the page. You can configure multiple interfaces. When multiple interfaces are configured, information about multiple interfaces is displayed on the page. @APIIMPLICITParam: Defines the details of a single parameter in the @APIIMPLicitParams annotation. ○ paramType: specifies where the parameter is placed § Header --> Request parameter fetch: @requestParam § Path (for restful interfaces) --> RequestParam § Path (for restful interfaces) @PathVariable § Body (Only POST is supported when a stream is submitted) § Form (only POST is supported when a form is submitted) ○ Name: parameter name ○ dataType: § Long § String ○ required: whether the parameter must be passed § true § false ○ value: the meaning of the parameter ○ defaultValue: the defaultValue of the parameter @apimodel: @APIModelProperty: Add attribute description to the attributes of the Model class @APIParam: @apiResponses: wrapper: contains a list of multiple ApiResponse objects @APIResponse: defined in the @apiResponses annotation, generally used to describe an error response message Error code, for example, 400 ○ Message: message, for example, "Request parameters are not filled in" ○ Response: @authorization Declares an Authorization scheme to be used on a resource or an operation. @authorizationScope Declares a greater immediacy for raising exceptions Describes an OAuth2 authorization scope.Copy the code

In this section we will show you how to use the ###@Api annotation on a class to mark this class as a Swagger resource

@restController @enablesWagger2 // Start Swagger annotation @api (value ="Swagger Test Control", description = "Control class to demonstrate Swagger usage", tags = "Swagger Test Control Tag")
public class SwaggerTestCtl {

}
Copy the code

The results are as follows:

###@ApiOperation is used to describe the function of a method

@apiOperation (value = value"Get records by ID", response = student.class) // Define the request parameter @apiIMPLICITParams ({@apiIMPLICITParam (paramType ="query", dataType = "String", name = "id", value = "Primary key", required = true) })
public Student queryById(String id){
    System.out.println("queryById id = " + id);
    return new Student();
}
Copy the code

The results are as follows:

@ ApiImplicitParams and @ ApiImplicitParam

// Define the request parameter @apiIMPLICITParams ({@apiIMPLICITParam (paramType =)"query", dataType = "String", name = "id", value = "Primary key", required = true) })
public Student queryById(String id){
   System.out.println("queryById id = " + id);
   return new Student();
}

Copy the code

The results are as follows:

# # # @ ApiModel and @ ApiModelProperty

Define the model class

@ApiModel( description = "Students")
public class Student {
    @ApiModelProperty(value = "The primary key id")
    private String id;
    @ApiModelProperty(value = "Name", required = true)
    private String name;
    @ApiModelProperty(value = "Age", required = true) private int age; ... }Copy the code

In method use

@RequestMapping(value = "/update", method = {requestmethod.post}) // @apiOperation (value ="Add Student Records", notes="Passing complex object DTOS",produces = "application/json")
public int update(@RequestBody Student student){
    System.out.println("update student = " + student);
    return 1;
}
Copy the code

The results are as follows:

@ ApiResponses and @ ApiResponse

@RequestMapping(value = "/del", method = {requestmethod. POST, requestmethod. GET}) @apiOperation (value ="Delete student Records Student records"@apiresponses ({@apiResponse (code = 400, message ="Internal server exception"),
        @ApiResponse(code = 500, message = "Insufficient authority") })
public int del(int id){
    System.out.println("del id = " + id);
    return 1;
}  
Copy the code

The results are as follows:

other

During the test, if the interface content is not refreshed, you can use Shift + F5 to refresh the interface forcibly

code

Please use tag V0.22 instead of master as I can’t guarantee that the master code will always be the same