Springboot integrated SWAGGER2 building RESTful API documentation

Source: Internet
Author: User

In the development process, sometimes we need to constantly test the interface, self-test, or by testing the interface, we need to build a document, are written separately, too cumbersome, now use Springboot integrated Swagger2 to build RESTful API documents, can be on the interface, Add comments directly

Let's introduce the development environment:

    1. JDK version is 1.8
    2. The version of Springboot is 1.4.1
    3. development tool for IntelliJ idea

We first introduced the Swagger2 jar package, and the Pom file introduction relies on the following:

<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</< Span class= "Hljs-name" >version></DEPENDENCY>   

Next, we build the Swagger2 configuration class with the following code:

Annotations turn on the Swagger2 function@EnableSwagger2annotation, which is a configuration class, @Configuation annotations contain @component annotationsIt is not necessary to use the @component annotation tag it's a bean.@ConfigurationPublicClassSwagger2 {/** * Createrestapi function to build a docketbean * Function name, can be arbitrarily named, like what name is what name * *@BeanPublic DocketCreaterestapi() {ReturnNew Docket (Documentationtype. swagger_2). Apiinfo (Apiinfo ())Call the Apiinfo method to create a Apiinfo instance, which is displayed in the document page information content. Select ()Control the instances under the exposed pathIf an interface does not want to be exposed, you can use the following annotations@ApiIgnore this, the interface will not be exposed to the Swagger2 page. APIs (Requesthandlerselectors.basepackage ("Com.example")). Paths (Pathselectors.any ()). Build ();} //Build API documentation for more information function private apiinfo apiinfo() {return new Apiinfobuilder ()//page title . Title ( "Spring Boot test builds restful API using Swagger2") //Creator . Contact ("he Xiao Wu")//Version No. . Version ("1.0")//Description . Description ("API description") . Build ();}}                  

The
configuration class for Swagger2 is already configured, so let's write some interfaces in the main function.

@SpringBootApplication (scanbasepackages = {"com"})The note contains two annotations of @controller and @responsebody@RestControllerPublicClassdemoapplication{PublicStaticvoidMain(string[] args) {springapplication. Run (Demoapplication.class, args);}/** * Note of the following functions, without adding annotations, will be described in the following uniform */@ApiOperation (value ="Test POST request", notes="Precautions")@ApiImplicitParam (DataType ="User", name ="User", value ="User Information", required =True@RequestMapping (value ="/testpost", method = Requestmethod.post)Public StringTestpost(@RequestBody User user) {Return"Success";}@ApiOperation (value ="Test GET Request", notes="Precautions")@ApiImplicitParam (name ="id", value ="User ID", DataType ="String", Paramtype ="Path")@RequestMapping (value ="/testget/{id}", method = Requestmethod.get)Public StringTestget(@PathVariable String ID) {return ID;}@ApiOperation (value ="Test mix annotations", notes="Precautions")@ApiImplicitParams ({@ApiImplicitParam (DataType ="User", name ="User", value ="User Information", required =True,paramtype ="Body"),@ApiImplicitParam (DataType ="string", name ="id", value ="User ID", required = True,paramtype = "path")}) @RequestMapping (value = "/joinannotation/{id}", method = requestmethod.post) publicUser  Joinannotation(@PathVariable String ID,@RequestBody user user) {return user;} @ApiIgnore publicString testignore() {return "Success";}}     

Don't you spit my way to name .... Let's see ... Test the demo, the name is random (in fact, my English is not very good .... hahaha haha .....)

after we have written the controller, we can access the following address: http://localhost:8080/swagger-ui.html, if you do not introduce swagger2 dependency, you will not be able to access. Then you'll get a page like this

The above page, is swagger2 inside of the page, you can find that apiinfo inside the content set on the left to show out, Demo-application is actually the controller's class name, the right has three buttons, respectively, is show/hide,list Opertions and expand Operations, three buttons can be opened, the interface under the class, click, you will get the following effect page:

Can be found, show out, controller under the three interface (actually there are four, but there is a note that we ignored, in this do not show it).

Above three interface, in our comments added, there are display, request, interface name, now we open an interface to see the specific content, the interface content, I am not in the text description, I directly in the inside to add a description. Forgive me.

This, the comparison is rotten, you will see it. We click the try it out button to send the request, the result is as follows:

The above is a relatively simple demo test document, if you want to configure more detailed, go to the official website to see it. Address I post it:

Swagger website Address: http://swagger.io/

here is the introduction, above the interface, the above about swagger2 I commonly used annotations of some of the description

I commonly used note description:

@ApiOperation: Use the method to illustrate the role of the method

    1. Value: Represents the interface name
    2. NOTES: Indicates a detailed description of the interface

@ApiImplicitParams: Use the method to include a set of parameter descriptions

@ApiImplicitParam: Use in @apiimplicitparams Annotations to specify aspects of a request parameter

    1. Paramtype: Parameter position
    • Header corresponding Annotations: @RequestHeader
    • Query corresponding annotations: @RequestParam
    • Path corresponding annotations: @PathVariable
    • Body Correspondence Note: @RequestBody
    1. Name: Name of parameter
    2. DataType: Parameter types
    3. Required: Whether the parameter must be passed
    4. Value: Description of the parameter
    5. DefaultValue: Default values for parameters

@ApiResponses: Used to represent a set of responses

@ApiResponse: Used in @apiresponses, generally used to express a wrong response information

    1. Code: Status Code
    2. Message: Return custom information
    3. Response: class that throws an exception

@ApiIgnore: Indicates that the interface function is not open for swagger2 display

These are the comments I tested, and did not delve into, interested, can look at other annotations, or source code, will be more than I describe the whole lot,

Yes, it is important to
note that the Paramtype property under the @ Apiimplicitparam annotation will affect the test of the interface, and if the Set property does not correspond to spring's annotations, it will not get the parameters, for example: Paramtype=path, The @requestparam annotation is used inside the function, so that it may not get the parameters passed in, it needs to correspond to the above, the @requestparam annotation to @pathvariable to get the corresponding parameters
...

Springboot integrated SWAGGER2 building RESTful API documentation

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.