Swagger快速上手入门1.0

Swagger2

最近收到老大要求,需要把swagger引入,对API进行测试,并且形成文档。文档和代码可以同步更新。
于是就对Swagger2做一些记录,项目使用的是基于springboot引入的。

引入Swagger2

maven pom.xml 依赖

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>

        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.13</version>
        </dependency>

快速跳过….

添加配置的class类:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket config() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("XXXXAPI文档")
                .contact(new Contact("name", "API地址", "联系方式"))
                .build();
    }
}

basePackage(“com.xxx.controller”) 让swagger能够扫描到你的接口,也就是controller包
@Configuration 相当于配置文件xml中的 beans
@Bean 相当于配置文件xml中的 bean
以此类推,springmvc项目可以这样配置。

注解controller

例如:
@Api(description = “”) : 作用于Controller类,对整个类的描述
@ApiOperation(value=”“) : 作用于方法,对方法的描述
@ApiParam(name = “token”, value = “token”,required = true):作用于方法内的参数

@Api(description = "首页接口")
@Controller
@RequestMapping("/home")
public class HomeController {

 @ApiOperation(value="首页", notes="默认参数code='xiaoyuan'")
    @RequestMapping("/index")
    @ResponseBody
    private ResultObject index(
        @ApiParam(name = "code", value = "code",required = true)
        @RequestParam("code")String code){

        .....
    }

}

重启项目,直接请求 http://localhost:8001/v2/api-docs (端口配置自己项目设置的) 就能看到一堆json,但是这样看很挫。

这里写图片描述

使用Swagger-ui生成美丽的文档

于是Swagger-ui,转换成美丽的样式。
到githut下载Swagger-UI: https://github.com/swagger-api/swagger-ui

下载完之后找到dist/index.html,修改如下

  window.onload = function() {

      // Build a system
      const ui = SwaggerUIBundle({
        //url: "http://petstore.swagger.io/v2/swagger.json",  //这个是GitHub官方的
        url: "http://localhost:8001/v2/api-docs",  //修改如下 /v2/api-docs 
        dom_id: '#swagger-ui',
        deepLinking: true,
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIStandalonePreset
        ],
        plugins: [
          SwaggerUIBundle.plugins.DownloadUrl
        ],
        layout: "StandaloneLayout"
      })

      window.ui = ui
    }

保存之后直接打开 index.html

这里写图片描述

最后直接把这个东西丢给老大,估计不会被怼把?

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值