swagger spring-boot 配置

Source:  https://www.cnblogs.com/xiaohanghang/p/6018654.html

Since the Spring Boot to rapidly develop, deploy and convenient features such as, I believe a large part of Spring Boot users will be used to build RESTful API. Moreover, the purpose are usually constructed RESTful API reasons due to multipath terminal, these terminals may share many of the underlying business logic, so we will abstract layer simultaneously serving a plurality of mobile Web or distal end.

As a result, our RESTful API is likely to face more than one developer or multiple development teams: IOS developers, Android developers or Web development. In order to reduce frequent communication with other teams usually costs during development, we will create a traditional practice RESTful API documentation to record all the details of the interface, however, this approach has several problems:

  • As many interfaces, and details of the complex (need to consider the different types of HTTP requests, HTTP headers, the HTTP request content, etc.), to create high-quality documents this in itself is a very difficult thing, grumbling downstream prevalent.
  • Over time, constantly revised interface must be synchronized at all times to modify the interface documents, and documents with two different codes but also in the media, unless there is a strict management mechanism, otherwise easily lead to inconsistencies.

In order to solve this problem above, this article will introduce heavy good partner RESTful API's Swagger2, it can be easily integrated into Spring Boot in, and with Spring MVC program with a strong organization RESTful API documentation. It can reduce the amount of work we created the document, while the description content and integrated into implementation code, modify the code so that maintenance documentation and integrated into one, allows us to easily modify documentation at the same time to modify the code logic. In addition Swagger2 page also provides a powerful test capabilities to debug each RESTful API. Specific results as shown below:

The following specifically describes the use of Swagger2 if Spring Boot. First, we need a Spring RESTful API project Boot to achieve, if you have not done this type of content, we recommend that you read
Spring Boot to build a more complex RESTful APIs and unit testing .

Here's what we will tutorial sample following experiment (Chpater3-1-5 is the result of our project, also reference) in Chapter3-1-1.

Add Swagger2 dependence

In pom.xmladding dependent Swagger2

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

Creating Swagger2 configuration class

In the Application.javacreation Swagger2 configuration class at the same level Swagger2.

Copy the code
 1 @Configuration
 2 @EnableSwagger2
 3 public class Swagger2 {
 4     @Bean
 5     public Docket createRestApi() {
 6         return new Docket(DocumentationType.SWAGGER_2)
 7                 .apiInfo(apiInfo())
 8                 .select()
 9                 .apis(RequestHandlerSelectors.basePackage("com.didispace.web"))
10                 .paths(PathSelectors.any())
11                 .build();
12     }
13     private ApiInfo apiInfo() {
14         return new ApiInfoBuilder()
15                 .title("Spring Boot中使用Swagger2构建RESTful APIs")
16                 .description("更多Spring Boot相关文章请关注:http://blog.didispace.com/")
17                 .termsOfServiceUrl("http://blog.didispace.com/")
18                 .contact("程序猿DD")
19                 .version("1.0")
20                 .build();
21     }
22 }
Copy the code

As shown in the code, by @Configurationannotation, to let Spring load the class configuration. By then @EnableSwagger2enable Swagger2 comment.

Through the createRestApifunction creates Docketafter Bean's, apiInfo()used to create the basic information of the Api (basic information exhibition now pages of the document). select()Function returns an ApiSelectorBuilderinstance of an interface which is used to control exposure to Swagger to show, using the designated scan path package according to the present embodiment is defined, Swagger scans all Controller API defined in this packet, and generates a document content (in addition to being @ApiIgnorespecified by the request).

Adding Document Content

After completion of the above configuration, in fact, can produce content of the document, but this document is a request for itself, and describes the main functions, and so named from produce, not user-friendly, we usually need to add some instructions to own content-rich documents . As shown below, we have by @ApiOperationincreasing the annotation to the API, through @ApiImplicitParams, @ApiImplicitParamannotations parameter increases to be described.

Copy the code
@RestController. 1 
 2 @RequestMapping (value = "/ Users") // here by making the following mapping are disposed at / users, can be removed 
 . 3 the UserController {public class 
 . 4 static the Map <Long, the User> Users the Collections.synchronizedMap = ( the HashMap new new <Long, the user> ()); 
 . 5 @ApiOperation (value = "list of users", Notes = "") 
 . 6 @RequestMapping ({value = ""}, = RequestMethod.GET Method) 
 . 7 public list <the user > getUserList () { 
 . 8 List <user> = R & lt new new the ArrayList <user> (users.values ()); 
 . 9 return R & lt; 
10} 
. 11 @ApiOperation (value = "Create user", notes = "user object created according to the user ") 
12 is @ApiImplicitParam (name =" user ", value =" user Details entity user ", required = true, dataType =" user ")
13     @RequestMapping(value="", method=RequestMethod.POST)
Public String postUser 14 (the User User @RequestBody) { 
15 users.put (user.getId (), User); 
16 return "Success"; 
. 17} 
18 is @ApiOperation (value = "get user details", notes = "The url id of the user to obtain detailed information ") 
. 19 @ApiImplicitParam (name =" id ", value =" user ID ", required = to true, dataType =" Long ") 
20 is @RequestMapping (value =" / {id} ", = RequestMethod.GET Method) 
21 is the user public the getUser (Long @PathVariable ID) { 
22 is return users.get (ID); 
23 is} 
24 @ApiOperation (value = "user details update", notes = "specified in terms of id url update the object, and updates the user according to user information details pass over ") 
25 @ApiImplicitParams ({ 
26 is @ApiImplicitParam (name =" ID ",value = "用户ID", required = true, dataType = "Long"), 
27 @ApiImplicitParam (name =" user ", value =" user Details entity user ", required = true, dataType ="User")
28     })
29     @RequestMapping(value="/{id}", method=RequestMethod.PUT)
30     public String putUser(@PathVariable Long id, @RequestBody User user) {
31         User u = users.get(id);
32         u.setName(user.getName());
33         u.setAge(user.getAge());
34         users.put(id, u);
35         return "success";
36     }
37     @ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
38     @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
39     @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
40     public String deleteUser(@PathVariable Long id) {
41         users.remove(id);
42         return "success";
43     }
44 }
Copy the code

On completion of the above code is added to start the Spring Boot program, visit: HTTP: // localhost: 8080 / Swagger-ui.html
. You will be able to see the page previously displayed RESTful API's. We can then opening a specific API request to / users POST request type as an example, the parameters can be found in Notes user information and code information in the description of our configuration, as shown in FIG.

 

                                                                    

API documentation and debugging access

In view of the request on the page, we see a user's Value input box? Yes, Swagger addition to viewing the interface functions, but also provides a debugging test function, we can click on the Model Schema to the right of the image above (yellow area: it indicates the data structure of the User), this time there will be a user object in Value template, we only need a little appropriate changes, click the bottom “Try it out!”button, to complete a request to call!

At this point, you can verify before the POST request is correct by several GET requests.

Compared to the work of these interfaces written document, we increase the configuration content is very small and streamlined, the code for the original invasion also stand within range. Therefore, while building RESTful API, adding swagger to manage the API documentation, it is a good choice.

Examples of complete results can be viewed Chapter3-1-5 .

Guess you like

Origin www.cnblogs.com/whm-blog/p/10972123.html