当前位置:网站首页>Swagger, Yapi interface management service_ SE
Swagger, Yapi interface management service_ SE
2022-07-06 10:56:00 【Bolus acidophilus】
List of articles
Swagger
Introduce
Official website :https://swagger.io/
Swagger Is a specification and complete framework , Used to generate 、 describe 、 Invocation and visualization RESTful Style Web service . The functions mainly include the following points :
A. It makes it more convenient to separate the front end from the back end , It's good for teamwork
B. Interface documents are automatically generated online , Reduce the burden of writing interface documents for back-end developers
C. Interface function test
Use Swagger Just define the interface and interface related information according to its specification , Re pass Swagger A series of derived projects and tools , You can generate various formats of interface documents , And online interface debugging page and so on .
Use it directly Swagger, Need to follow Swagger The specification defines the interface , It's actually writing Json file , It's cumbersome to write 、 It's not convenient , . And use... In projects , We usually choose some ready-made frameworks to simplify the preparation of documents , These frameworks are based on Swagger Of , Such as knife4j.knife4j Is for Java MVC Framework for the integration Swagger Generate Api Document enhancement solution . And we're going to use kinfe4j, Need to be in pom.xml The following dependencies can be introduced :
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
Usage mode
Next , We will integrate our project Knife4j, To automatically generate interface documents . Here we still need to create a new branch v1.2, In this branch knife4j Integration of , After the integration test , No problem , We will again v1.2 Branch into master.
Use knife4j, The following steps are required :
1). Import knife4j Of maven coordinate
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
2). Import knife4j Related configuration classes
Here we don't need to create a new configuration class , We are directly in the WebMvcConfig Just declare it in the configuration class .
A. Add two annotations to the configuration class @EnableSwagger2 @EnableKnife4j , Turn on Swagger and Knife4j The function of .
B. Declare a Docket Type of bean, Through the bean To specify the information of the generated document .
@Slf4j
@Configuration
@EnableSwagger2
@EnableKnife4j
public class WebMvcConfig extends WebMvcConfigurationSupport {
/** * Set static resource mapping * @param registry */
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info(" Start static resource mapping ...");
registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
}
/** * Expand mvc Message converter of framework * @param converters */
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
log.info(" Extended message converter ...");
// Create a message converter object
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
// Set the object converter , Bottom use Jackson take Java Object to json
messageConverter.setObjectMapper(new JacksonObjectMapper());
// Append the above message converter object to mvc In the converter collection of the framework
converters.add(0,messageConverter);
}
@Bean
public Docket createRestApi() {
// The document type
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.itheima.reggie.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(" Reggie takeout ")
.version("1.0")
.description(" Reggie takeout interface document ")
.build();
}
}
Be careful : Docket When making a statement , There is a package scanning path specified , This path specifies Controller The path of the package . because Swagger When generating interface documents , According to the package path specified here , Automatically scan the package @Controller, @RestController, @RequestMapping etc. SpringMVC Annotations , Generate the corresponding interface document according to these annotations .
3). Set static resource mapping
because Swagger In the generated online document , It involves many static resources , These static resources need to add static resource mapping , Otherwise, the interface document page cannot be accessed . So you need to WebMvcConfig Class addResourceHandlers The following configuration is added to the method .
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
4). stay LoginCheckFilter Set the request path that does not need to be processed in
Need to put Swagger And Knife4j Relevant static resources are released directly , No need to log in to access , Otherwise, we need to log in , Can access the page of the interface document .
In the original request path that does not need to be processed , Add the following links :
"/doc.html",
"/webjars/**",
"/swagger-resources",
"/v2/api-docs"
View interface documentation
After the above integrated configuration , Our project integration Swagger And Knife4j We're done , Next we can restart the project , Provider documentation , The access link is : http://localhost:8080/doc.html
We can see , Of all the Controller Interfaces for adding, deleting, modifying and querying all businesses provided in , All have been automatically generated , We can see the requested through the interface document url、 Request mode 、 Request parameters 、 Request instance 、 Response parameters , Examples of responses . And , We can also use this online interface document , Test the interface .
Be careful : Because of our server Controller Methods of business addition, deletion, modification and query in , You must log in before you can access , therefore , When we are testing , You also need to access the login interface first . After login , We can access other interfaces for testing .
We can not only browse the generated interface documents in the browser ,Knife4j It also supports offline documents , Download interface documents , The supported download formats are :markdown、html、word、openApi.
Commonly used annotations
Problem specification
Above we visit directly Knife4j Interface document page for , You can view all interface document information , But we found that , These interface document classifications and interface descriptions are Controller The name of the class ( The name of hump changes ) And the method name , And in the interface document , All request parameters , The response data , There is no Chinese description , I don't know the meaning of the parameters , The readability of interface documents is poor .
Note introduction
In order to solve the above problems ,Swagger A lot of comments are provided , Through these notes , We can better and more clearly describe our interface , Contains the request parameters of the interface 、 The response data 、 Data models, etc . Core notes , It mainly includes the following :
annotation | Location | explain |
---|---|---|
@Api | class | load Controller Class , Represents a description of a class |
@ApiModel | class ( Usually entity classes ) | Describe the role of entity classes |
@ApiModelProperty | attribute | Describes the properties of an entity class |
@ApiOperation | Method | Explain the purpose of the method 、 effect |
@ApiImplicitParams | Method | Represents a set of parameter descriptions |
@ApiImplicitParam | Method | Use in @ApiImplicitParams In the annotations , Specify the attributes of each aspect of a request parameter |
Annotation test
1). Entity class
Can pass @ApiModel , @ApiModelProperty To describe entity classes and attributes
@Data
@ApiModel(" package ")
public class Setmeal implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(" Primary key ")
private Long id;
// classification id
@ApiModelProperty(" classification id")
private Long categoryId;
// Package name
@ApiModelProperty(" Package name ")
private String name;
// Package price
@ApiModelProperty(" Package price ")
private BigDecimal price;
// state 0: Discontinue use 1: Enable
@ApiModelProperty(" state ")
private Integer status;
// code
@ApiModelProperty(" Package number ")
private String code;
// Description information
@ApiModelProperty(" Description information ")
private String description;
// picture
@ApiModelProperty(" picture ")
private String image;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
@TableField(fill = FieldFill.INSERT)
private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;
}
2). In response to the entity R
@Data
@ApiModel(" Return results ")
public class R<T> implements Serializable{
@ApiModelProperty(" code ")
private Integer code; // code :1 success ,0 And other numbers are failures
@ApiModelProperty(" error message ")
private String msg; // error message
@ApiModelProperty(" data ")
private T data; // data
@ApiModelProperty(" Dynamic data ")
private Map map = new HashMap(); // Dynamic data
// Omit static methods ....
}
3). Controller Class and its methods
describe Controller、 Method and its method parameters , You can annotate : @Api, @APIOperation, @ApiImplicitParams, @ApiImplicitParam
@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = " Package related interfaces ")
public class SetmealController {
@Autowired
private SetmealService setmealService;
@Autowired
private CategoryService categoryService;
@Autowired
private SetmealDishService setmealDishService;
/** * New package * @param setmealDto * @return */
@PostMapping
@CacheEvict(value = "setmealCache",allEntries = true)
@ApiOperation(value = " New package interface ")
public R<String> save(@RequestBody SetmealDto setmealDto){
log.info(" Package information :{}",setmealDto);
setmealService.saveWithDish(setmealDto);
return R.success(" Successfully added package ");
}
/** * Package paging query * @param page * @param pageSize * @param name * @return */
@GetMapping("/page")
@ApiOperation(value = " Package paging query interface ")
@ApiImplicitParams({
@ApiImplicitParam(name = "page",value = " Page number ",required = true),
@ApiImplicitParam(name = "pageSize",value = " Records per page ",required = true),
@ApiImplicitParam(name = "name",value = " Package name ",required = false)
})
public R<Page> page(int page,int pageSize,String name){
// Page builder object
Page<Setmeal> pageInfo = new Page<>(page,pageSize);
Page<SetmealDto> dtoPage = new Page<>();
LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
// Add query criteria , according to name Conduct like Fuzzy query
queryWrapper.like(name != null,Setmeal::getName,name);
// Add sorting criteria , Sort in descending order according to the update time
queryWrapper.orderByDesc(Setmeal::getUpdateTime);
setmealService.page(pageInfo,queryWrapper);
// Object Copy
BeanUtils.copyProperties(pageInfo,dtoPage,"records");
List<Setmeal> records = pageInfo.getRecords();
List<SetmealDto> list = records.stream().map((item) -> {
SetmealDto setmealDto = new SetmealDto();
// Object Copy
BeanUtils.copyProperties(item,setmealDto);
// classification id
Long categoryId = item.getCategoryId();
// According to the classification id Query classification objects
Category category = categoryService.getById(categoryId);
if(category != null){
// Category name
String categoryName = category.getName();
setmealDto.setCategoryName(categoryName);
}
return setmealDto;
}).collect(Collectors.toList());
dtoPage.setRecords(list);
return R.success(dtoPage);
}
/** * Delete package * @param ids * @return */
@DeleteMapping
@CacheEvict(value = "setmealCache",allEntries = true)
@ApiOperation(value = " Package deletion interface ")
public R<String> delete(@RequestParam List<Long> ids){
log.info("ids:{}",ids);
setmealService.removeWithDish(ids);
return R.success(" Package data deleted successfully ");
}
/** * Query package data according to conditions * @param setmeal * @return */
@GetMapping("/list")
@Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
@ApiOperation(value = " Package condition query interface ")
public R<List<Setmeal>> list(Setmeal setmeal){
LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
queryWrapper.orderByDesc(Setmeal::getUpdateTime);
List<Setmeal> list = setmealService.list(queryWrapper);
return R.success(list);
}
}
4). Restart service test
We passed the above Swagger Annotations , For entity classes and attributes in entity classes , as well as Controller and Controller Describe the method , Next , We restart the service , Then take a look at the changes in the automatically generated interface document .
In the page of the interface document , We can see the Chinese description of the interface , Clearly see what each interface does , What is the meaning of interface method parameters , Whether the parameter is required , What is the meaning of the response result parameters , Can be clearly described .
All in all , We need to clearly describe an interface , With the help of Swagger Comments provided to us .
Yapi
Introduce
YApi It's efficient 、 Easy to use 、 Powerful api Management platform , Designed to develop 、 product 、 Testers provide more elegant interface management services . Can help developers easily create 、 Release 、 maintain API,YApi It also provides excellent interaction experience for users , Developers only need to use the interface data writing tool and simple click operation provided by the platform to realize the interface management .
YApi Make interface development simpler and more efficient , Make interface management more readable 、 Maintainability , Make teamwork more reasonable .
Source code address : https://github.com/YMFE/yapi
Official documents : https://hellosean1025.github.io/yapi/
To use YApi, The project team needs to deploy itself , In this project, we can use the platform provided by the course to test , domain name : https://mock-java.itheima.net/
Use
Get ready
Registered account , Login platform
Defining interfaces
Log in to Yapi After the platform , We can create projects , Create an interface classification under the project , Add interfaces to the corresponding categories .
1). Create project
2). Add categories
In the current project , For employees 、 variety of dishes 、 package 、 Order operation , When we maintain the interface , You can classify interfaces , If there is no corresponding classification , We add our own categories .
3). Add interface
After entering the basic interface information , Add submit , You can see the basic information of the interface :
But at the moment , We do not specify the request parameters in the interface , Response data and other information , We can further click Edit , For this interface Edit the details .
4). Running interface
Yapi Interface test function is also provided , When we finish editing the interface , The code development of the back-end service is completed , Start the service , You can use Yapi Interface test is done .
Be careful : Because the menu paging query interface , It can only be accessed after logging in , So when testing the interface , You need to first request the login interface in the employee management interface , After login , Then access the interface .
stay Yapi In the platform , After defining the interface document , Front and back-end developers need to develop front-end and back-end functions according to the description of the interface in the interface document .
Export interface document
stay Yapi In the platform, we can not only read documents online , Can also be Yapi Directly export the documents maintained in , Can export md,json,html Format , You can choose by yourself when exporting .
In the exported html File or md In file , It mainly describes the basic information of the interface , Include : Request path 、 Request mode 、 Interface description 、 Request parameters 、 Return data and other information . The display form is as follows :
Import interface document
Above, we explained the export of interface documents , We can also import external interface documents into Yapi In the platform , In this way, we don't need to add interfaces one by one . We can use the information provided in the course materials json The interface document in format is imported directly Yapi From the platform .
Confirmation pop-up during import , choice " confirm ".
After importing successfully , We can do that Yapi The platform sees the imported interface .
边栏推荐
- Windows cannot start the MySQL service (located on the local computer) error 1067 the process terminated unexpectedly
- npm一个错误 npm ERR code ENOENT npm ERR syscall open
- MySQL 29 other database tuning strategies
- Mysql25 index creation and design principles
- Valentine's Day is coming, are you still worried about eating dog food? Teach you to make a confession wall hand in hand. Express your love to the person you want
- Postman Interface Association
- @controller,@service,@repository,@component区别
- Invalid default value for 'create appears when importing SQL_ Time 'error reporting solution
- MySQL27-索引優化與查詢優化
- Time in TCP state_ The role of wait?
猜你喜欢
Isn't there anyone who doesn't know how to write mine sweeping games in C language
IDEA 导入导出 settings 设置文件
Mysql36 database backup and recovery
MySQL22-逻辑架构
MySQL19-Linux下MySQL的安装与使用
MySQL27-索引优化与查询优化
A brief introduction to the microservice technology stack, the introduction and use of Eureka and ribbon
MySQL21-用戶與權限管理
[recommended by bloggers] background management system of SSM framework (with source code)
windows无法启动MYSQL服务(位于本地计算机)错误1067进程意外终止
随机推荐
Anaconda3 installation CV2
Solve the problem that XML, YML and properties file configurations cannot be scanned
MySQL34-其他数据库日志
MySQL33-多版本并发控制
Swagger、Yapi接口管理服务_SE
Windows cannot start the MySQL service (located on the local computer) error 1067 the process terminated unexpectedly
第一篇博客
MySQL19-Linux下MySQL的安装与使用
frp内网穿透那些事
windows下同时安装mysql5.5和mysql8.0
CSDN问答模块标题推荐任务(一) —— 基本框架的搭建
Mysql28 database design specification
[recommended by bloggers] C WinForm regularly sends email (with source code)
Texttext data enhancement method data argument
Use of dataset of pytorch
Ansible实战系列二 _ Playbook入门
Breadth first search rotten orange
CSDN问答标签技能树(二) —— 效果优化
MySQL主从复制、读写分离
Baidu Encyclopedia data crawling and content classification and recognition