introduce

What is a Swagger

Swagger Swagger is a specification and complete framework for generating, describing, invoking, and visualizing RESTful Web services. The overall goal is to have the client and the file system update at the same rate as the server. The file’s methods, parameters, and models are tightly integrated into the server-side code, allowing the API to always be synchronized.

role

  • Interface documents are automatically generated online
  • A functional test

Swagger is a set of open source projects with the following key items:

  • Swagger-tools: Provides a variety of tools to integrate and interact with Swagger. Features such as pattern validation, Swagger 1.2 document conversion to Swagger 2.0 document, etc.

  • Swagger-core: Swagger implementation for Java/Scala. With JAX-RS(Jersey, Resteasy, CXF…) , Servlets and the Play framework.

  • Swagger-js: Swagger implementation for JavaScript.

  • Swagger-nod-express: Swagger module for Node.js Express Web application framework.

  • Swagger-ui: An independent collection of HTML, JS, and CSS that dynamically generates elegant documentation for Swagger-compliant apis.

  • Swagger-codegen: A template-driven engine that generates client code in various languages by analyzing user Swagger resource declarations.

Use Swagger in Spring

Integrating Swagger with Spring uses Springfox-Swagger, which integrates the use of Spring and Swagger

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${springfox.swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${springfox.swagger.version}</version>
</dependency>
Copy the code

use

Configure Swagger in Spring

/** * Swagger2 configuration class * When integrated with Spring Boot, put in the same directory as application.java. * Or through@ImportImport configuration */
@Configuration
@EnableSwagger2
public class Swagger2 {
    
    /** * Create API application * add API related information * select() function to return an ApiSelectorBuilder instance to control which interfaces are exposed to Swagger to present, * This example uses the specified package path to scan to define the directory that specifies the API to be created. *@return* /
    @Bean
    public Docket createRestApi(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.turbo.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    
    /** * Create the basic information for the API (which is shown in the documentation page) * Visit http://project actual address /swagger-ui.html *@return* /
    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                .title("Building RESTful APIs with Swagger2 in Spring Boot")
                .description("")
                .termsOfServiceUrl("")
                .contact("zou".""."[email protected]")
                .version("1.0") .build(); }}Copy the code

API annotations

@Api

For classes, this annotation marks a Controller (Class) as a Swagger resource (API). By default, Swagger-core only scans and resolves classes with @API annotations, and automatically ignores annotations for other class resources (JAX-RS Endpoints, Servlets, and so on). This annotation contains several important attributes

  • Tags API group tags. Apis with the same tags will be grouped together for presentation.
  • Value If tags are not defined, value will be used as tags for the Api
  • Description A detailed description of the API, no longer in use after version 1.5.X, but actually found to be still available in version 2.0.0

@ApiOperation

Describes an operation or HTTP method on a specified (routed) path. Different operations that have the same path are grouped into the same operation object. Different HTTP request methods and paths combine to form a unique operation. The attributes of this annotation are:

  • Value is a simple description of the operation. The length is 120 letters and 60 Chinese characters.
  • Notes detailed instructions for the operation.
  • HttpMethod Specifies the action name of the HTTP request. The available values are “GET”, “HEAD”, “POST”, “PUT”, “DELETE”, “OPTIONS” and “PATCH”.
  • The default value of code is 200. Valid values must comply with the standard HTTP Status code Definitions.

@ApiImplicitParams

In the method, annotate the container class of ApiImplicitParam, stored as an array.

@ApiImplicitParam

Annotate a single parameter of the API. Although the @Apiparam annotation is bound to JAX-RS parameters, the @ApiImplicitParam annotation can define the parameter list in a uniform way and is the only way to define the parameters in both servlet and non-JAX-RS environments. Note that the annotation @ApiImplicitParam must be contained within the annotation @ApiImplicitParams. You can set the following important parameter properties:

  • Name Parameter name
  • Value A brief description of the parameter
  • Required Whether the parameter is mandatory
  • DataType Parameter type, which can be a class name or a basic type (String, int, Boolean, etc.)
  • ParamType Specifies the incoming (request) type of the parameter. Optional values include path, query, body, header, or form.

@ApiParam

Added the description of meta information about parameters. This annotation can only be used in the context of jax-RS 1.x/2.x synthesis. The main properties are

  • Required Whether this parameter is required. The default value is false
  • Value Indicates a brief description of the parameter

@ApiResponses

Annotation @apiResponse wrapper class, array structure. Even if you need to use an @ApiResponse annotation, you need to include the @ApiResponse annotation within the @apiResponses annotation.

@ApiResponse

Describes the possible results of an operation. This annotation can be used to describe all possible success and error codes when a REST API request occurs. This annotation may or may not be used to describe the return type of the operation, but the return type for a successful operation must be defined in @apiOperation. If the API has different return types, you need to define the return values separately and associate the return types. But Swagger does not support annotations for the same return code, multiple return types. Note: This annotation must be included in the @apiResponses annotation.

  • Code HTTP request return code. Valid values must comply with the standard HTTP Status Code Definitions.
  • Message a text message that is easier to understand
  • Response returns type information, which must use the fully qualified class name, such as “com.xyz.cc.person.class”.
  • ResponseContainer If the return type is container type, you can set the corresponding value. Valid values are “List”, “Set” or “Map”, and any other invalid values are ignored.

The Model annotation

For Model annotations, Swagger provides two: @ApiModel and @ApiModelProperty, which describe the Model and the properties within the Model, respectively.

@ApiModel

Description of a Model (usually used when request parameters cannot be described using the @ApiImplicitParam annotation)

Provide a description of the Swagger Model with additional information. In the @APIOperation annotation, all classes are automatically introspected, but this annotation allows for more detailed description of the model structure. The main attributes are:

  • Alias of the Value Model, which defaults to the class name
  • Description Detailed description of the model

@ApiModelProperty

Describes the properties of a Model

The main attribute values for the model attribute are:

  • A brief description of the value attribute
  • The example value of the example attribute
  • Required Whether the value is required

Note the sample

Api sample

@AllArgsConstructor
@RestController
@RequestMapping("/api/category")
@Api(value = "/category", tags = "Component Classification")
public class BizCategoryController {

    private IBizCategoryService bizCategoryService;

    @GetMapping("/list")
    @ApiOperation(value = "A list", notes = "Paginated List")
    public R<PageModel<BizCategory>> list(PageQuery pageQuery,
                                          @RequestParam @ApiParam("Component Category Name") String name) {
        IPage<BizCategory> page = bizCategoryService.page(pageQuery.loadPage(),
                new LambdaQueryWrapper<BizCategory>().like(BizCategory::getName, name));
        return R.success(page);
    }

    @GetMapping("/list/all")
    @ApiOperation(value = "Query all", notes = "Paginated List")
    public R<List<BizCategory>> listAll() {
        List<BizCategory> categories = bizCategoryService.list();
        return R.success(categories);
    }

    @GetMapping("/{categoryId}")
    @ApiOperation(value = "Details", notes = "Component Classification Details")
    public R<BizCategory> detail(@PathVariable @ApiParam(Classification of "Id") Long categoryId) {
        BizCategory category = bizCategoryService.getById(categoryId);
        return R.success(category);
    }

    @PostMapping("/save")
    @ApiOperation(value = "Save", notes = "Add or Modify")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", name = "categoryId", value = "Component ID (mandatory when changing)"),
            @ApiImplicitParam(paramType = "form", name = "name", value = "Component Category Name", required = true)})public R<BizCategory> save(Long categoryId, String name) {
        BizCategory category = new BizCategory();
        category.setId(categoryId);
        category.setName(name);
        bizCategoryService.saveOrUpdate(category);
        return R.success(category);
    }

    @DeleteMapping("/{categoryId}")
    @ApiOperation(value = "Delete", notes = "Delete")
    public R delete(@PathVariable @ApiParam(Classification of "Id") Long categoryId) {
        bizCategoryService.delete(categoryId);
        returnR.success(); }}Copy the code

ApiModel sample

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="BizComponent object", description="Component")
public class BizComponent implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @ApiModelProperty(value = "Classification")
    private Long categoryId;

    @ApiModelProperty(value = "Component Name")
    private String name;

    @ApiModelProperty(value = "Component Description")
    private String description;

    @ApiModelProperty(value = "Date field")
    private LocalDateTime componentTime;

    @ApiModelProperty(value = "Creation time")
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    @ApiModelProperty(value = "Modification time")
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime modifiedTime;
}
Copy the code

Swagger – UI interface

Swagger’s generated API documentation is /v2/api-docs, but you can use the UI to see the documentation more clearly and to debug it online

springfox-swagger-ui

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${springfox.swagger.version}</version>
</dependency>
Copy the code

If you are using Springfox-Swagger-UI, the API documentation path after starting the project is /swagger-ui.html

swagger-bootstrap-ui

Swagger-bootstrap-ui is an enhanced UI implementation of Springfox-Swagger. I personally recommend using this UI. The API documentation structure is much clearer and it is easy to debug online

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>${swagger.bootstrap.ui.version}</version>
</dependency>
Copy the code

The URL to visit is /doc.html

Swagger grouping

Swagger’s grouping interface is configured with different scan packets on the back end, and the back end interface responds to the front end according to the basic attributes of configured scan packets

The back-end Java configuration is as follows, specifying the group name and the respective packages to scan

@Bean(value = "defaultApi")
public Docket defaultApi(a) {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .groupName("Default interface")
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
        .paths(PathSelectors.any())
        .build();
}
@Bean(value = "groupApi")
public Docket groupRestApi(a) {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(groupApiInfo())
        .groupName("Packet interface")
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.example.demo.group"))
        .paths(PathSelectors.any())
        .build();
}
Copy the code

The interface for grouping information is/Swagger-resources

[{"name": "Packet interface"."url": "/v2/api-docs? Group = Group interface"."swaggerVersion": "2.0"."location": "/v2/api-docs? Group = Group interface"}, {"name": "Default interface"."url": "/v2/api-docs? Group = default interface"."swaggerVersion": "2.0"."location": "/v2/api-docs? Group = default interface"}]Copy the code

You can also view the API documentation by grouping in swagger-UI