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
1234567891011 |
<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
.
1234567891011121314151617181920212223242526 |
@Configuration@EnableSwagger2public class Swagger2 { @Bean Public Docket Createrestapi() { return new Docket (documentationtype.swagger_2) . Apiinfo (Apiinfo ()). Select (). APIs (Requesthandlerselectors.basepackage ("Com.didispace.web")). Paths (Pathselectors.any ()). build (); }private Apiinfo apiinfo() { return New Apiinfobuilder () . 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.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
@RestController@RequestMapping (value="/users") //Through this configuration so that the following mappings are under/users, can be removed public class Usercontroller { static Map<long, user> users = Collections.synchronizedmap (new Hashmap<long, user> ()); @ApiOperation (value="Get user list", notes="") @RequestMapping (value={""}, Method=requestmethod.get) Public list<user> getuserlist() { list<user> r =New Arraylist<user> (Users.values ()); return R;}@ApiOperation (value="Create user", notes="Create user based on user object") @ApiImplicitParam (name = "User", value = "Subscriber Detail entity user", required = true, DataType = " username") @RequestMapping (value="", Method=requestmethod.post) Public String postuser(@RequestBody user user) { Users.put (User.getid (), user);return "Success"; }@ApiOperation (value="Get user Details", notes="Get user details based on the ID of the URL") @ApiImplicitParam (name = "id", value = "User id", required = true, DataType = "Long") @RequestMapping (value="/{id}", Method=requestmethod.get) Public User getUser(@PathVariable Long id) { return Users.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 passed user information.") @ApiImplicitParams ({ @ApiImplicitParam (name = "id", value = "User id", required = true, DataType = "Long"), @ApiImplicitParam (name = "User", value = "Subscriber Detail entity user", required = true, DataType = " username") })@RequestMapping (value="/{id}", Method=requestmethod.put) Public String 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) Public String deleteuser(@PathVariable Long id) { Users.remove (ID);return "Success"; } } |
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 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.
Alt
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.
A complete example of the results can be viewed chapter3-1-5.
Reference information
- Swagger official website
- http://blog.didispace.com/springbootswagger2/
Spring-boot Combat "06" "Turn": Use Swagger2 in Spring boot