Swagger document usage

Many people don’t know the path of swagger ui, because we use a more usable one swagger-bootstrap-ui, we actually use domain name + port +/doc.html, such as: http://localhost:8080/doc.html

Before there was no Swagger, we needed to write the documents ourselves, and there were problems with the handwritten documents:

  1. When the document is updated, it needs to be docked with the front-end personnel, and the document is not updated in time
  2. There are many interface documents and no group management is carried out, which increases the difficulty of management
  3. Can not directly debug online interface, usually need to use tools (such as postman), the efficiency is greatly reduced
  4. Interface description and return result are not clear

These problems can be easily solved through swagger, and the spirngbootintegration of swagger is relatively simple

swagger official website

Add dependency

 <dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger2</artifactId>
     <version>1.9.3</version>
</dependency>
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>2.9.2</version>
</dependency>

Add configuration class and open

Under the config file in the yami-shop-api project , there is a configuration class corresponding to swagger, as long as you know what can be configured specifically, after all, this thing does not need to be moved after it is configured once.

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
    
    

     @Bean
     public Docket baseRestApi() {
    
    
         return new Docket(DocumentationType.SWAGGER_2)
         .apiInfo(apiInfo())
         .groupName("基础版")
         .select()
         .apis(RequestHandlerSelectors.basePackage("com.yami.shop.api"))
         .paths(PathSelectors.any())
         .build();
     }
     @Bean
     public ApiInfo apiInfo() {
    
    
         return new ApiInfoBuilder()
         .title("商城接口文档")
         .description("简介")
         .termsOfServiceUrl("服务Url")
         .contact(new Contact("作者","服务Url", ""))
         .version("1.0")
         .build();
     }
}

Special attention should be paid to the configuration of the api file, which is the path of the controller package, otherwise the generated document will not be able to scan the interface

apis(RequestHandlerSelectors.basePackage("com.yami.shop.api"))

With @Configurationannotation class, so spring hosting this class, @Beantagging method is equivalent to the XML bean configuration

Use @EnableSwagger2logo to openSwagger2

Interface use

After configuration, we can use swagger, such as in the AreaControllerclass

@RestController
@RequestMapping("/p/area")
@Api(tags="省市区接口")
public class AreaController {
    
    

    @Autowired
    private AreaService areaService;
    
    @GetMapping("/listByPid")
    @ApiOperation(value="获取省市区信息", notes="根据省市区的pid获取地址信息")
    @ApiImplicitParam(name = "pid", value = "省市区的pid(pid为0获取所有省份)", required = true, dataType = "String")
    public ResponseEntity<List<Area>> listByPid(Long pid){
    
    
        List<Area> list = areaService.listByPid(pid);
        return ResponseEntity.ok(list);
    }
}

@Api(tags="省市区接口")Define label group interface, all interfaces defined under this class will be located under this label

@ApiOperation()Define specific interface title information, notes can add notes to this label

@ApiImplicitParam()The corresponding parameter list information, the user tells the front-end developers what parameters and parameter descriptions need to be passed in this interface

If there are multiple parameters that need to be explained, you can use the @ApiImplicitParams()following to include multiple@ApiImplicitParam()

Entity class

@Data
@TableName("tz_area")
public class Area implements Serializable {
    
    
    private static final long serialVersionUID = -6013320537436191451L;
    @TableId
    @ApiModelProperty(value = "地区id",required=true)
    private Long areaId;

    @ApiModelProperty(value = "地区名称",required=true)
    private String areaName;

    @ApiModelProperty(value = "地区上级id",required=true)
    private Long parentId;

    @ApiModelProperty(value = "地区层级",required=true)
    private Integer level;

    @TableField(exist=false)
    private List<Area> areas;
}

@ApiModelProperty()Use this annotation to tell front-end developers what the field represents

Common notes

annotation effect
@Api Decorate the entire class and describe the role of Controller
@ApiOperation Describe a method of a class, or an interface
@ApiParam Single parameter description
@ApiModel Use objects to receive parameters
@ApiProperty When receiving parameters with an object, describe a field of the object
@ApiResponse 1 description in HTTP response
@ApiResponses HTTP response overall description
@ApiIgnore Use this annotation to ignore this API
@ApiError Information returned when an error occurs
@ApiImplicitParam A request parameter
@ApiImplicitParams Multiple request parameters

Documentation of pagination parameters and operations on swagger documentation

Our careful attention to swagger document, the document can be found swagger return url interface data are: /v2/api-docs. This url is springfox.documentation.swagger2.web.Swagger2Controlle#getDocumentation()associated. By jsonSerializer.toJson(swagger)generating a specific json document.

When we use PageParam<T>when this paging parameters generated document, always returns generic objects inside information, according to whether we use @ApiParam(hidden = true)another or @JsonIgnoreare ineffective, so we can modify your jsonSerializerresponse generated json

Customize the serialization of Swagger, remove the records value in the pagination parameter

public class SpringfoxJsonSerializer extends JsonSerializer {
    
    

    public SpringfoxJsonSerializer(List<JacksonModuleRegistrar> modules) {
    
    
        super(modules);
    }

    @Override
    public Json toJson(Object toSerialize) {
    
    
        if (!(toSerialize instanceof Swagger)) {
    
    
            return super.toJson(toSerialize);
        }
        Swagger swagger = (Swagger)toSerialize;

        swagger.getPaths().forEach((key, path) ->{
    
    
            Operation get = path.getGet();
            if (get != null) {
    
    

                List<Parameter> parameters = get.getParameters();
                if (parameters != null) {
    
    
                    parameters.removeIf(parameter -> parameter.getName().startsWith("records[0]."));
                }
            }
        });

        return super.toJson(swagger);
    }
}

Newly serialized bean

@Configuration
public class SpringFoxJsonSerializerConfig {
    
    

    @Bean
    @Primary
    public JsonSerializer yamiSpringfoxJsonSerializer(List<JacksonModuleRegistrar> moduleRegistrars) {
    
    
        return new SpringfoxJsonSerializer(moduleRegistrars);
    }
}

Guess you like

Origin blog.csdn.net/lmsfv/article/details/106058536