Six, Springboot integrated Swagger2

Source: Internet
Author: User

1.Swagger Introduction

Swagger is a normative and complete framework for generating, describing, invoking, and visualizing RESTful Web services. The overall goal is to have the client and the file system update at the same speed as the server. File methods, parameters and models are tightly integrated into the server-side code, allowing the API to always stay in sync.

2.Spring Boot Integrated Swagger

First, modify Pom.xml, add maven dependency

        <!--Swagger -        <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>

Second, add Swagger configuration class

@Configuration @enableswagger2 Public classSwaggerconfig {@Bean PublicDocket Createrestapi () {return NewDocket (documentationtype.swagger_2). Apiinfo (Apiinfo ()). Select (). APIs ( Requesthandlerselectors.basepackage ("Specify the package path to scan"). Paths (Pathselectors.any ()). build (); }    Privateapiinfo Apiinfo () {return NewApiinfobuilder (). Title ("Big headline"). Description ("description"). Termsofserviceurl ("http://path. com"). Contact (NewContact ("name", "http://name.com", "[email protected]") //author. Version ("1.0")//version. Build (); } @SuppressWarnings ("Unused")    PrivatePredicate<string>petstorepaths () {returnor (Regex ("/user.*"), Regex ("/cities.*")        ); }}

  @Configuration let spring load the class configuration

  @EnableSwagger2 Enable Swagger2

After you create the docket bean through the createrestapi function,apiinfo () is used to create the basic information for the API (which is the basic information present in the document page). The Select () function returns a apiselectorbuilder instance to control which interfaces are exposed to the swagger, and this example is defined by the package path of the specified scan. Swagger scans all the controller-defined APIs under the package and produces the contents of the document (in addition to requests that are @ApiIgnore specified)

3. Adding document Content

Make some declarations on the API: Add related swagger annotations to the controller class. But there is a requirement that this controller class be sure to let the @componentscan of the previous configuration class scan to

  Swagger annotations indicate that the interface generates documents, including interface names, request methods, parameters, return information, and so on.

  Swagger Note API Detail description

@Api: Modifies the entire class to describe the role of the controller @ApiOperation: A method that describes a class, Or an interface @apiparam: Single parameter description @apimodel: Use object to receive parameter @apiproperty: When receiving parameters with an object, A field that describes an object @apiresponse:http response where 1 descriptions @apiresponses:http The overall description of the response @apiignore: Use this annotation to ignore this api@apierror : Information returned with error @apiparamimplicitl: One request parameter @apiparamsimplicit multiple request parameters
@Api (tags={"Integral Interface"}) @RequestMapping ("Credit") @RestController Public classCreidtcontroller {@AutowiredPrivateCreditservice Creditservice; @AutowiredPrivateconsulclient consulclient; Private StaticLogger log = Loggerfactory.getlogger (Creidtcontroller.class); /**     * @paramID *@returnUser*/@ApiOperation (Value= "Get available points based on user ID", notes= "contains various types of credits") @ApiImplicitParam (name= "id", value = "number", required =true, paramtype= "Path") @GetMapping ("{ID}")     PublicCredit GetUser (@PathVariable String id) {return NULL; }        /**     * @paramserviceId*/@ApiOperation (Value= "Reject service instance", notes= "reject service instance") @ApiImplicitParam (name= "ServiceId", value = "Service id", required =true, paramtype= "Path") @GetMapping ("/clearservice/{serviceid}")     Public voidClearservice (@PathVariable String serviceId) {log.info ("Offline Service-" +serviceId);    Consulclient.agentservicederegister (SERVICEID); }                }

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 click on the specific API request, as an example of the post type/users request, to find the notes information we have configured in the above code and the description of the parameter user.

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

Reference: 72877660 Swagger.io

Six, Springboot integrated Swagger2

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.