1、什么是swagger?

Swagger 是一款目前世界最流行的API管理工具,是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。文档提供了一个方法,我们可以用指定的 JSON 或者 YAML 摘要来描述你的 API,包括了比如 names、order 等 API 信息。你可以通过一个文本编辑器来编辑 Swagger 文件,或者你也可以从你的代码注释中自动生成。各种工具都可以使用 Swagger 文件来生成互动的 API 文档。

2、使用swagger

  • maven
  <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>
        <!-- https://mvnrepository.com/artifact/io.github.swagger2markup/swagger2markup -->
        <dependency>
            <groupId>io.github.swagger2markup</groupId>
            <artifactId>swagger2markup</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.swagger/swagger-core -->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-core</artifactId>
            <version>1.5.22</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.swagger/swagger-models -->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.22</version>
        </dependency>
  • 在application.yml中加入:
swagger:
 enable: true
  • 编写配置文件
@EnableSwagger2
@Configuration
@ConditionalOnProperty(name = "swagger.enable",havingValue ="true")
public class Swagger2Config {

  @Bean
  public Docket createRestApi() {

      return new Docket(DocumentationType.SWAGGER_2)
              .apiInfo(apiInfo())
              .select()
              .apis(RequestHandlerSelectors.any())
              .paths(PathSelectors.any())
              .build();
  }

  //构建 api文档的详细信息函数
  private ApiInfo apiInfo() {
      return new ApiInfoBuilder()
              //页面标题
              .title("功能测试")
              //创建人
              .contact(new Contact("author", "url", "email"))
              //版本号
              .version("1.0")
              //描述
              .description("API 描述")
              .build();
  }
}
  • 常用注解
  • @Api
    该注解将一个Controller(Class)标注为一个swagger资源(API)。在默认情况下,Swagger-Core只会扫描解析具有@Api注解的类,而会自动忽略其他类别资源(JAX-RS endpoints,Servlets等等)的注解。该注解包含以下几个重要属性:
    tags
    API分组标签。具有相同标签的API将会被归并在一组内展示。
    value
    如果tags没有定义,value将作为Api的tags使用
    description
    API的详细描述
@Api(tags = "登录模块",value = "管理用户登录")
@Controller
public class LoginController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    ```

@ApiOperation
在指定的(路由)路径上,对一个操作或HTTP方法进行描述。具有相同路径的不同操作会被归组为同一个操作对象。不同的HTTP请求方法及路径组合构成一个唯一操作。此注解的属性有:
value
对操作的简单说明,长度为120个字母,60个汉字。
notes
对操作的详细说明。
httpMethod
HTTP请求的动作名,可选值有:"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"。
code
默认为200,有效值必须符合标准的HTTP Status Code Definitions。
@ApiImplicitParams
注解ApiImplicitParam的容器类,以数组方式存储。
@ApiImplicitParam
对API的单一参数进行注解。虽然注解@ApiParam同JAX-RS参数相绑定,但这个@ApiImplicitParam注解可以以统一的方式定义参数列表,也是在Servelet及非JAX-RS环境下,唯一的方式参数定义方式。可以设置以下重要参数属性:
name
参数名称
value
参数的简短描述
required
是否为必传参数
dataType
参数类型,可以为类名,也可以为基本类型(String,intboolean等)
paramType
参数的传入(请求)类型,可选的值有path, query, body, header or form。
@ApiParam
增加对参数的元信息说明。这个注解只能被使用在JAX-RS 1.x/2.x的综合环境下。其主要的属性有:
required
是否为必传参数
value
参数简短说明
```java
@ApiOperation(value = "登录接口",httpMethod = "POST")
@ApiImplicitParams({
        @ApiImplicitParam(name = "username",value = "账号",required = true,dataType = "String",paramType = "query"),
        @ApiImplicitParam(name = "password",value = "密码",required = true,dataType = "String",paramType = "query"),
        @ApiImplicitParam(name = "verify",value = "验证码",required = true,dataType = "String",paramType = "query"),
})
@Log("登录")
@PostMapping("/login")
@ResponseBody
R ajaxLogin(String username, String password,String verify,HttpServletRequest request) {
  • Model的注解

对于Model的注解,Swagger提供了两个:@ApiModel及@ApiModelProperty,分别用以描述Model及Model内的属性。
@ApiModel
提供对Swagger model额外信息的描述。在标注@ApiOperation注解的操作内,所有的类将自动被内省(introspected),但利用这个注解可以做一些更加详细的model结构说明。主要属性有:
value
model的别名,默认为类名
description
model的详细描述

@ApiModel(value = "用户表")
public class UserDO implements Serializable 
  • @ApiModelProperty

对model属性的注解,主要的属性值有:
value
属性简短描述
example
属性的示例值
required
是否为必须值

/ 邮箱
@ApiModelProperty(name = "email",value = "邮箱",dataType = "String")
private String email;
// 手机号
@ApiModelProperty(name = "mobile",value = "手机号",dataType = "String")
private String mobile;
// 状态 0:禁用,1:正常
@ApiModelProperty(name = "status",value = "状态 0:禁用,1:正常",dataType = "Integer")
private Integer status;
// 创建用户id
@ApiModelProperty(name = "userIdCreate",value = "创建用户id",dataType = "Long")
private Long userIdCreate;
// 创建时间
@ApiModelProperty(name = "gmtCreate",value = "创建时间",dataType = "Date")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date gmtCreate;
  • 前端ui路径

http://localhost:8082/swagger-ui.html

  • 页面效果

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • 测试

在这里插入图片描述
在这里插入图片描述

生成离线文档

package com.jr.testDemo;
import com.jr.JrInvoiceManageBackendApplication;
import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.Language;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.net.URL;
import java.nio.file.Paths;

@RunWith(SpringRunner.class)
//设定端口,申明启动类!!重要
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = JrInvoiceManageBackendApplication.class)
public class SwaggerTo {

    /**
     * 生成AsciiDocs格式文档
     * @throws Exception
     */
    @Test
    public void generateAsciiDocs() throws Exception {
        //    输出Ascii格式
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL("http://localhost:8082/v2/api-docs"))
                .withConfig(config)
                .build()
                .toFolder(Paths.get("//docs/asciidoc/generated/"));
    }

    /**
     * 生成Markdown格式文档
     * @throws Exception
     */
    @Test
    public void generateMarkdownDocs() throws Exception {
        //    输出Markdown格式
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.MARKDOWN)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL("http://localhost:8082/v2/api-docs"))
                .withConfig(config)
                .build()
                .toFolder(Paths.get("/docs/asciidoc/generated/"));
    }
//  /**
//   * 生成Confluence格式文档
//   * @throws Exception
//   */
//  @Test
//  public void generateConfluenceDocs() throws Exception {
//      //    输出Confluence使用的格式
//      Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
//              .withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP)
//              .withOutputLanguage(Language.ZH)
//              .withPathsGroupedBy(GroupBy.TAGS)
//              .withGeneratedExamples()
//              .withoutInlineSchema()
//              .build();
//
//      Swagger2MarkupConverter.from(new URL("http://localhost:8016/v2/api-docs"))
//              .withConfig(config)
//              .build()
//              .toFolder(Paths.get("./docs/confluence/generated"));
//  }

    /**
     * 生成AsciiDocs格式文档,并汇总成一个文件
     * @throws Exception
     */
    @Test
    public void generateAsciiDocsToFile() throws Exception {
        //    输出Ascii到单文件
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL("http://localhost:8082/v2/api-docs"))
                .withConfig(config)
                .build()
                .toFile(Paths.get("./docs/asciidoc/generated/all"));
    }

    /**
     * 生成Markdown格式文档,并汇总成一个文件
     * @throws Exception
     */
    @Test
    public void generateMarkdownDocsToFile() throws Exception {
        //    输出Markdown到单文件
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.MARKDOWN)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL("http://localhost:8082/v2/api-docs"))
                .withConfig(config)
                .build()
                .toFile(Paths.get("./docs/markdown/generated/all"));
    }
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐