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:


Here's how to do this if you use Swagger2 in spring boot. First, we need a RESTful API project implemented by spring boot.

Add Swagger2 Dependency

pom.xmljoin Swagger2 in the dependency

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

@Configuration @enableswagger2 Public classSwagger2 {@Bean PublicDocket Createrestapi () {return NewDocket (documentationtype.swagger_2). Apiinfo (Apiinfo ()). Select (). APIs ( Requesthandlerselectors.basepackage ("Com.didispace.web"). Paths (Pathselectors.any ()). build (); }    Privateapiinfo Apiinfo () {return NewApiinfobuilder (). 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.

@RestController @requestmapping (value= "/users")//This configuration allows the following mappings to be/users, removing Public classUsercontroller {StaticMap<long, user> users = Collections.synchronizedmap (NewHashmap<long, user>()); @ApiOperation (Value= "Get user list", notes= "") @RequestMapping (value={""}, method=requestmethod.get) PublicList<user>getuserlist () {List<User> r =NewArraylist<user>(Users.values ()); returnR; } @ApiOperation (Value= "Create User", notes= "create user based on user object") @ApiImplicitParam (name= "User", Value = "Users detailed entity", required =true, DataType = "User") @RequestMapping (value= "", method=requestmethod.post) PublicString postuser (@RequestBody user user) {users.put (User.getid (), user); return"Success"; } @ApiOperation (Value= "Get user Details", notes= "get user details based on URL id") @ApiImplicitParam (name= "id", value = "User id", required =true, DataType = "Long") @RequestMapping (value= "/{id}", method=requestmethod.get) PublicUser getUser (@PathVariable Long id) {returnusers.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 data passed in.") @ApiImplicitParams ({@ApiImplicitParam (name= "id", value = "User id", required =true, DataType = "Long"), @ApiImplicitParam (name= "User", Value = "Users detailed entity", required =true, DataType = "User")}) @RequestMapping (value= "/{id}", method=requestmethod.put) PublicString 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) PublicString deleteuser (@PathVariable Long id) {users.remove (ID); return"Success"; }}

Complete the above code additions, start the Spring boot program, Access: 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.


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.

Common note Description @api ()

A resource that identifies the class as swagger.

tags– Express Description
Value– is also a description, you can use tags instead
But tags, if there are multiple values, will generate multiple list

@Api (value= "User Controller", tags={"user Interface"}) @RestControllerpublicclass  Usercontroller {}


@ApiOperation ()

Used for methods; An operation that represents an HTTP request
Value is used for method description
Notes for prompting content
Tags can be re-grouped (as appropriate)

@ApiParam ()

Used for methods, parameters, field descriptions, add metadata for parameters (description or mandatory)
name– name of the parameter
value– parameter Description
required– is required

@Api (value= "User Controller", tags={"user Interface"}) @RestControllerpublicclass  Usercontroller {     @ApiOperation (value= "Get user Information", tags={"Get user information copy"},notes= "Attention problem Point")     @GetMapping ( "/getuserinfo")     Public user GetUserInfo (@ApiParam (name= "id", value= "User ID", required= true) Long ID, @ApiParam (name= "username", value= "user name") String username) {     //  UserService can be ignored , is the business logic      User user = userservice.getuserinfo ()      ; return user;  }}


@ApiModel ()

Used to describe a class and to receive a parameter with an entity class
value– indicates the object name
description– description
can be omitted

@ApiModelProperty ()

Used for a method, a field, a description of the model property, or a change in data manipulation
value– Field Description
name– overriding property names
Datatype– overriding property types
required– is required
example– Illustrative examples
hidden– Hidden

@ApiModel (value= "User Object", description= "Users Object") Public classUserImplementsserializable{Private Static Final LongSerialversionuid = 1L; @ApiModelProperty (Value= "username", name= "username", example= "Xingguo")     PrivateString username; @ApiModelProperty (Value= "Status", Name= "state", required=true)      PrivateInteger State; PrivateString password; PrivateString Nickname; PrivateInteger isDeleted; @ApiModelProperty (Value= "id array", hidden=true)      Privatestring[] IDs; PrivateList<string>idlist; //Omit Get/set}
  @ApiOperation ("Change user Information")  @PostMapping ("/updateuserinfo")  publicint Updateuserinfo (@RequestBody @ApiParam (name= "User Object", value= "incoming JSON format", required=true) user user) {      int num = userservice.updateuserinfo (user);      return num;  }


@ApiIgnore ()

Used on a class or method, can not be displayed on the page by swagger
It's relatively simple, not an example here.

@ApiImplicitParam ()

Used for methods
Represents a separate request parameter

@ApiImplicitParams ()

Used for methods that contain multiple @ApiImplicitParam
name– parameter Ming
value– parameter Description
datatype– Data types
paramtype– parameter types
example– Illustrative examples

  @ApiOperation ("Query Test")  @GetMapping ("select")  //@ApiImplicitParam (name= " Name ", value=" username ", datatype=" String ", Paramtype =" Query ")  @ApiImplicitParams ({  @ApiImplicitParam (Name= "Name", value= "username", datatype= "string", Paramtype = "Query", example= "Xingguo"),  @ Apiimplicitparam (Name= "id", value= "User ID", datatype= "long", Paramtype = "Query")})  public  void  Select () {  }


Resources

Swagger official website

Use Swagger2 to build robust RESTful API documentation in Spring boot

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.