Introduction to Spring Boot's Swagger usage and annotations

Introduction

What is Swagger

Swagger is a standardized and complete framework for generating, describing, invoking and visualizing RESTful style Web services. The overall goal is to make the client and file system update at the same speed as the server. File methods, parameters and models are tightly integrated into the server-side code, allowing the API to always stay in sync.

effect

  • Interface documentation is automatically generated online
  • function test

Swagger is a set of open source projects, the main ones are as follows:

  • Swagger-tools : Provide various tools for integration and interaction with Swagger. For example, functions such as pattern checking and conversion of Swagger 1.2 documents into Swagger 2.0 documents.

  • Swagger-core : Swagger implementation for Java/Scala. Integrate with JAX-RS (Jersey, Resteasy, CXF...), Servlets and Play frameworks.

  • Swagger-js : Swagger implementation for JavaScript.

  • Swagger-node-express : Swagger module, an Express web application framework for node.js.

  • Swagger-ui : A dependency - free collection of HTML, JS, and CSS that can dynamically generate elegant documents for Swagger compatible APIs.

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

Use Swagger in Spring

It will be used to integrate Swagger in Spring, which integrates the use of springfox-swaggerSpring 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>

use

Configure Swagger in Spring

 

/**
 * Swagger2配置类
 * 在与spring boot集成时,放在与Application.java同级的目录下。
 * 或者通过 @Import 导入配置
 */
@Configuration
@EnableSwagger2
public class Swagger2 {
    
    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
     * 本例采用指定扫描的包路径来定义指定要建立API的目录。
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.turbo.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    
    /**
     * 创建该API的基本信息(这些基本信息会展现在文档页面中)
     * 访问地址:http://项目实际地址/swagger-ui.html
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("")
                .termsOfServiceUrl("")
                .contact("zou", "", "[email protected]")
                .version("1.0")
                .build();
    }
}

API annotation

@Api

Used on classes, this annotation marks a Controller (Class) as a swagger resource (API). By default, Swagger-Core will only scan and resolve classes with @Api annotations, and will automatically ignore annotations for other types of resources (JAX-RS endpoints, Servlets, etc.). The annotation contains the following important attributes

  • tags
    API group tags. APIs with the same label will be combined and displayed in a group.

  • If value is not defined, value will be used as Api tags

  • The detailed description of the description API is no longer used after version 1.5.X, but it is actually found that it can still be used in version 2.0.0

@ApiOperation

Describe an operation or HTTP method on the specified (routing) path. Different operations with the same path will be grouped into the same operation object. Different HTTP request methods and path combinations constitute 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 description of the operation.

  • The action name of httpMethod HTTP request. Optional values ​​are: "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH".
  • The code
    defaults to 200, and valid values ​​must comply with the standard HTTP Status Code Definitions .

@ApiImplicitParams

Used in the method, the container class of the annotation ApiImplicitParam is stored in an array.

@ApiImplicitParam

Annotate a single parameter of the API. Although the annotation @ApiParam is bound to JAX-RS parameters, this @ApiImplicitParam annotation can define the parameter list in a unified way, which is also the only way to define the parameter in the Servelet and non-JAX-RS environments. Note that this annotation @ApiImplicitParam must be included in the annotation @ApiImplicitParams. The following important parameter attributes can be set:

  • name
    parameter name

  • A short description of the value parameter
  • Is required a required
    parameter
  • The dataType
    parameter type can be a class name or a basic type (String, int, boolean, etc.)

  • The incoming (request) type of the paramType parameter, the optional values ​​are path, query, body, header or form.

@ApiParam

Added meta information description of parameters. This annotation can only be used in the comprehensive environment of JAX-RS 1.x/2.x. Its main attributes are


  • Whether required is a required parameter, the default is false
  • A
    short description of the value parameter

@ApiResponses

Annotate @ApiResponse's wrapper class, array structure. Even if you need to use an @ApiResponse annotation, you also need to include the @ApiResponse annotation in the annotation @ApiResponses.

@ApiResponse

Describe the possible return results of an operation. When a REST API request occurs, this annotation can be used to describe all possible success and error codes. This annotation can be used or not to describe the return type of the operation, but the return type of 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 the same return code, multiple return type annotations. 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
    return type information, must use fully qualified class name, such as "com.xyz.cc.Person.class".

  • If the return type of responseContainer is a container type, you can set the corresponding value. Valid values ​​are "List", "Set" or "Map", any other invalid values ​​will be ignored.

Model annotation

For Model annotations, Swagger provides two: @ApiModel and @ApiModelProperty, which are used to describe Model and properties in Model respectively.

@ApiModel

Describe the information of a Model (usually used when the request parameter cannot be described using the @ApiImplicitParam annotation)

Provide a description of additional information about the Swagger model. In the operation marked with @ApiOperation annotation, all classes will be automatically introspected, but using this annotation can do some more detailed model structure descriptions. The main attributes are:


  • The alias of the value model, the default is the class name

  • Detailed description of the description model

@ApiModelProperty

Describe the attributes of a model

For the annotations of model attributes, the main attribute values ​​are:

  • A
    short description of the value attribute

  • Example value of the example attribute
  • Is required a required
    value

Annotation example

Api example

 

@AllArgsConstructor
@RestController
@RequestMapping("/api/category")
@Api(value = "/category", tags = "组件分类")
public class BizCategoryController {

    private IBizCategoryService bizCategoryService;

    @GetMapping("/list")
    @ApiOperation(value = "列表", notes = "分页列表")
    public R<PageModel<BizCategory>> list(PageQuery pageQuery,
                                          @RequestParam @ApiParam("组件分类名称") 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 = "查询所有", notes = "分页列表")
    public R<List<BizCategory>> listAll() {
        List<BizCategory> categories = bizCategoryService.list();
        return R.success(categories);
    }

    @GetMapping("/{categoryId}")
    @ApiOperation(value = "详情", notes = "组件分类详情")
    public R<BizCategory> detail(@PathVariable @ApiParam("分类Id") Long categoryId) {
        BizCategory category = bizCategoryService.getById(categoryId);
        return R.success(category);
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存", notes = "新增或修改")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", name = "categoryId", value = "组件id(修改时为必填)"),
            @ApiImplicitParam(paramType = "form", name = "name", value = "组件分类名称", 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 = "删除", notes = "删除")
    public R delete(@PathVariable @ApiParam("分类Id") Long categoryId) {
        bizCategoryService.delete(categoryId);
        return R.success();
    }
}

ApiModel example

 

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="BizComponent对象", description="组件")
public class BizComponent implements Serializable {

    private static final long serialVersionUID = 1L;

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

    @ApiModelProperty(value = "分类")
    private Long categoryId;

    @ApiModelProperty(value = "组件名称")
    private String name;

    @ApiModelProperty(value = "组件描述")
    private String description;

    @ApiModelProperty(value = "日期字段")
    private LocalDateTime componentTime;

    @ApiModelProperty(value = "创建时间")
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    @ApiModelProperty(value = "修改时间")
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime modifiedTime;
}

swagger-ui interface

The API document information interface generated by swagger is /v2/api-docs, but we can use the ui interface to view the document description more clearly , and can also debug online

springfox-swagger-ui

 

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

If it is used springfox-swagger-ui, the api document access path after starting the project is /swagger-ui.html

image

swagger-bootstrap-ui

swagger-bootstrap-ui is an enhanced UI implementation of springfox-swagger, I personally recommend using this ui, the api document structure is clearer, and online debugging is also very convenient

 

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

The URL to visit is /doc.html

image

Swagger grouping

Swagger's packet interface is to configure different scanning packages through the back-end, and respond to the front-end according to the basic attributes of the configured scanning package.

The configuration of the back-end java is as follows, specifying the group name and each package to be scanned

 

@Bean(value = "defaultApi")
public Docket defaultApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .groupName("默认接口")
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
        .paths(PathSelectors.any())
        .build();
}
@Bean(value = "groupApi")
public Docket groupRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(groupApiInfo())
        .groupName("分组接口")
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.example.demo.group"))
        .paths(PathSelectors.any())
        .build();
}

The interface of packet information is /swagger-resources

 

[
    {
        "name": "分组接口",
        "url": "/v2/api-docs?group=分组接口",
        "swaggerVersion": "2.0",
        "location": "/v2/api-docs?group=分组接口"
    },{
        "name": "默认接口",
        "url": "/v2/api-docs?group=默认接口",
        "swaggerVersion": "2.0",
        "location": "/v2/api-docs?group=默认接口"
    }
]

In swagger-ui, you can also view api documents by grouping


 

Guess you like

Origin blog.csdn.net/suifeng629/article/details/106195248