Use Swagger2 to build robust RESTful API documentation in 3.Spring boot

Source: Internet
Author: User

Original: Http://www.jianshu.com/p/8033ef83a8ed

Thanks to the fast development and ease of deployment of spring boot, it is believed that a large part of Spring boot users will be used to build restful APIs. The purpose of building restful APIs is often due to multiple terminals, which share many of the underlying business logic, so we abstract this layer to serve multiple mobile or web front ends.

As a result, our RESTful API is likely to face multiple developers or multiple development teams: iOS development, Android development, or Web development. To reduce the cost of frequent communication with other teams during development, we create a RESTful API document that records all of the interface details, but there are several issues with this approach:

    • Because of the numerous interfaces and the complexity of the details (different HTTP request types, HTTP header information, HTTP request content, and so on), creating the document in its own high quality is a very difficult thing to do and the downstream complaints are heard.
    • As time goes by, the interface document must be modified synchronously while the interface is being modified, and the document and code are in two different mediums, which can easily lead to inconsistencies unless there is a strict management mechanism.

To solve this problem, this article introduces the Swagger2 partner of the RESTful API, which can easily be integrated into spring boot and organize a robust RESTful API document with the Spring MVC program. It can reduce the amount of time we create a document, as well as the integration of the content into the implementation code, so that the maintenance document and the modified code are integrated, allowing us to modify the code logic and easily modify the document description. In addition, SWAGGER2 provides powerful page testing capabilities to debug each restful API. The exact effect is as shown:


alt=

Here's how to do this if you use Swagger2 in spring boot. First, we need a RESTful API project that spring boot implements, and if you haven't done that, it's recommended to read
Spring Boot builds a more complete restful APIs and unit tests.

Below we will take the tutorial example of the chapter3-1-1 to carry out the following experiment (CHPATER3-1-5 is our results engineering, also refer to).

Add Swagger2 Dependency

pom.xmljoin Swagger2 in the dependency

<Dependency><Groupid>io.springfox</Groupid><Artifactid>springfox-swagger2</artifactid> < version>2.2.2</version></dependency>< dependency> <groupId> Io.springfox</groupid> <artifactid>springfox-swagger-ui</ artifactid> <version>2.2.2</< Span class= "Hljs-name" >version></DEPENDENCY>   
Creating the Swagger2 Configuration class

Application.javaCreate a configuration class for Swagger2 at the sibling Swagger2 .

@Configuration@EnableSwagger2PublicClassSwagger2 {@BeanPublic Docketcreaterestapi () {return new Docket (documentationtype.swagger_2). Apiinfo (Apiinfo ()). Select (). APIs ( Requesthandlerselectors.basepackage ( "Com.didispace.web"). Paths (Pathselectors.any ()) . build (); } private apiinfo apiInfo () {return new Apiinfobuilder (). Title ( Span class= "hljs-string" > "Spring boot uses Swagger2 to build restful APIs"). Description ( "more Spring Boot related articles please pay attention to: http://blog.didispace.com/"). Termsofserviceurl ("/http " blog.didispace.com/"). Contact (" program ape DD "). Version (" 1.0 "). Build (); }}

As shown in the code above, with @Configuration annotations, let spring load the class configuration. The annotations are then @EnableSwagger2 enabled for Swagger2.

After the createRestApi Bean is created by the function Docket , apiInfo() It is used to create basic information about the API (these basic information is present in the document page). The select() function returns an ApiSelectorBuilder instance used to control which interfaces are exposed to swagger, and this example is defined by the packet path of the specified scan, and swagger scans all the controller-defined APIs under the package and produces the document content (in addition @ApiIgnore to the specified request).

Add Document Content

After completing the above configuration, can actually produce the document content, but such a document mainly for the request itself, and the description is mainly derived from functions such as naming, not user-friendly, we usually need to add some instructions to enrich the content of the document. As shown below, we use annotations to add instructions @ApiOperation , pass, and annotations to the API to add descriptions to the @ApiImplicitParams @ApiImplicitParam parameters.

@RestController@RequestMapping (value="/users")This configuration allows the following mappings to be/users, removingPublicClassUsercontroller {Static Map<long, user> users = Collections.synchronizedmap (New Hashmap<long, user> ());@ApiOperation (value="Get user list", notes="")@RequestMapping (value={""}, Method=requestmethod.get)Public list<user>Getuserlist() {list<user> r =New Arraylist<user> (Users.values ());return R; }@ApiOperation (value="Create User", notes=Create user according to user object)@ApiImplicitParam (name ="User", value ="User detail entity", required =True, DataType ="User")@RequestMapping (value="", Method=requestmethod.post)Public StringPostuser(@RequestBody user user) {Users.put (User.getid (), user);Return"Success"; }@ApiOperation (value="Get user Details", notes="Get user details based on the ID of the URL")@ApiImplicitParam (name ="id", value ="User ID", required =True, DataType ="Long")@RequestMapping (value="/{id}", Method=requestmethod.get)Public UserGetUser(@PathVariable Long ID) {return Users.get (ID); }@ApiOperation (value="Update user Details", notes="Specifies the update object based on the ID of the URL, and updates the user details based on the data passed to it")@ApiImplicitParams ({@ApiImplicitParam (name ="id", value ="User ID", required =True, DataType ="Long"),@ApiImplicitParam (name ="User", value ="User detail entity", required =True, DataType ="User")})@RequestMapping (value="/{id}", Method=requestmethod.put)Public StringPutuser(@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";}  @ApiOperation (Value= "delete User", Notes= " Specify the Delete object according to the ID of the URL  @ApiImplicitParam (name =  "id", value =  "User ID", required = true, DataType =  "Long")  @RequestMapping (Value= "/{id}", Method=requestmethod.delete) Span class= "hljs-function" >public String deleteuser (@PathVariable Long id) {users.remove (ID); return  "Success";}}       

Complete the above code additions, start the Spring boot program, visit: http://localhost:8080/swagger-ui.html
。 You can see the page of the RESTful API shown earlier. We can then open the specific API request, taking the/users request of post type as an example, we can find the notes information we configured in the above code and the description information of the parameter user as shown in.


Altapi Document access and debugging

On the requested page, we see that user's value is an input box? Yes, swagger in addition to the view interface function, but also provides debugging testing function, we can click on the right side of the model Schema (yellow area: It indicates the user's data structure), at this point in the value of the User object template, we only need to modify, click below “Try it out!”button to complete a request call!

At this point, you can also verify that the previous post request is correct by several get requests.

Compared to the work of writing documents for these interfaces, our added configuration content is very small and streamlined, and the intrusion into the original code is within the scope of tolerance. Therefore, it is a good choice to add swagger to manage API documents while building restful APIs.

Use Swagger2 to build robust RESTful API documentation in 3.Spring boot

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.