Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Swagger2 to build RESTful API documents in Spring Boot

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces how to use Swagger2 to build RESTful API documents in Spring Boot, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Due to the characteristics of rapid development and easy deployment of Spring Boot, it is believed that a large number of users of Spring Boot will be used to build RESTful API. Our purpose of building RESTful API is usually due to multiple terminals, these terminals will share a lot of underlying business logic, so we will abstract such a layer to serve multiple mobile terminals or Web frontend at the same time.

In this way, it is possible for our RESTful API to face multiple developers or development teams: IOS development, Android development, or Web development. In order to reduce the cost of frequent communication with other teams during development, traditionally we create a RESTful API document to record all interface details, but this approach has the following problems:

Because of the numerous interfaces and complex details (you need to consider different HTTP request types, HTTP header information, HTTP request content, etc.), it is very difficult to create this document with high quality, and there are a lot of complaints downstream.

With the passage of time, when constantly modifying the interface implementation, the interface document must be modified synchronously, and the document and the code are in two different media, which can easily lead to inconsistencies unless there is a strict management mechanism.

In order to solve the above problems, this article will introduce RESTful API's blockbuster partner Swagger2, which can be easily integrated into Spring Boot and work with Spring MVC programs to organize powerful RESTful API documents. It can not only reduce the workload of creating documents, but also integrate the description content into the implementation code, so that the maintenance documentation and modification code are integrated into one, which allows us to modify the document description conveniently while modifying the code logic. In addition, Swagger2 also provides powerful page testing capabilities to debug each RESTful API. The specific effect is shown in the following figure:

Let's be more specific if you use Swagger2 in Spring Boot. First, we need a RESTful API project implemented by Spring Boot.

Add Swagger2 dependency

Add Swagger2 dependencies to pom.xml

Io.springfox springfox-swagger2 2.2.2

Io.springfox springfox-swagger-ui 2.2.2

Create a Swagger2 configuration class

Create the configuration class Swagger2 for Swagger2 at the Application.java sibling.

@ Configuration

@ EnableSwagger2

Public class Swagger2 {

@ Bean public Docket createRestApi () {

Return new Docket (DocumentationType.SWAGGER_2) .apiInfo (apiInfo ()) .select () .apis (RequestHandlerSelectors.basePackage ("com.didispace.web")) .build ();}

Private ApiInfo apiInfo () {

Return new ApiInfoBuilder () .title ("build RESTful APIs using Swagger2 in Spring Boot") .description ("desc") .termsOfServiceUrl ("http://blog.didispace.com/") .contact (" programmer DD ") .version (" 1.0") .build ();}}

As shown in the code above, let Spring load this type of configuration with the @ Configuration annotation. Then enable Swagger2 with the @ EnableSwagger2 annotation.

After you create the Bean of the Docket through the createRestApi function, apiInfo () is used to create the basic information of the Api (which will be displayed in the document page). The select () function returns an ApiSelectorBuilder instance to control which interfaces are exposed to Swagger. This example is defined by the specified scanning package path. Swagger scans all API defined by Controller under the package and generates document content (except for requests specified by @ ApiIgnore).

Add document content

After completing the above configuration, we can actually produce the content of the document, but such a document is mainly aimed at the request itself, and the description is mainly generated by functions and other names, which is not user-friendly. We usually need to add some instructions to enrich the document content. As shown below, we add notes to API with @ ApiOperation annotations and parameters through @ ApiImplicitParams and @ ApiImplicitParam annotations.

@ RestController

@ RequestMapping (value= "/ users")

/ / configure here to make the following mappings all under / users, which can be removed.

Public class UserController {

Static Map users = Collections.synchronizedMap (new HashMap ())

@ ApiOperation (value= "get user list", notes= "")

@ RequestMapping (value= {""}, method=RequestMethod.GET)

Public List getUserList () {List r = new ArrayList (users.values ())

Return r;}

@ ApiOperation (value= "create user", notes= "create user from User object")

@ ApiImplicitParam (name = "user", value = "user detail entity user", required = true, dataType = "User")

@ 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 according to url's id")

@ 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= "updates user details", notes= "specifies the update object according to the id of url, and updates user details according to the passed user information")

@ ApiImplicitParams ({

@ ApiImplicitParam (name = "id", value = "user ID", required = true, dataType = "Long")

@ ApiImplicitParam (name = "user", value = "user detail entity user", required = true, dataType = "User")})

@ 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 deletion object according to url's 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 addition, start the Spring Boot program, and visit: http://localhost:8080/swagger-ui.html

. You can see the RESTful API page shown earlier. We can click on 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 the following figure.

API document access and debugging

In the page requested above, we see that the Value of user is an input box. Yes, in addition to viewing the interface function, Swagger also provides debugging and testing functions. We can click on the Model Schema on the right side of the above figure (yellow area: it indicates the data structure of User). At this time, there is a template for user object in Value. We just need to modify it slightly and click "Try it out!" below. Button, you can complete a request call!

At this point, you can also use several GET requests to verify that the previous POST request is correct.

Compared with the work of documenting these interfaces, the additional configuration is very small and concise, and the intrusion of the original code is also within tolerance. Therefore, while building RESTful API, it is a good choice to add swagger to manage API documents.

On how to use Swagger2 in Spring Boot to build RESTful API documents is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report