Share a REST APIs document Framework swagger and apisswagger integrated in the project

Source: Internet
Author: User

Share a REST APIs document Framework swagger and apisswagger integrated in the project

1. Why is swagger used?

1-1 when a background developer develops an interface, do they need to re-write an interface document and submit it to the front-end developer, of course, what programmers do not like most is to write documents (of course, documents are necessary and conducive to project maintenance)

1-2 when the background staff Develop interfaces, of course, the background developers also need to test whether the interfaces are available. When there are fewer parameters, the test is not very troublesome. When there are more than 10 parameters, the backend developers need to splice parameters one by one, which is time-consuming and easy to write the wrong parameter name. swagger can solve this problem very well (of course, it can also use other plug-ins: rest-client tool, postMan)

2 Build Environment: window, spring boot, swaager, maven

3. Start building: the building process is very simple. This article does not elaborate on swagger annotations. In fact, it is okay to use only a few commonly used annotations (@ ApiOperation, @ EnableSwagger2, @ Api)

3-1 import the required jar package and modify pom. xml

<dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>            <version>RELEASE</version>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-aop</artifactId>        </dependency>        <!-- swagger -->        <dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox-swagger-ui</artifactId>            <version> 2.6.0</version>        </dependency>        <dependency>            <groupId>io.springfox</groupId>            <artifactId>springfox-swagger2</artifactId>            <version> 2.6.0</version>        </dependency>        <!-- swagger end -->

3-2 configure swagger

@ Configuration @ EnableSwagger2 // swagger annotation public class SwaggerConfig {@ Bean public Docket allInterface () {return new Docket (DocumentationType. SWAGGER_2 ). groupName ("AllInterface (all interfaces)") // defines a group. select () // select the paths and APIs to generate the document. apis (RequestHandlerSelectors. basePackage ("com. lishun. controller ") // the path of the intercepted package. paths (regex ("/. * ") // blocked interface path. build () // create. apiInfo () // configuration description. tags (new Tag ("index", "start page"), getTags ();}/*** @ Description: you can specify other tags (corresponding to the tags attribute value of controller @ Api annotation) * @ author lishun * @ date 2018/2/28 * @ param [] * @ return springfox.doc umentation. service. tag [] */private Tag [] getTags () {Tag [] tags = {new Tag ("login", "Logon related")}; return tags ;} private ApiInfo apiInfo () {return new ApiInfoBuilder ()//. title ("swagger api documentation") // title. description ("swagger api documentation") // description. termsOfServiceUrl ("")//. contact (new Contact ("", "", "") // contact. version ("1.0") // version. build ();}}

3-3 unify the return values of all interfaces (facilitating front-end staff development and handling controller exceptions in a unified manner)

Public class ResultBean <T> implements Serializable {/* message */public String message = "";/* Status code */public Integer code; /* total page number */private long totalPage;/* page size */private int pages;/* page number */private int pageNum;/* returns entity information */private T resultData; /* returns the collection object information */private List <T> resultDataList; public ResultBean () {} public ResultBean (List <T> resultData, long totalPage, int pages, int pageNum) {this. resultDataList = resultData; this. totalPage = totalPage; this. pages = pages; this. pageNum = pageNum;} public ResultBean (T resultData) {this. resultData = resultData;} public void setMessage (String message) {this. message = message;} public long getTotalPage () {return totalPage;} public void setTotalPage (long totalPage) {this. totalPage = totalPage;} public int getPages () {return pages;} public void setPages (int pages) {this. pages = pages;} public int getPageNum () {return pageNum;} public void setPageNum (int pageNum) {this. pageNum = pageNum;} public List <T> getResultDataList () {return resultDataList;} public void setResultDataList (List <T> resultDataList) {this. resultDataList = resultDataList;} public void setMessage (String message, Object... args) {this. message = String. format (message, args);} public String getMessage () {return message;} public void setResultData (T resultData) {this. resultData = resultData;} public T getResultData () {return this. resultData;} public Integer getCode () {return code;} public void setCode (Integer code) {this. code = code;} public <T> void setResultBean (Integer code, String message, Object... mesaageFormatArgs) {setCode (code); setMessage (message, mesaageFormatArgs );}}

3-4 Handling controller exceptions in a unified manner

/*** @ Author lishun * @ Description: controller aop interception * @ date expires /10/27 */@ Component @ Aspectpublic class ControllerAspect {@ Pointcut ("execution (public com. lishun. result. resultBean com. lishun. controller. *. *(..)) ") public void dataSource () {}; @ Around (" dataSource () ") public Object doAround (ProceedingJoinPoint proceedingJoinPoint) throws Throwable {ResultBean result = null; try {result = (ResultBean <?>) ProceedingJoinPoint. proceed ();} catch (Exception e) {result = new ResultBean (); result. setCode (ResultCode. FAILED); result. setMessage (e. getMessage (); e. printStackTrace ();} return result ;}}

3-4 contrloer

@ RestController @ Api (tags = {"index"}) public class IndexController {@ GetMapping ("/index/{id}") @ ApiOperation (value = "findByOne ", notes = "get a piece of data") public ResultBean <String> findByOne (@ PathVariable (value = "id") String id) {ResultBean <String> resultBean = new ResultBean <> (); resultBean. setCode (ResultCode. OK); resultBean. setResultData ("request succeeded"); return resultBean;} @ PostMapping ("/index/add") @ ApiOperation (value = "add", notes = "add ") public ResultBean <String> add (Users users) {ResultBean <String> resultBean = new ResultBean <> (); resultBean. setCode (ResultCode. OK); resultBean. setResultData ("successful request"); return resultBean;} @ DeleteMapping ("/index/delete/{id}") @ ApiOperation (value = "delete ", notes = "delete") public ResultBean <String> delete (@ PathVariable (value = "id") String id) {ResultBean <String> resultBean = new ResultBean <> (); resultBean. setCode (ResultCode. OK); resultBean. setResultData ("successful request"); return resultBean ;}}

 

3-5 Test

This is mainly used to test interface APIs. Therefore, there is no business logic layer for database access.

Start the project and access http: // localhost: 8080/swagger-ui.html #/

      

      

Expand add Interface

      

3-6 Note !!!!! To generate an environment, you must disable swagger. swagger is only suitable for development and test environments.

      

    

Related Article

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.