Use Swagger2 to build robust RESTful API documentation in Spring boot

Source: Internet
Author: User

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 complex 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

1234567891011 <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</version> </dependency>
Creating the Swagger2 Configuration class

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

1234567891011121314151617181920212223242526 @Configuration@EnableSwagger2public class Swagger2 { @Bean public Docket Createrestapi() { 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 ("using Swagger2 to build restful APIs in Spring Boot"). Description ("more Spring Boot related articles please follow: 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 to being @ApiIgnore 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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 @RestController@RequestMapping (value="/users") //through This configuration so that the following mappings are under/users, can be removed public class Usercontroller { 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 based on user Object") @ApiImplicitParam (name = "user", value = "subscriber Detail entity user", required = true, DataType = " username") @RequestMapping (value="", method=requestmethod.post) public String postuser(@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 User getUser(@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 passed user Information.") @ApiImplicitParams ({ @ApiImplicitParam (name = "id", value = "user id", required = true, DataType = "Long"), @ApiImplicitParam (name = "user", value = "subscriber Detail entity user", required = true, DataType = " username") })@RequestMapping (value="/{id}", method=requestmethod.put) 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"; }@ApiOperation (value="delete user", notes="specify Delete object based on URL Id") @ApiImplicitParam (name = "id", value = "user id", required = true, DataType = "Long") @RequestMapping (value="/{id}", Method=requestmethod.delete) 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.

Alt

API documentation 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.

A complete example of the results can be viewed chapter3-1-5.

Reference information
      • Swagger official website

http://blog.didispace.com/springbootswagger2/

Use Swagger2 to build robust RESTful API documentation in 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.