My blog: Lanling xiaosheng, welcome to browse blog!
In implementing Data access, we explained how to use Spring Data JPA in a project to access a database. This chapter continues to explore other springBoot features and how to build online API documentation quickly and efficiently.
One, foreword
In the past, we used to write a WOLD document by hand. I believe that as a code writer, the last thing I want to do is write all kinds of documents. Of course interface documentation is required. But the API documentation that we manually maintain is really slow in terms of efficiency. The interface is constantly changing with the iteration of the project. Updating interface documents in real time is a very distracting thing. Today we will briefly introduce how to use Swagger2 to quickly generate online documents.
Second, the introduction of
Swagger is a document usage tool that implements the OpenApi standard, including various open source toolsets, according to its official website https://swagger.io/.
- Swagger Core example of an API specification used to generate Swagger
- Swagger UI generates an interface, which we’ll use here.
- SwaggerHub API design and documentation
- .
Three, quick start
3.1 Importing Dependencies
After building the Restful API, we first introduce Swagger2 and Swagger UI dependencies in the POM.xml file:
< the dependency > < groupId > IO. Springfox < / groupId > < artifactId > springfox - swagger2 < / artifactId > < version > 2.9.2 < / version > </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> The < version > 2.9.2 < / version > < / dependency >Copy the code
3.2 Swagger2 Configuration
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @ Configuration @ EnableSwagger2 public class Swagger2Conf {/ control display of http://localhost:8081/swagger-ui.html#/ * * * * @ the return */ @Bean public Docket controllerApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(new ApiInfoBuilder() .title(" title: XXX _ interface document ").description(" Description: used for XXXX function, including XXX,XXX module..." ) .contact(new Contact("Socks", null, Null)). The version (version number: "1.0"). The build ()). The select () / / select the package name. The apis (RequestHandlerSelectors. BasePackage (" com ")) .paths(PathSelectors.any()) .build(); }}Copy the code
3.3 Access Address
- http://localhost:8081/swagger-ui.html#/ is the following interface
- http://localhost:8081/v2/api-docs is the returned json interface
Here, swagger2 application can be used as a quick start, but we may need to do some description of Controller, method, we can use the following API refinement management can be achieved.
3.4 FINE API management
First, introduce a few commonly used notes:
3.4.1@ Api: Added to Controller to explain the current Controller
- Value: Doesn’t seem to work
- Tags: Describes the controller,
- Protocols: Indicates the protocol type: HTTP
- Hidden: Nothing
@api (value = "value", tags = "user management ", hidden = true) @RestController @RequestMapping("/api/v1/user") public class UserController { .... }Copy the code
3.4.2@APIOperation: Annotations are added to a method to explain the current method, including the user return value
- Value API explanation
- Notes API considerations
- Response The type returned, etc
3.4.3@APIIgnore: When applied to REST API controller methods, the API will not be displayed:
@apiOperation (value = "delete list ", notes =" note ", response = HttpResponse.class) @ApiIgnore @DeleteMapping("/delete/{id}") public HttpResponse delete(@PathVariable Long id) { userMap.remove(id); return HttpResponse.ok(); }Copy the code
3.4.4 @apiIMPLicitParams and @apiIMPLicitParam, used to explain method parameters,
@ApiIMPLicitParams can contain more than one @APIIMPLicitParam, such as
/** * list request * @return */ @apiOperation (value = "user list ",notes =" attention ",response = httpresponse.class) @requestMapping (path = "/list",method = RequestMethod.PUT, Consumes =" application/json") @apiimplicitparams ({@apiimplicitparam (name="userName",value ="userName"), @apiIMPLICITParam (name="age",value =" User age")}) public HttpResponse list(String userName,Integer age) {list <User> User = new ArrayList<>(userMap.values()); return HttpResponse.ok().setData(user); }Copy the code
This makes the API documentation much richer:
3.4.5 POJO Object Description
Swagger2 = Swagger2; Swagger2 = Swagger2; Swagger2 = Swagger2; @apiModel and @APIModelProperty, without annotations, look like this:
3.4.5.1: @APIModel added to the POJO class
- Value: The default is the class name
- Description: Describes the current POJO
3.4.5.1: @ ApiModelProperty
- Name: property, default POJO property
- Value: the value
- Nodtes: A note
- DataType: Attribute type
- Required: Is it necessary
- AllowEmptyValue: Whether to allow empty space
- AllowableValues: The allowed value
package com.miroservice.chapter2.pojo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @apiModel (value = "user",description = "user") public class user {@apiModelProperty (value = "user ID",notes = "notes",dataType = "long",required = false,allowEmptyValue = true) private Long id; @APIModelProperty (value =" user name ", Notes =" notes",dataType =" String", Required = false,allowEmptyValue = True) private String userName; @apiModelProperty (" user age ") private Long Age; . }Copy the code
Each attribute of the user saved in this way is explained:
3.5 Shut down Swagger2 in Production Environment
We use Swagger2 for the convenience of development, but if we open this document in the production environment, I estimate that the work will be lost soon. How can we prohibit the use of Swagger2 in the formal environment? Actually, it is very simple. We can configure the use of Swagger by adding a note:
ConditionalOnProperty/ConditionalOnProperty/ConditionalOnProperty/ConditionalOnProperty/ConditionalOnProperty/ConditionalOnProperty/ConditionalOnProperty
@Configuration @EnableSwagger2 @ConditionalOnProperty(name = "swagger.enable", HavingValue = "true") public class Swagger2Conf {/ control display of http://localhost:8081/swagger-ui.html#/ * * * * @ return * / @ Bean The public Docket controllerApi () {return new Docket (DocumentationType. SWAGGER_2). ApiInfo (new ApiInfoBuilder (.) the title (" title: Description (" Description: used for XXXX function, including XXX,XXX module..." ) .contact(new Contact("Socks", null, Null)). The version (version number: "1.0"). The build ()). The select () / / select the package name. The apis (RequestHandlerSelectors. BasePackage (" com ")) .paths(PathSelectors.any()) .build(); }}Copy the code
Four,
Swagger2 provides a wide range of extensions, including grouping apis, configuring tokens for each API, Generate static documents, etc., interested in their own in-depth study, the introduction of this chapter for peacetime development should be enough.
That’s it, and you can also check out this blog’s #Spring Boot Getting Started Practice series! #
This article is published by OpenWrite!