6. Springboot integrates Swagger2

1. Introduction to Swagger

  Swagger is a canonical and complete framework for generating, describing, invoking, and visualizing RESTful-style web services. The overall goal is to have the client and filesystem update at the same rate as the server. File methods, parameters and models are tightly integrated into the server-side code, allowing the API to be always in sync.

2.Spring Boot 集成Swagger

1. Modify pom.xml and add maven dependencies

        <!-- Swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>

2. Add Swagger configuration class

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    
    @Bean
    public Docket createRestApi() {        
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo (apiInfo ())
                .select()
                .apis(RequestHandlerSelectors.basePackage( "Specify the scanned package path" ))
                .paths(PathSelectors.any())                  
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title( "Big Title" )
                .description("description")
                .termsOfServiceUrl("http://路径.com")
                .contact(new Contact("name", "http://name.com", "[email protected]"))//作者
                .version( "1.0") //version.build (                 );

    }
    
    @SuppressWarnings("unused")
    private Predicate<String> petstorePaths() {
        return or(
                regex("/user.*"),
                regex("/cities.*")
        );
    }

}

  @Configuration lets Spring load the class configuration

  @EnableSwagger2启用Swagger2

After creating the Docket Bean   through the createRestApi function , apiInfo() is used to create the basic information of the Api (these basic information will be displayed on the documentation page). The select() function returns an ApiSelectorBuilder instance to control which interfaces are exposed to Swagger for display. In this example, the package path specified for scanning is used to define it. Swagger will scan all the APIs defined by the Controller under the package and generate document content (except for those defined by @@ ApiIgnore specified request)

3. Add document content

  Make some declarations on the API: add relevant swagger annotations to the Controller class. But there is a requirement, this Controller class must be scanned by @ComponentScan of the previous configuration class

  Swagger indicates that the interface will generate documents through annotations, including interface name, request method, parameters, return information, and so on.

  swagger annotation API detailed description

@Api : Decorate the entire class, describe the role of the Controller
 @ApiOperation : Describe a method of a class, or an interface
@ApiParam: single parameter description
@ApiModel: use an object to receive parameters
@ApiProperty: When receiving parameters with an object, describe a field of the object
@ApiResponse: HTTP response with 1 description
@ApiResponses: overall description of the HTTP response
@ApiIgnore: Use this annotation to ignore this API
@ApiError : the information returned when an error occurred
@ApiParamImplicitL: a request parameter
@ApiParamsImplicit multiple request parameters
@Api(tags={"Integral interface" })
@RequestMapping("credit")
@RestController
public  class CreidtController {

    @Autowired
    private CreditService creditService;
    
    @Autowired  
    private ConsulClient consulClient;
        
    private static Logger log = LoggerFactory.getLogger(CreidtController.class);

    /**
     * @param id
     * @return User
      */ 
    @ApiOperation(value = "Get available points based on user ID", notes="Contains various types of points" )   
    @ApiImplicitParam(name = "id", value = "编号", required = true, paramType="path")
    @GetMapping("{id}")
    public Credit getuser(@PathVariable String id) {
        return null;
    }
    
    /** 
     * @param serviceId
      */ 
    @ApiOperation(value = "Exclude service instance", notes="Exclude service instance" )
    @ApiImplicitParam(name = "serviceId", value = "服务ID", required = true, paramType="path")
    @GetMapping("/clearService/{serviceId}")
    public void clearService(@PathVariable String serviceId) {
        log.info( "Offline service-" + serviceId);
        consulClient.agentServiceDeregister(serviceId);
    }        
        
}

  After adding the above code, start the Spring Boot program and visit: http://localhost:8080/swagger-ui.html

  You can see the page of the RESTful API shown above. We can click on the specific API request again. Taking the POST type /users request as an example, we can find the Notes information we configured in the above code and the description information of the parameter user.

4. API document access and debugging

  In the requested page above, we see that the user's Value is an input box? Yes, in addition to viewing interface functions, Swagger also provides debugging and testing functions. We can click on the Model Schema (yellow area: it indicates the user's data structure) on the right side of the figure above, and then there is a user object in the Value. , we only need to modify it slightly, click the “Try it out!”button below to complete a request call!

 

At this point, you can also verify that the previous POST request was correct with several GET requests.

Reference: https://blog.csdn.net/Amethyst128/article/details/72877660
    swagger.io

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325094880&siteId=291194637