Swagger2由入门到实战

一、为什么使用Swagger2
当下很多公司都采取前后端分离的开发模式,前端和后端的工作由不同的工程师完成。在这种开发模式下,维持一份及时更新且完整的 Rest API 文档将会极大的提高我们的工作效率。传统意义上的文档都是后端开发人员手动编写的,相信大家也都知道这种方式很难保证文档的及时性,这种文档久而久之也就会失去其参考意义,反而还会加大我们的沟通成本。而 Swagger 给我们提供了一个全新的维护 API 文档的方式,下面我们就来了解一下它的优点:

1、代码变,文档变。只需要少量的注解,Swagger 就可以根据代码自动生成 API 文档,很好的保证了文档的时效性。

2、跨语言性,支持 40 多种语言。

3、Swagger UI 呈现出来的是一份可交互式的 API 文档,我们可以直接在文档页面尝试 API 的调用,省去了准备复杂的调用参数的过程。

4、还可以将文档规范导入相关的工具(例如 Postman、SoapUI), 这些工具将会为我们自动地创建自动化测试。

二.配置使用Swagger2

1、在pom.xml加入swagger2相关依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xncoding</groupId>
    <artifactId>springboot-swagger2</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot-swagger2</name>
    <description>集成Swagger2</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>com.vaadin.external.google</groupId>
                    <artifactId>android-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.11</version>
        </dependency>

        <!-- swagger2 集成-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.pegdown</groupId>
            <artifactId>pegdown</artifactId>
            <version>1.6.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.github.swagger2markup</groupId>
            <artifactId>swagger2markup</artifactId>
            <version>1.3.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
        <!--将mapper文件打包进去-->
        <resources>

            <resource>
                <!--指定根目录 到源文件夹 一般如下-->
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.yaml</include>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource> <!--指定根目录 到源文件夹 一般如下-->
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.yaml</include>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

</project>

2.新建Swagger2的配置类

/**
 * Swagger2的Java配置类
 *
 * @author XiongNeng
 * @version 1.0
 * @since 2018/1/7
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .produces(Sets.newHashSet("application/json"))
                .consumes(Sets.newHashSet("application/json"))
                .protocols(Sets.newHashSet("http", "https"))
                .apiInfo(apiInfo())
                .forCodeGeneration(true)
                .select()
                // 指定controller存放的目录路径
                .apis(RequestHandlerSelectors.basePackage("com.cjlcoding.jwt"))
//                .paths(PathSelectors.ant("/api/v1/*"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 文档标题
                .title("系统API服务")
                // 文档描述
                .description("系统API接口文档")
                // .termsOfServiceUrl("https://github.com")
                .version("v1")
                // .license("MIT 协议")
                // .licenseUrl("http://www.opensource.org/licenses/MIT")
                // .contact(new Contact("chenjl","https://github.com/yidao620c","453252@gmail.com"))
                .build();
    }
}

三、Swagger2注解详解
关于请求方式和请求路径,swagger默认为类上的请求方式添加解释说明, 自动生成显示对应方法的请求方式和访问方法的相对路径。

1、@Api :请求类的说明

@Api:放在请求的类上,与 @Controller 并列,说明类的作用,如人行衍生类,信天翁类,公安部类等。
tags=“说明该类的作用”
value=“该参数没什么意义,所以不需要配置”
description=“类功能性描述”(过时)

注:如果没指定tags,tags默认值与类名保持一致,description默认与类名保持一致

举例 @Api:

@Api(tags = {"生成随机数相关模块"},value = "我不显示",description = "生成随机数的类")
@RestController
@RequestMapping("/dynamistic/grow")
public class Practice2 {
}

2、@ApiOperation:方法的说明

@ApiOperation:“用在请求的方法上,说明方法的作用”
value=“说明方法的作用”
notes=“方法的备注说明”

举例 @ApiOperation:

@ApiOperation(value = "生成bitNum位radix进制随机数,值得类型valueType", notes = "用于生成二维码的数据源")
@GetMapping("/random")
public GrowNum growRandomNum(@RequestParam int bitNum,
                             @RequestParam String radix,
                             @RequestParam String valueType) {
    return new GrowNum();
}

3、@ApiImplicitParams、@ApiImplicitParam:方法参数的说明

@ApiImplicitParams:用在请求的方法上,包含一组参数说明
@ApiImplicitParam:对单个参数的说明
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(用于restful接口)–> 请求参数的获取:@PathVariable
· body(请求体)–> @RequestBody User user
· form(普通表单提交)
dataType:参数类型,默认String,其它值dataType=“int”
defaultValue:参数的默认值

@ApiImplicitParams、@ApiImplicitParam举例

@ApiImplicitParams({
            @ApiImplicitParam(name = "bitNum", value = "位", required = true, paramType = "Integer"),
            @ApiImplicitParam(name = "radix", value = "进制", required = true, paramType = "String"),
            @ApiImplicitParam(name = "valueType", value = "随机数类型", required = false, paramType = "String")
    })
    @GetMapping("/random")
    public GrowNum growRandomNum(@RequestParam int bitNum,
                                 @RequestParam String radix,
                                 @RequestParam String valueType) {
        return new GrowNum();
    }

4、@ApiResponses、@ApiResponse:方法返回值的说明

@ApiResponses:方法返回对象的说明
@ApiResponse:每个参数的说明
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类

举例@ApiResponses、@ApiResponse:

@ApiResponses(value = {
        @ApiResponse(code = 200, message = "请求已完成"),
        @ApiResponse(code = 201,message = "资源成功被创建"),
        @ApiResponse(code = 400,message = "请求中有语法问题,或不能满足请求"),
        @ApiResponse(code = 401,message = "未授权客户机访问数据"),
        @ApiResponse(code = 403,message = "服务器接受请求,但是拒绝处理"),
        @ApiResponse(code = 404,message = "服务器找不到给定的资源;文档不存在"),
        @ApiResponse(code = 500,message = "服务器出现异常")
})
@RestController
@RequestMapping("/dynamistic/grow")
public class Practice2 {
}

5、@ApiModel:用于JavaBean上面,表示一个JavaBean
@ApiModel:用于JavaBean的类上面,表示此 JavaBean 整体的信息
(这种一般用在post创建的时候,使用 @RequestBody 这样的场景,请求参数无法使用 @ApiImplicitParam 注解进行描述的时候 )

6. @ApiModelProperty:用在JavaBean的属性上面,说明属性的含义

举例 @ApiModel和 @ApiModelProperty:

@ApiModel("生成随机数的相关属性model")
@Component
public class GrowNum {

    @ApiModelProperty("随机数的位数")
    private Integer bitNum;

    @ApiModelProperty("进制数")
    private String radix;

    @ApiModelProperty("随机数值的类型")
    private String valueType;
 }

启动项目页面访问路径:http://localhost:8080/swagger-ui.html

完整代码已经上传到gitee上,路径:https://gitee.com/maganminga/springboot-buckets/tree/master/springboot-swagger2

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Swagger是一种用于设计、构建、文档化和使用RESTful Web服务的开源工具集。它提供了一种简单且强大的方式来描述API,以及生成交互式文档、客户端SDK和服务端存根代码。下面是关于Swagger入门到精通的步骤: 1. 安装Swagger:首先,你需要安装Swagger工具集。你可以从Swagger官方网站或者通过包管理工具(如npm、pip等)来安装Swagger。 2. 创建Swagger文档:一旦安装完成,你可以开始创建Swagger文档。Swagger使用YAML或JSON格式来描述API。你可以通过编辑器(如Swagger Editor)或者直接编写YAML/JSON文件来创建文档。 3. 定义API:在Swagger文档中,你需要定义API的各个方面,包括路径、HTTP方法、请求参数、响应数据等。你可以使用Swagger提供的规范来定义API的各个部分。 4. 添加元数据:除了API定义,你还可以添加一些元数据,如API的标题、描述、版本号等。这些信息将在生成的文档中显示,并帮助用户更好地理解和使用你的API。 5. 生成文档:一旦你完成了Swagger文档的编写,你可以使用Swagger工具集中的工具来生成交互式文档。这些文档将提供给开发人员和用户,以便他们了解和使用你的API。 6. 测试API:Swagger还提供了一些工具来测试API。你可以使用Swagger UI来发送请求并查看响应数据。这样可以确保你的API按照预期工作,并帮助你发现和解决潜在的问题。 7. 生成客户端SDK和服务端存根代码:Swagger还可以根据API定义生成客户端SDK和服务端存根代码。这些代码将帮助开发人员更轻松地集成和使用你的API。 8. 部署和使用API:最后,你需要将API部署到服务器上,并让用户使用它。你可以将生成的文档和代码提供给用户,以便他们能够快速上手并开始使用你的API。 通过以上步骤,你可以从入门到精通地使用Swagger来设计、构建、文档化和使用RESTful Web服务。记得不断学习和实践,掌握更多高级功能和最佳实践,以提升你的Swagger技能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叶枫^_^

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值