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:
alt=
Here's how to do this if you use Swagger2 in spring boot. First, we need a RESTful API project that spring boot implements, and if you haven't done that, it's recommended to read
Spring Boot builds a more complex restful APIs and unit tests.
Below we will take the tutorial example of the chapter3-1-1 to carry out the following experiment (CHPATER3-1-5 is our results engineering, also refer to).
Add Swagger2 Dependency
pom.xml
join 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.java
Create 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 (); }}
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 @ApiIgnore
to the specified request). As shown in the code above, with @Configuration
annotations, let spring load the class configuration. The annotations are then @EnableSwagger2
enabled for Swagger2.
Add Document Content
@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"; }}
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.
alt Complete the above code to add, 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 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.
This article reprinted from the program Ape dd-Suphing: http://blog.didispace.com/springbootswagger2/
Use Swagger2 to build robust RESTful API documentation in Spring boot