Spring Boot 2.x Basics Tutorial: Using Swagger2 build powerful API documentation

With the separation of the front and rear end of the popular architecture and micro-architecture services, we use Spring Boot RESTful API project to build a scene more and more. Usually we are a RESTful API is likely to serve a number of different developers or development teams: IOS developers, Android developers, Web developers and even other back-end services. In order to reduce communication costs usually frequent during development, the traditional approach is to create a RESTful API documentation and other teams 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 our own starter implemented in Spring Boot in to integrate Swagger. The project's Github Integration: https://github.com/SpringForAll/spring-boot-starter-swagger . If you find it easy to use, welcomed the Star support us!

Ready to work

First, we need a Spring RESTful API project Boot to achieve, if you have not done this type of content, we recommend you read the tutorial:
the Spring 2.x Boot Basics Tutorial: Building a RESTful API unit tests construct a. Alternatively, the sample can be used directly as a tutorial on the basis that the following warehouse chapter2-1project:

Integration Swagger2

Here, above our warehouse chapter2-1to integrate renovation project.

The first step : Add swagger-spring-boot-starter dependent

In pom.xmladdition of dependencies, as follows:

<dependency>
    <groupId>com.spring4all</groupId>
    <artifactId>swagger-spring-boot-starter</artifactId>
    <version>1.9.0.RELEASE</version>
</dependency>

Step : Main Class adding @EnableSwagger2Docannotations, as follows

@EnableSwagger2Doc
@SpringBootApplication
public class Chapter22Application {

    public static void main(String[] args) {
        SpringApplication.run(Chapter22Application.class, args);
    }

}

The third step : application.propertiesconfigure document-related content, such as

swagger.title=spring-boot-starter-swagger
swagger.description=Starter for swagger 2.x
swagger.version=1.4.0.RELEASE
swagger.license=Apache License, Version 2.0
swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html
swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger
swagger.contact.name=didi
swagger.contact.url=http://blog.didispace.com
[email protected]
swagger.base-package=com.didispace
swagger.base-path=/**

Each of the parameters the following meanings:

  • swagger.title:title
  • swagger.description:description
  • swagger.version:version
  • swagger.license:license
  • swagger.licenseUrl: License URL
  • swagger.termsOfServiceUrl: Terms of Service URL
  • swagger.contact.name:v'vd
  • swagger.contact.url: Maintainer URL
  • swagger.contact.email: Maintainer email
  • swagger.base-package: Base package swagger scanning, default: Full scan
  • swagger.base-path: URL regular basis need to be addressed, default: / **

More configuration instructions visible official description: https://github.com/SpringForAll/spring-boot-starter-swagger

Step Four : Start the application, visit: http://localhost:8080/swagger-ui.htmlyou can see the following interface documentation page:

Adding Document Content

After completion of the integration Swagger, in http://localhost:8080/swagger-ui.htmlmay see the page, the description of each interface are in English also follow the name or code defines generated. These are not user-friendly content, so we need to add some instructions to their own rich content of the document. As shown below, by us @Api, @ApiOperationannotations increase instructions to the API, through @ApiImplicitParam, @ApiModel, @ApiModelPropertyannotations parameter increases to FIG.

Such as the following examples:

@Api(tags = "用户管理")
@RestController
@RequestMapping(value = "/users")     // 通过这里配置使下面的映射都在/users下
public class UserController {

    // 创建线程安全的Map,模拟users信息的存储
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<>());

    @GetMapping("/")
    @ApiOperation(value = "获取用户列表")
    public List<User> getUserList() {
        List<User> r = new ArrayList<>(users.values());
        return r;
    }

    @PostMapping("/")
    @ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
    public String postUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    @PutMapping("/{id}")
    @ApiImplicitParam(paramType = "path", dataType = "Long", name = "id", value = "用户编号", required = true, example = "1")
    @ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
    public String putUser(@PathVariable Long id, @RequestBody User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象")
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }

}

@Data
@ApiModel(description="用户实体")
public class User {

    @ApiModelProperty("用户编号")
    private Long id;
    @ApiModelProperty("用户姓名")
    private String name;
    @ApiModelProperty("用户年龄")
    private Integer age;

}

After the above code is added, start the program Spring Boot, visit: http://localhost:8080/swagger-ui.html, you can see with the Chinese document follows the description (which indicated the correspondences between the elements of the document with annotations by reference):

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 the API document management, it is a good choice.

The sample code

The complete works of this paper can be viewed below repository chapter2-2directory:

If you think this article is good, welcome Starsupport, your concern is I insist on the power!

I welcome the attention of the public number: Program ape DD, get exclusive organize learning resources and push dry goods daily. If you are interested in my topic content, you can focus on my blog: didispace.com

Guess you like

Origin www.cnblogs.com/didispace/p/11611193.html