Swagger 接口开发测试工具

面试:你懂什么是分布式系统吗?Redis分布式锁都不会?>>>   hot3.png

1. Swagger介绍

OpenAPI规范(OpenAPI Specification 简称OAS)是Linux基金会的一个项目,试图通过定义一种用来描述API格式或API定义的语言,来规范RESTful服务开发过程,目前版本是V3.0,并且已经发布并开源在github上。 https://github.com/OAI/OpenAPI-Specification

Swagger是全球最大的OpenAPI规范(OAS)API开发工具框架,支持从设计和文档到测试和部署的整个API生命周期的开发。(https://swagger.io/)

Spring Boot 可以集成Swagger,生成Swagger接口,Spring Boot是Java领域的神器,它是Spring项目下快速构建项目的框架。

2. Swagger常用注解

在Java类中添加Swagger的注解即可生成Swagger接口,常用Swagger注解如下:

@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiModelProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息
@ApiImplicitParam:一个请求参数
@ApiImplicitParams:多个请求参数

3. Swagger接口定义

修改接口工程中页面查询接口,添加Swagger注解。

@Api(value="cms页面管理接口",description = "cms页面管理接口,提供页面的增、删、改、查")
public interface CmsPageControllerApi {

	@ApiOperation("分页查询页面列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name="page",value = "页码",required=true,paramType="path",dataType="int"),
		@ApiImplicitParam(name="size",value = "每页记录数",required=true,paramType="path",dataType="int")
	})
	public QueryResponseResult findList(int page, int size, 		QueryPageRequest queryPageRequest) ;
}

在QueryPageRequest类中使用注解 ApiModelProperty 对属性注释:

@Data
@ToString
public class QueryPageRequest extends RequestData {
	//站点id
	@ApiModelProperty("站点id")
	private String siteId;
	//页面ID
	@ApiModelProperty("页面ID")
	private String pageId;
	//页面名称
	@ApiModelProperty("页面名称")
	private String pageName;
	//页面别名
	@ApiModelProperty("页面别名")
	private String pageAliase;
	//模版id
	@ApiModelProperty("模版id")
	private String templateId;
}

4. 编写Swagger扫描类

在Api接口工程编写config类Swagger2Configuration

@Configuration
@EnableSwagger2
public class Swagger2Configuration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.guohao"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("api文档")
                .description("api文档")
//                .termsOfServiceUrl("/")
                .version("1.0")
                .build();
    }

}

5. Swagger接口测试

Swagger接口生成工作原理:

1、系统启动,扫描到api工程中的Swagger2Configuration类;
2、在此类中指定了包路径com.xuecheng,找到在此包下及子包下标记有@RestController注解的controller类;
3、根据controller类中的Swagger注解生成接口文档。

启动cms服务工程,查看接口文档,请求:http://localhost:31001/swagger-ui.html

使用Swagger工具测试服务接口:
1)在服务接口中打断点;
2)打开接口文档页面,输入请求参数,点击“Try it out”发起请求。

你可能感兴趣的:(Swagger 接口开发测试工具)