还在手动维护API文档吗?是时候用用丝袜哥(swagger)了!

在现在微服务满天飘的年代,一个稍微大点的项目就可能有10几个服务,每个服务会产生很多API互相调用,如果没有一个自动生成API文档的工具,那就有的搞了!

Swagger是一个简单但功能强大的API表达工具。它具有地球上最大的API工具生态系统,数以千计的开发人员,使用几乎所有的现代编程语言,都在支持和使用Swagger。使用Swagger生成API,我们可以得到交互式文档,自动生成代码的SDK以及API的发现特性等。

来体验一把吧!

Swagger

使用swagger能帮我们生成API文档,那么它会生成什么样的API文档呢?

OpenAPI

OpenAPI规范是Linux基金会的一个项目,试图通过定义一种用来描述API格式或API定义的语言,来规范RESTful服务开发过程。OpenAPI规范帮助我们描述一个API的基本信息。

比如:

  • 有关该API的一般性描述
  • 可用路径(/资源)
  • 在每个路径上的可用操作(获取/提交…)
  • 每个操作的输入/输出格式

根据OpenAPI规范编写的二进制文本文件,能够像代码一样用任何VCS工具管理起来一旦编写完成,API文档可以作为:

  • 需求和系统特性描述的根据
  • 前后台查询、讨论、自测的基础
  • 部分或者全部代码自动生成的根据
  • 其他重要的作用,比如开放平台开发者的手册…

编写API文档

Swagger官方提供了API文档在线编辑器:

http://editor.swagger.io/

我估计你现在打开的很慢,我已经打开了并截好了图等你来看:

在这里插入图片描述

左边编辑,右边随时预览,我这里提供了一个文档案例:

swagger: '2.0'
info:
  version: 1.0.0
  title: 测试Swagger 文档API
  description: 测试Swagger 文档API
  contact:
    name: 行百里er
    url: https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI1MDU1MjkxOQ==#wechat_redirect
    email: 888@qqq.com
  license:
    name: MIT
    url: http://opensource.org/licenses/MIT
schemes: 
  - http
  
host: traveler100.com
basePath: /api/v1

paths:
  /user/{mobile}:
    get:
      summary: 根据手机号码获取一个用户信息
      description: 根据手机号码获取一个用户信息
      parameters: 
        - name: mobile
          in: path
          required: true
          description: 手机号码
          type: string
      responses:
        200:
          description: OK
    
  /user/listUsers:
    get:
      summary: 返回List 包含所有用户
      description: 返回List 包含所有用户
      parameters:
          - name: pageSize
            in: query
            description: 每页显示多少
            type: integer
          - name: pageNum
            in: query
            description: 当前第几页
            type: integer
      
      responses:
        200:
          description: OK
          
          schema:
            type: array
            items: 
              required:
                - username
              properties:
                username:
                  type: string
                password:
                  type: string    

效果图:
在这里插入图片描述

屌不屌?

这种是先写文档再出代码,代码里会自动生成一些注解。

but,如果丝袜哥只提供这个,那就太差点意思了,需要自己编写文档,而且yml格式的东西,一不注意多个空格就会报错,还是没有解放我编写文档的双手!

所以,如你所料,它很贴心的提供了自动帮我们生成文档的神器!

Swagger集成SpringBoot

官方依赖:

<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.2.2</version>
</dependency>
<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.2.2</version>
</dependency>
<dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.13</version>
</dependency>

官方的这个用起来比较麻烦,我就不演示了,我们看一下第三方的专门使用spring-boot-starter的。

第三方spring-boot-starter-swagger

添加pom依赖

<dependency>
    <groupId>com.spring4all</groupId>
    <artifactId>swagger-spring-boot-starter</artifactId>
    <version>1.9.1.RELEASE</version>
</dependency>

配置文件

swagger:
  ui-config:
    api-sorter: alpha
    json-editor: true
    display-request-duration: true
  title: 测试Swagger 文档API
  contact:
    name: 公众号:行百里er
    email: 19193127929@qq.com
    url: https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI1MDU1MjkxOQ==#wechat_redirect
  base-package: com.travler100.test.swaggerdemo.controller

这个是我做演示的配置文件,配置项比较少。完整的配置可参考spring-boot-starter-swagger项目的github官网:

https://github.com/SpringForAll/spring-boot-starter-swagger

配置说明:

- swagger.enabled=是否启用swagger,默认:true
- swagger.title=标题
- swagger.description=描述
- swagger.version=版本
- swagger.license=许可证
- swagger.licenseUrl=许可证URL
- swagger.termsOfServiceUrl=服务条款URL
- swagger.contact.name=维护人
- swagger.contact.url=维护人URL
- swagger.contact.email=维护人email
- swagger.base-package=swagger扫描的基础包,默认:全扫描
- swagger.base-path=需要处理的基础URL规则,默认:/**
- swagger.exclude-path=需要排除的URL规则,默认:空
- swagger.host=文档的host信息,默认:空
- swagger.globalOperationParameters[0].name=参数名
- swagger.globalOperationParameters[0].description=描述信息
- swagger.globalOperationParameters[0].modelRef=指定参数类型
- swagger.globalOperationParameters[0].parameterType=指定参数存放位置,可选header,query,path,body.form
- swagger.globalOperationParameters[0].required=指定参数是否必传,true,false

项目中启用注解

  • @EnableSwagger2Doc 作用于启动类
@SpringBootApplication
@EnableSwagger2Doc
public class SwaggerDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SwaggerDemoApplication.class, args);
	}

}
  • @Api 作用于Controller、@ApiOperation 作用于方法
@RestController
@Api(tags = {"用户管理API"})
public class UserController {

    @ApiOperation(value = "获取用户列表")
    @RequestMapping(value = "/user/listUsers", method = RequestMethod.GET)
    public CommonResult<List<User>> listUsers() {
        List<User> list = new ArrayList<>();
        User u1 = new User();
        u1.setId(1L);
        u1.setUserName("张三");
        u1.setMobile("13888888888");
        u1.setAge(18);
        u1.setGender((byte) 1);

        User u2 = new User();
        u2.setId(2L);
        u2.setUserName("韩梅");
        u2.setMobile("13888888889");
        u2.setAge(20);
        u2.setGender((byte) 0);

        list.add(u1);
        list.add(u2);

        return CommonResult.success(list);
    }

    @ApiOperation(value = "根据手机号码获取用户信息")
    @RequestMapping(value = "/user/{mobile}", method = RequestMethod.GET)
    public CommonResult<User> user(@PathVariable("mobile") String mobile) {
        User u = new User();
        u.setId(new Random().nextLong()*1000);
        u.setUserName("张三");
        u.setMobile(mobile);
        u.setAge(18);
        u.setGender((byte) 1);
        return CommonResult.success(u);
    }
}
  • @ApiModelProperty 作用于实体类属性
@Data
public class User {
    @ApiModelProperty(value = "编号", name = "id", dataType = "Long", example = "302918")
    private Long id;
    @ApiModelProperty(value = "姓名", name = "userName", dataType = "String", example = "张三")
    private String userName;
    @ApiModelProperty(value = "手机号", name = "mobile", dataType = "String", example = "13888888888")
    private String mobile;
    @ApiModelProperty(value = "性别", name = "gender", dataType = "Byte", example = "1")
    private Byte gender;
    @ApiModelProperty(value = "年龄", name = "gender", dataType = "Integer", example = "18")
    private Integer age;
}

看效果

启动SpringBoot项目,输入地址:http://localhost:8011/swagger-ui.html

在这里插入图片描述

好舒服啊!这就是我期待的效果!

我们点开一个Controller对应的API看一下:

在这里插入图片描述

这里展示了这个Controller里所有的API列表,再点开/user/{mobile}看一下:

在这里插入图片描述

挖槽,还可以直接测试API,赶紧试试,点Try it out

在这里插入图片描述

Niubility!

小结

没有小结,快来试试swagger吧!

求个赞,祝你有情人终成眷属!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值