Spring Boot Learning Note-Integrate Swagger2 to automatically generate RESTful API documentation

Source: Internet
Author: User
Tags documentation

In the app backend development often need to provide a RESTful API interface for mobile clients (Android, IOS), in the late version of the rapid iterative process, the implementation of the interface must be modified synchronously modify the interface document, and the document and code in two different media, unless there is a strict management mechanism, Otherwise, it is easy to cause the code to be inconsistent with the interface document.

This article introduces the Swagger2 partner of the RESTful API, which can easily be integrated into the spring ecosystem and organize a robust RESTful API document with the Spring MVC program. It allows us to reduce the amount of documentation we create, while incorporating the description into the implementation code to integrate the maintenance and modification code so that we can easily modify the document description while modifying the code logic. Swagger2 also provides powerful page testing capabilities to debug each restful API, as shown in the following figure:

Spring Boot Integration Swagger2 1. Add Swagger2 dependency

Adding Swagger2 dependencies to Pom.xml

<!--swagger2-->
<dependency>
  <groupId>io.springfox</groupId>
  < artifactid>springfox-swagger2</artifactid>
  <version>2.6.1</version>
</ dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId> springfox-swagger-ui</artifactid>
  <version>2.6.1</version>
</dependency>
2. Write Swagger2 Configuration Class

The

Class name is arbitrary, but you need to add @enableswagger2 and @configuration annotations as follows:

Package Com.bytebeats.springboot.ch2.swagger;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import Springfox.documentation.builders.ApiInfoBuilder;
Import springfox.documentation.builders.PathSelectors;
Import springfox.documentation.builders.RequestHandlerSelectors;
Import Springfox.documentation.service.ApiInfo;
Import Springfox.documentation.service.Contact;
Import Springfox.documentation.spi.DocumentationType;
Import Springfox.documentation.spring.web.plugins.Docket;

Import Springfox.documentation.swagger2.annotations.EnableSwagger2;  /** * ${description} * * @author Ricky Fung * @create 2017-01-02 23:53 * * @EnableSwagger2 @Configuration public class
                Swagger2config {@Bean public Docket Createrestapi () {return new docket (documentationtype.swagger_2) . Apiinfo (Apiinfo ()). Select ()//is the current package path. APIs (requesthandlers Electors.basepackage ("Com.bytebeats.springboot.ch2.controller"). Paths (Pathselectors.any ()). build ();
                }//Build API documentation for more information function private Apiinfo apiinfo () {return new Apiinfobuilder ()//page title . Title ("Spring Boot test uses Swagger2 to build restful APIs")//Creator. Contact ("Ric
                KY "," http://www.bytebeats.com "," ricky_feng@163.com "))//version number. Version (" 1.0 ")
    Description. Description ("API description"). Build ();
 }
}

With @configuration annotations, let spring load the class configuration, @EnableSwagger2 annotations to enable Swagger2.

Once the docket bean has been created through the CREATERESTAPI function, Apiinfo () is used to create the basic information for the API (these basic information is present in the document page). The Select () function returns a Apiselectorbuilder instance that controls which interfaces are exposed to swagger, and this example is defined by the package path of the specified scan, and swagger scans all the controller-defined APIs under the package. and produce the document content (in addition to the API that is annotated by @apiignore). 3. Write Controller

Here you start writing your own restful Controller, which is no different from normal development. The main interface method is the addition of several annotations: Add instructions to the API by @apioperation annotations by @apiimplicitparams, @ApiImplicitParam annotations to the parameters. Ignoring interfaces that don't want to generate RESTful API documentation through @apiignore

The Usercontroller code is as follows:

Package Com.bytebeats.springboot.ch2.controller;
Import Com.bytebeats.springboot.ch2.domain.User;
Import Io.swagger.annotations.ApiImplicitParam;
Import Io.swagger.annotations.ApiImplicitParams;
Import io.swagger.annotations.ApiOperation;
Import org.springframework.web.bind.annotation.*;

Import Springfox.documentation.annotations.ApiIgnore;
Import java.util.ArrayList;

Import java.util.List; /** * ${description} * * @author Ricky Fung * @create 2017-01-02 23:41 */@RestController @RequestMapping ("/demo") pu Blic class Usercontroller {@ApiOperation (value= "Create user", notes= "create user according to User object") @ApiImplicitParams ({@A
            Piimplicitparam (DataType = "Java.lang.Long", name = "id", value = "id", required = true, Paramtype = "path"), @ApiImplicitParam (DataType = "User", name = "User", value = "subscriber Information", required = True)}) @RequestMapping (value = "/

   User/{id} ", method = requestmethod.post) public User Insert (@PathVariable Long ID, @RequestBody user user) {     SYSTEM.OUT.PRINTLN ("ID:" +id+ ", User:" +user);

        User.setid (ID);
    return user; } @ApiOperation (value= "Get the specified ID user details", notes= "get user details based on userid") @ApiImplicitParam (name = "id", value = "User ID", D Atatype = "String", Paramtype = "path") @RequestMapping (value = "/user/{id}", method = requestmethod.get) public U
        Ser GetUser (@PathVariable Long ID) {User user = new User ();
        User.setid (ID);
        User.setpassword ("abc");
        User.setusername ("12345");
    return user; } @ApiOperation (value= "Get all User Details", notes= "Get user list Information") @RequestMapping (value = "/users", method = Requestmethod.ge
        T) public list<user> getuserlist () {list<user> List = new arraylist<> ();
        User user = new user ();
        User.setid (15L);
        User.setpassword ("Ricky");

        User.setusername ("root");

        List.add (user);
    return list; } @ApiIgnore @ApiOperation (value= "Remove the specified ID user", notes= "by ID to deleteIn addition to the user Information ") @ApiImplicitParam (name =" id ", value =" User id ", DataType =" Java.lang.Long ", Paramtype =" path ") @RequestMap Ping (value = "/user/{id}", method = requestmethod.delete) public String DELETE (@PathVariable Long id) {System.
        Out.println ("Delete User:" +id);
    return "OK";
 }
}

After completing the above code, package the spring boot program and start, open the browser access: http://localhost:8080/swagger-ui.html, you can see the previous article shows the RESTful API page.




Source Download

Click here to download Source: https://github.com/TiFG/spring-boot-in-action

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.