springboot-使用OpenAPI之后我再也没有写过接口文档
一 前言
这篇文章主要是带大家入门下如何使用OpenAPI
二 什么是 OpenAPI,
OpenAPI 是 一种基于Resful 风格 对 API进行格式化描述的一种规范; 允许你描述你整个项目的API,简单的讲就是一种接口文档生成的规范;包括如下几点 :
- 端点描述(如 GET /user , Post /user);
- 操作的参数,入输入参数,输出参数;
- 认证信息
三 什么是 Swagger
Swagger 由多个组件组成,它是一个开源的构建工具,其作用就是以 OpenAPI 为 规范基准, 能够帮助开发人员设计,构建文档,测试接口,文档规范化,和消费掉Restful API;说白了就是 OpenAPI 的实现,能够生成接口文档,以后不用自己手写了!!!
- Swagger Editor 是一个编辑工具,可以编辑描述API;
- Swagger UI 能让OpenAPI呈现出规范的可交互的API文档,以供他人查阅;
- Swagger Codegen 基于OpenAPI规范 能够生成客户端类库,服务端文档和存根,并且支持多语言,支持使用Docker,jar等方式运行构建;
更多组件详细看官网:swagger doc,看了官网的ylm格式基本结构晕,一堆黑的,客户体验非常不友好吐槽一下!看了github是基于JAX-RS 应用 ,不是很懂,再吐槽一下;
四 API生成
4.1 相关注释

4.2 pom.xml
<dependencies>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.22</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.22</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<optional>true</optional>
</dependency>
</dependencies>4.3 swagger配置
//主要是配置一些项目得基本信息,注解路径,项目主要联系人等;比较重要是@EnableSwagger2表示开启Swagger;
onfiguration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
// 构建文档
Docket docket = new Docket(DocumentationType.SWAGGER_2);
// 文档信息
Docket build = docket.apiInfo(apiInfo())
// 查询
.select()
// 注解包的路径
.apis(RequestHandlerSelectors.basePackage("com.zszxz.swagger.controller"))
// 任何路径
.paths(PathSelectors.any())
.build();
return build;
}
private ApiInfo apiInfo() {
// 文档对象构建器
ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder();
// 文档标题
ApiInfo apiInfo = apiInfoBuilder.title("知识追寻者(公众号) API doc")
// 描述信息
.description("知识追寻者第一次操作OpenAPI!!!!!")
// 版本号
.version("v1")
// 联系人
.contact(new Contact("知识追寻者", "", "lsc50534314@"))
// 声明许可
.license("知识追寻者许可")
// 许可路径,这边是我的github
.licenseUrl("https:///zszxz")
.build();
return apiInfo;
}
}## 4.4 实体@Data
@ApiModel(description = "用户知识追寻者实体")
public class ZSZXZ {
@ApiModelProperty(value = "姓名",dataType = "String")
private String name;
@ApiModelProperty(value = "邮件",dataType = "String")
private String email;
@ApiModelProperty(value = "爱好",dataType = "String")
private String hobby;
}4.5 controller
@RestController
// 资源信息
@Api(value = "知识追寻者文档API")
public class SwaggerController {
// 方法注释
@ApiOperation(value = "获取用户")
// 响应信息
@ApiResponse(code = 200,message = "获取用户列表成功")
@GetMapping("zszxz")
public ResponseEntity getUser(){
ZSZXZ zszxz = new ZSZXZ();
zszxz.setName("知识追寻者");
zszxz.setHobby("爱睡觉");
zszxz.setEmail("不告诉你");
return ResponseEntity.ok(zszxz);
}
// 方法注释
@ApiOperation(value = "跟据用户编号获取用户")
// 响应信息
@ApiResponses({@ApiResponse(code = 200,message = "获取用户列表成功")
,@ApiResponse(code = 204,message = "没有内容")})
// 参数信息
@ApiImplicitParam(name = "id", value = "用户编号", dataType = "ZSZXZ",required = true, paramType = "path")
@GetMapping("zszxz/{id}")
public ResponseEntity getUserById(@PathVariable Long id){
ZSZXZ zszxz = new ZSZXZ();
zszxz.setName("知识追寻者");
zszxz.setHobby("爱睡觉");
zszxz.setEmail("不告诉你");
return ResponseEntity.ok(zszxz);
}
@PostMapping("zszxz")
// 响应信息
@ApiResponse(code = 201,message = "添加用户列表成功")
// 方法信息
@ApiOperation(value = "添加用户")
public ResponseEntity addUser(@RequestBody ZSZXZ zszxz){
System.out.println("save the user:"+zszxz);
return ResponseEntity.ok("success save the user");
}
// 响应信息
@ApiResponse(code = 200,message = "修改用户成功")
@ApiOperation(value = "修改用户",notes = "修改用户")
@PutMapping("zszxz/{id}")
// 参数信息 多个参数使用注释中得内容, @RequestBody 修斯参数没必要写
/*@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用户编号", dataType = "Long",required = true,paramType = "path")
,@ApiImplicitParam(name = "user", value = "用户", dataType = "ZSZXZ",required = true, paramType = "json")})*/
@ApiImplicitParam(name = "id", value = "用户编号", dataType = "Long",required = true,paramType = "path")
public ResponseEntity updateUser(@PathVariable Long id ,@RequestBody ZSZXZ zszxz){
System.out.println("update the user:"+zszxz);
return ResponseEntity.ok("success update the user,the number is :"+id);
}
// 响应信息
@ApiResponses({@ApiResponse(code = 200,message = "删除用户成功")
,@ApiResponse(code = 401,message = "没有权限")
})
@ApiOperation(value = "删除用户")
@DeleteMapping("zszxz/{id}")
@ApiImplicitParam(name = "id", value = "用户编号", dataType = "Long",required = true,paramType = "path")
public ResponseEntity updateUser(@PathVariable Long id ){
System.out.println("delete the user :"+id);
return ResponseEntity.ok("delete the user :"+id);
}
}4.6 生成结果
默认路径:localhost:8080/swagger-ui.html#/  openai api embedding接口_spring boot_02](https://s2.51cto.com/images/blog/202410/15122745_670def41a6bf825138.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_30,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=/resize,m_fixed,w_1184)
4.7 查看实体

五 注解参数
@Api:
作用在类上,用来标注该类具体实现内容。表示标识这个类是swagger的资源 。
参数:
- tags:可以使用tags()允许您为操作设置多个标签的属性,而不是使用该属性。
- description:可描述描述该类作用。
@ApiImplicitParam:
作用在方法上,表示单独的请求参数
参数:
- name :参数名。
- value : 参数的具体意义,作用。
- required : 参数是否必填。
- dataType :参数的数据类型。
- paramType :查询参数类型,这里有几种形式:
类型 | 作用 |
path | 以地址的形式提交数据 |
query | 直接跟参数完成自动映射赋值 |
body | 以流的形式提交 仅支持POST |
header | 参数在request headers 里边提交 |
form | 以form表单的形式提交 仅支持POST |
在这里我被坑过一次:当我发POST请求的时候,当时接受的整个参数,不论我用body还是query,后台都会报Body Missing错误。这个参数和SpringMvc中的@RequestBody冲突,索性我就去掉了paramType,对接口测试并没有影响。
@ApiImplicitParams:
用于方法,包含多个 @ApiImplicitParam:
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "book's name", required = true, dataType = "Long", paramType = "query"),
@ApiImplicitParam(name = "date", value = "book's date", required = false, dataType = "string", paramType = "query")})@ApiModel:
用于类,表示对类进行说明,用于参数用实体类接收;
@ApiModelProperty:
用于方法,字段 ,表示对model属性的说明或者数据操作更改
例:
@ApiModel(value = "User", description = "用户")
public class User implements Serializable{
private static final long serialVersionUID = 1546481732633762837L;
/**
* 用户ID
*/
@ApiModelProperty(value = "用户ID", required = true)
@NotEmpty(message = "{id.empty}", groups = {Default.class,New.class,Update.class})
protected String id;
/**
* code/登录帐号
*/
@ApiModelProperty(value = "code/登录帐号")
@NotEmpty(message = "{itcode.empty}", groups = {Default.class,New.class,Update.class})
protected String itcode;
/**
* 用户姓名
*/
@ApiModelProperty(value = "用户姓名")
@NotEmpty(message = "{name.empty}", groups = {Default.class,New.class,Update.class})
protected String name;@ApiOperation:
@ApiOperation(value = "获取图书信息", notes = "获取图书信息", response = Book.class, responseContainer = "Item", produces = "application/json")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "book's name", required = true, dataType = "Long", paramType = "query"),
@ApiImplicitParam(name = "date", value = "book's date", required = false, dataType = "string", paramType = "query")})
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public Book getBook(@PathVariable Long id, String date) {
return books.get(id);
}用于方法,表示一个http请求的操作 。
@ApiResponse:
用于方法,描述操作的可能响应。
@ApiResponses:
用于方法,一个允许多个ApiResponse对象列表的包装器。
@ApiParam:
用于方法,参数,字段说明,表示对参数的添加元数据(说明或是否必填等)
@ApiResponses(value = {
@ApiResponse(code = 500, message = "2001:因输入数据问题导致的报错"),
@ApiResponse(code = 500, message = "403:没有权限"),
@ApiResponse(code = 500, message = "2500:通用报错(包括数据、逻辑、外键关联等,不区分错误类型)")})@Authorization:
声明要在资源或操作上使用的授权方案。
@AuthorizationScope:
介绍一个OAuth2授权范围。
@ResponseHeader:
响应头设置,使用方法。
















