心得体会之Swagger

2019-10-01 14:36 来源:未知

swagger官网: 

背景

RESTful(Representational State Transfer)是目前(最)流行的API设计风格。
当我们的平台的API增加的一定数量时,如何以一种更好的方式来管理维护这些API呢?

无意间从一个朋友那里听说swagger这个东西,经过他的展示,觉得挺不错的,主要功能就是方便、直观、漂亮的将后台所定义接口展示给客户端开发人员,而且还给后台开发人员节省了很多时间成本。

swagger ui demo: 

WIKI

图片 1

wiki api

图片 2

api content

  1. 增加了程序猿的工作量
  2. 每次修改API参数、请求方式、返回值等都要同步的去修改wiki api文档,通常情况下是没及时更新,后来后来两边就无法对应起来了,这个时候wiki api已经失去了意义。
  3. 没办法优雅的单元测试

背景简介

让API文档总是与API定义同步更新,是一件非常有价值的事。

swagger

Swagger is a simple yet powerful representation of your RESTful API. With the largest ecosystem of API tooling on the planet, thousands of developers are supporting Swagger in almost every modern programming language and deployment environment. With a Swagger-enabled API, you get interactive documentation, client SDK generation and discoverability.
http://swagger.io/
https://github.com/swagger-api/swagger.io

下面我们举个简单的栗子(spring-boot+swagger):

  1. 加入swagger依赖
    <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.3.1</version>
    </dependency>
    <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.3.1</version>
    </dependency>

  2. swagger配置
    @SpringBootApplication
    @EnableAutoConfiguration
    @EnableSwagger2
    @ComponentScan(value = {
    "com.dcf", "com.iqunxing"
    })
    public class ApplicationConfig extends SpringBootServletInitializer {

        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(ApplicationConfig.class);
        }
    
        @Autowired
        private TypeResolver typeResolver;
    
        @Bean
        public Docket petApi() {
            return new Docket(DocumentationType.SWAGGER_2)
             .forCodeGeneration(true)
             .apiInfo(
                     new ApiInfo("rest API接口文档", "客户营销 - 企业官网自助建站", "v0.0.1", null, "taorong.sun@dcfservice.net", null,
                             null))
             .select()
             .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
             .paths(PathSelectors.any())
             .build()
             .pathMapping("/")
             .directModelSubstitute(LocalDate.class, String.class)
             .genericModelSubstitutes(ResponseEntity.class)
             .alternateTypeRules(
                     newRule(typeResolver.resolve(DeferredResult.class,
                             typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                             typeResolver.resolve(WildcardType.class)))
             .useDefaultResponseMessages(false)
             .globalResponseMessage(
                     RequestMethod.GET,
                     newArrayList(new ResponseMessageBuilder().code(500).message("500 message")
                             .responseModel(new ModelRef("Error")).build()));
     // 如果需要鉴权,请放开以下注释行->
     // .securitySchemes(newArrayList(apiKey()))
     // .securityContexts(newArrayList(securityContext()))
     // <-如果需要鉴权,请放开以上注释行
     // 如果需要全局性参数,请放开以下注释行->
     // .globalOperationParameters(
     // newArrayList(new ParameterBuilder()
     // .name("someGlobalParameter")
     // .description(
     // "Description of someGlobalParameter")
     // .modelRef(new ModelRef("string"))
     // .parameterType("query").required(true).build()));
     // <-如果需要全局性参数,请放开以上注释行
     // 如果需要UrlTemplating,请放开以下注释行->
     // .enableUrlTemplating(true);
     // <-如果需要UrlTemplating,请放开以上注释行
        }
    }
    
  3. controller里增加API说明
    @Api(tags = {
    "企业官网创建编辑"
    })
    @RestController
    @RequestMapping("/services/")
    public class CustomerSiteController {

        @Autowired
        private ICustomerSiteService customerSiteService;
    
        @Autowired
        private IUserService userService;
    
        @ApiOperation(value = "查询企业所有信息 - [MARKETING-CS-CS-01]", response = GetCustomerSiteRsp.class, notes = "[SELECT]dcf_user.user,dcf_customer.site_addition,dcf_customer.site_basic,dcf_customer.site_addition,dcf_customer.site_contact,dcf_customer.site_domain,dcf_customer.site_flash,dcf_customer.site_goods,dcf_customer.site_online_shop")
        @RequestMapping(value = "/getCustomerSite", method = RequestMethod.GET)
        public Response getCustomerSite() {
            String currentUserId = SecurityUtils.getCurrentUserId();
            User currentUser = userService.getUserByPk(currentUserId);
            GetCustomerSiteReq req = new GetCustomerSiteReq();
            req.setCustomerId(currentUser.getCustomerId());
            GetCustomerSiteRsp rsp = customerSiteService.getCustomerSite(req);
            if (StringUtils.equals(RetCodeConst.SUCCESS, rsp.getRetCode())) {
                return Response.success(rsp);
            }
            return Response.fail(null, "查询企业信息失败");
        }
    }
    

大功告成,我们来看下效果吧

图片 3

swagger api doc

图片 4

定制后的效果

那么优点就显而易见咯:

  1. 更少的工作量(除配置外)
  2. 和代码同步更新,减少维护成本
  3. 支持单元测试
  4. 文档规范统一

错误之处请包涵并指出,谢谢

缘何而来

在服务端开发过程中,开发人员往往会提供出来很多API接口供客户端开发人员使用,那么为了方便使用呢,开发人员会在开发接口的过程中同时维护一份文档,以说明每一个接口的访问方式、需要的参数、返回的结果等基本信息。但是这种传统的API书写方式很耗费时间,而且容易造成因为接口文档更新不及时导致的前后端双方交流成本增加的问题。
所谓工欲善其事,必先利其器。基于上述情况,诞生了许多API接口文档自动化生成工具,如Swagger、I/O Docs、apiary.io、Docco、Dexy、Doxygen、TurnAPI。今天重点要说的就是其中的Swagger。(宝宝再也不用担心接口文档的更新问题了)

 

我的全部

Swagger(The World's Most Popolar Framework for APIs),is a simple yet powerful representation of your RESTful API. With the largest ecosystem of API tooling on the planet, thousands of developers are supporting Swagger in almost every modern programming language and deployment environment. With a Swagger-enabled API, you get interactive documentation, client SDK generation and discoverability.

Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化Restful风格的Web服务。总体目标是使接口文档与服务端接口以同样的速度更新。文档的方法、参数和模型紧密集成到服务端的代码,允许API始终保持同步。Swagger让部署管理和使用功能强大的API变得如此简单。

像其他大的项目一样(如Spring),Swagger的下面也包含很多模块,那么这里主要涉及他的UI模块。

图片 5

swaggerFrame.png

A Powerful Interface to your API

Swagger is a simple yet powerful representation of your RESTful API. With the largest ecosystem of API tooling on the planet, thousands of developers are supporting Swagger in almost every modern programming language and deployment environment. With a Swagger-enabled API, you get interactive documentation, client SDK generation and discoverability.

We created Swagger to help fulfill the promise of APIs. Swagger helps companies like Apigee, Getty Images, Intuit, LivingSocial, McKesson, Microsoft, Morningstar, and PayPal build the best possible services with RESTful APIs.

Now in version 2.0, Swagger is more enabling than ever. And it's 100% open source software.

 图片 6

 

图片 7

 

图片 8

理论与实践相结合

本文基于Maven+SpringMVC4.3+Swagger环境,对swagger的使用进行介绍。

TAG标签:
版权声明:本文由金沙澳门官网4166发布于中国史,转载请注明出处:心得体会之Swagger