Swagger 3.0 使用指南
Swagger 官网地址:https://swagger.io/
1.Swagger 是什么?
API Developmentfor Everyone
Simplify API development for users, teams, and enterprises with the Swagger open source and professional toolset. Find out how Swagger can help you design and document your APIs at scale.
面向所有人的 API 开发
使用 Swagger 开源和专业工具集简化用户、团队和企业的 API 开发。 了解 Swagger 如何帮助您大规模设计和记录您的 API。
2.Swagger 与OAS 之间存在什么关系?
OpenAPI Specification
The World Standard for RESTful APIs
The OpenAPI Specification was donated to the Linux Foundation under the OpenAPI Initiative in 2015. The specification creates a RESTful interface for easily developing and consuming an API by effectively mapping all the resources and operations associated with it.
OpenAPI 规范
(全球)标准的RESTful API
OpenAPI 规范于 2015 年在 OpenAPI 倡议下捐赠给 Linux 基金会。该规范创建了一个 RESTful 接口,通过有效地映射关联的所有资源和操作来轻松开发和使用 API。
- OAS 全称是 Open Api Specification,Open API的规范
- Swagger 是一个开源工具,该工具遵循OpenAPI规范,是OpenAPI规范的一个实现
3.找不见Swagger官网使用说明,该怎么办?
说实话,第一次使用的时候,看遍官方所有的页面,完全找不见官方的使用方法、引入依赖、配置等。看了好多博客,真NM全是废话,光说怎么用呢,不说是怎么来的。迫于无奈,最后通过搜索关键字,找见入口内容。
步骤:
搜索关键字:java -> 选择Java Integration(Java 集成) -> 根据语言选择合适的Swagger框架
Java语言选择SpringFox框架即可,SpringFox官网已经存在3.0+版本。
SpringFox: 与SpringMVC继承、并且支持Swagger1.2和Swagger2.0。
springFox 官网文档地址(内容未更新,主要还是swagger2.0):https://springfox.github.io/springfox/
建议参考SprignFox的github仓库中README.MD文件:https://github.com/springfox/springfox
4.Swagger 使用指南
4.1 引入springfox starter依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
4.2 创建SwaggerConfig配置文件
springfox 3.0 中需要使用@EnableOpenApi,@EnableSwagger2该注解已经废弃。
可参考SpringFox 官方文档:http://springfox.github.io/springfox/docs/current/#getting-started
package com.xxx.springboot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.Arrays;
import java.util.HashSet;
/**
* swagger配置文件
* @author admin
*/
@EnableOpenApi
@Configuration
public class SwaggerConfig {
@Bean
Docket api() {
// springfox 的基本API配置
return new Docket(DocumentationType.OAS_30)
// 将映射的路径当作base Path,添加给apis
.pathMapping("/")
// 设置api 文档基本信息: 常见内容:版本,主题,联系人...
.apiInfo(new ApiInfoBuilder()
.contact(new Contact("xxx", "www.baidu.com", "9999999@qq.com"))
.description("web api doc")
.title("WEB API DOC")
.version("1.0")
.build())
// 分类,可根据groupName选择不同的api 列表
.groupName("public api")
// 设置host信息
.host("http://192.168.0.1:8080")
// 支持的协议
.protocols(new HashSet<>(Arrays.asList("http", "https")))
.enable(true)
// 创建API 选择器
.select()
// 暴露的给Swagger的API,指定扫描包的接口
.apis(RequestHandlerSelectors.basePackage("com.xxx"))
// 符合要求的接口
.paths(PathSelectors.ant("/user/**"))
.build();
}
}
注意:高版本SpringBoot与SpringFox 3.0 整合时,会出现空指针异常。
解决办法:
application.properties配置文件中添加以下内容
# springboot 高版本处理 swagger 空指针问题
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
4.3 创建API接口
需要在接口上面添加springfox提供的注解.
相关注解使用可参考:https://github.com/swagger-api/swagger-core/wiki/Swagger-2.X—Annotations#quick-annotation-overview
4.3.1 相关注解
OpenAPI
Name |
Description |
@OpenAPIDefinition |
General metadata for an OpenAPI definition |
@Info |
Info metadata for an OpenAPI definition |
@Contact |
Properties to describe the contact person for an OpenAPI definition |
@License |
Properties to describe the license for an OpenAPI definition |
Operations
Name |
Description |
@Operation |
Describes an operation or typically a HTTP method against a specific path. |
@Parameter |
Represents a single parameter in an OpenAPI Operation. |
@RequestBody |
Represents the body of the request in an Operation |
@ApiResponse |
Represents the response in an Operation |
@Tag |
Represents tags for an operation or for the OpenAPI definition. |
@Server |
Represents servers for an operation or for the OpenAPI definition. |
@Callback |
Describes a set of requests |
@Link |
Represents a possible design-time link for a response. |
Media
Name |
Description |
@Schema |
Allows the definition of input and output data. |
@ArraySchema |
Allows the definition of input and output data for array types. |
@Content |
Provides schema and examples for a particular media type. |
4.2 定义API接口
package com.xxx.springboot.controller;
import com.xxx.springboot.controller.response.UserResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 用户接口类
* @author admin
*/
@Tag(name = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {
@Operation(tags = "用户管理", summary = "获取用户信息", description = "获取指定用户的用户信息")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "成功", content = {
@Content(mediaType = "application/json")
}),
@ApiResponse(responseCode = "400", description = "失败", content = {
@Content(mediaType = MediaType.APPLICATION_JSON_VALUE)
}),
})
@GetMapping(value = "/{user_id}")
public UserResponse getUserInfo(
@Parameter(name = "user_id", description = "用户信息ID")
@PathVariable(name = "user_id") String userId) {
return UserResponse.builder()
.id(userId)
.name("lisi")
.address("shanxi")
.age(20)
.build();
}
}
4.4 启用工程,浏览器访问,查看效果
地址:http://localhost:8080/swagger-ui/index.html