接口文档 – Swagger2的使用
1,api一定需要开发文档配合,移动端只需要根据开发文档进行开发即可;
2,传统的开发文档问题:格式随意,更新不及时;
https://www.jianshu.com/p/d7b13670e0eb
1.swagger2
2 小么鸡
3.Apizza
4.Yapi showdoc easydoc
配置依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
配置文件定义API
@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
@Bean
public Docket productApi() {
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
tokenPar.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("cn.wolfcode.wolf2w.controller"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars)
.apiInfo(metaData());
}
private ApiInfo metaData() {
return new ApiInfoBuilder()
.title("SpringBoot集成Swagger2")
.description("狼行天下项目接口文档")
.version("1.0.0")
.license("Apache License Version 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0")
.build();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
访问
http://localhost:8080/swagger-ui.html
常见标签
@Api/@ApiOperation
@Api:用在类上,说明该类的作用
@Api(value = "用户资源",description = "用户资源控制器")
@ApiOperation:用在方法上,说明方法的作用
@ApiOperation(value = "注册功能",notes = "其实就是新增用户")
@ApiImplicitParams/@ApiImplicitParam
@ApiImplicitParams:用在方法上包含一组参数说明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
paramType:参数放在哪个地方
header-->请求参数的获取
query-->请求参数的获取
path-->请求参数的获取(用于restful接口):
body-->请求实体中
@ApiImplicitParams({
@ApiImplicitParam(value = "昵称",name = "nickName",dataType = "String",required = true),
@ApiImplicitParam(value = "邮箱",name = "email",dataType = "String",required = true),
@ApiImplicitParam(value = "密码",name = "password",dataType = "String",required = true)
})
@ApiModel/@ApiModelProperty
@ApiModel:描述一个Model的信息
(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModelProperty:描述一个model的属性
@ApiModel(value="用户",description="平台注册用户模型")
@ApiModelProperty(value="昵称",name="nickName",dataType = "String",required = true)
@ApiResponses/@ApiResponse
@ApiResponses:用于表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息(200相应不写在这里面)
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出的异常类
@ApiResponses({
@ApiResponse(code=200,message="用户注册成功")
})
@ApiIgnore
有些接口不想显示,就贴上去,可以贴在类上,也可以贴在方法上。