Swagger API documentation Swagger API documentation centralized registry

Swagger API documentation centralized registry

 

Interface documentation is very important before and after the end of the development of a docking assembly. Write interface documentation manual time-consuming and there is a problem with the code document can not be updated, so as to produce a framework for automatic generation of interface documentation such swagger. swagger document generally with the project code generation and update access address is also based on the project addresses, so the small number of project teams better. If the team a lot of projects, such as micro-services architecture team, moving the tens or even hundreds of service projects, it means that front-end developers need to remember dozens or even hundreds of swagger document addresses, it is very friendly a. Currently seemingly no more popular API documentation centralized management project (also, or I did not find), and therefore spent some time myself integrates a, described below.

1. swagger-bootstrap-ui project

The project is an open source project (on GitHub https://github.com/xiaoymin/swagger-bootstrap-ui  ), made of swagger ui enhancements, the overall function seems to be richer. To see the effect,

swagger-bootstrap-ui

Debugging url address of the project was originally based on its own services, I will change it to the url address registration services, registration services to support the debugging interfaces. Adjusted Source Address:  https://github.com/ronwxy/swagger-bootstrap-ui

2. swagger api registration services

The project integrates a swagger-bootstrap-ui, and provides a swagger api registration interface, providing services to accept all valid configuration register, so that the service can be registered unified view on one page, no longer have to remember too much of the document address .

swagger-bootstrap-ui2

启动注册服务后,访问 http://localhost:11090/doc.html 打开文档页面。如上图,可通过下拉列表来选择不同项目,加载项目的接口文档查看或调试。
项目地址: 关注本文最后二维码公众号,回复“swagger”获取源码地址 (一个不只有实战干货的技术公众号,欢迎关注。如果觉得有用,不要吝啬你的star,反正又不要钱,O(∩_∩)O)

3. 服务端配置

在业务服务端,需要提供一些配置。
首先,需要配置一些Bean,如下提供了一个配置类(这里只列出了主要部分,完整代码参考: https://github.com/ronwxy/base-spring-boot)

Copy the code
public class Swagger2AutoConfiguration {

    @Bean
    public Docket restApi() {
        ParameterBuilder builder = new ParameterBuilder();
        builder.name("x-auth-token").description("授权token")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false);
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(groupName)
                .select()
                .apis(RequestHandlerSelectors.basePackage(apisBasePackage))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(Collections.singletonList(builder.build()))
                .apiInfo(apiInfo());
    }

    @Profile({"dev"})
    @Bean
    public CommandLineRunner swaggerRegistar(ConfigurableApplicationContext context) {
        return new SwaggerInfoRegistar(context);
    }

    /**
     * use to register swagger api info url to swagger api registry;
     *
     * @author liubo
     */
    public class SwaggerInfoRegistar implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            String url = buildLocalSwaggerDocsUrl();
            registerLocalSwaggerUrl(url);
        }

        /**
         * register the v2/api-docs url
         *
         * @param url
         */
        private void registerLocalSwaggerUrl(String url) {
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("project", getApiTitle());
            body.add("url", url);
            ResponseEntity<Map> re = restTemplate.postForEntity(getSwaggerRegisterUrl(), body, Map.class);
            if (HttpStatus.OK.equals(re.getStatusCode())) {
                logger.info("swagger api registered success to {}", getSwaggerRegisterUrl());
            } else {
                logger.warn("swagger api registered failed [{}]", re.getBody().get("msg"));
            }
        }
    }

}
Copy the code

该类完成了swagger的基本配置,同时将swagger的/v2/api-docs地址注册到了步骤2中介绍的注册服务。 

然后,因为要从注册服务端调用该业务服务的接口进行调试,存在跨域,因此服务需要做跨域支持,配置文件中添加如下定义,

Copy the code
@Bean
@ConditionalOnMissingBean(name = "corsFilterRegistrationBean")
public FilterRegistrationBean corsFilterRegistrationBean() {
    UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();

    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.applyPermitDefaultValues();
    corsConfiguration.setAllowedMethods(Arrays.asList(CorsConfiguration.ALL));
    corsConfiguration.addExposedHeader(HttpHeaders.DATE);

    corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);

    CorsFilter corsFilter = new CorsFilter(corsConfigurationSource);
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    filterRegistrationBean.setFilter(corsFilter);
    filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    filterRegistrationBean.addUrlPatterns("/*");

    return filterRegistrationBean;
}
Copy the code

 

最后,在属性配置文件application.yml中配置一些必要的属性,

swagger:
  api-title: Demo标题  #会展示在下拉列表框中,一般写项目名称
  api-description:  Demo描述,集中注册
  group-name: Demo项目
  apis-base-package: cn.jboost.springboot.swagger # API类所在包名
  swagger-registry-path: http://localhost:11090/swagger/register  #就是2中注册服务的注册接口地址

 

配置完后, 就可以像一般项目一样编写接口类,加swagger注解。项目启动时, 会自动向注册服务完成注册,刷新注册服务的文档页面即可在下拉列表看到。

4. 总结

本文介绍了一个基于swagger ui增强版项目swagger-bootstrap-ui的接口文档集中化管理实现。采用该实现,将所有swagger在线接口文档集中管理,有效提高前后端对接效率。

 

接口文档是前后端开发对接时很重要的一个组件。手动编写接口文档既费时,又存在文档不能随代码及时更新的问题,因此产生了像swagger这样的自动生成接口文档的框架。swagger文档一般是随项目代码生成与更新,访问地址也是基于项目地址,因此对项目数不多的团队还好。如果团队的项目很多,比如采用微服务架构的团队,动则几十甚至上百个服务项目,那就意味着前端开发人员需要记住几十甚至上百个swagger文档地址,那就很不友好了。目前貌似还没有较流行的API文档集中化管理项目(也或者是我没找到),因此花了点时间自己集成了一个,介绍如下。

1. swagger-bootstrap-ui项目

该项目是github上的一个开源项目(https://github.com/xiaoymin/swagger-bootstrap-ui ),对swagger ui做了增强,功能整体看起来要丰富一些。来看看效果,

swagger-bootstrap-ui

该项目的调试url地址原本是基于自身服务的,我将它改为了注册服务的url地址,以支持注册服务的接口调试。调整后的源码地址: https://github.com/ronwxy/swagger-bootstrap-ui

2. swagger api注册服务

该项目集成了swagger-bootstrap-ui,并提供了swagger api注册接口,接受所有提供了有效配置的服务项目注册,让注册的服务在一个页面上可统一查看,再也不用记太多文档地址了。

swagger-bootstrap-ui2

启动注册服务后,访问 http://localhost:11090/doc.html 打开文档页面。如上图,可通过下拉列表来选择不同项目,加载项目的接口文档查看或调试。
项目地址: 关注本文最后二维码公众号,回复“swagger”获取源码地址 (一个不只有实战干货的技术公众号,欢迎关注。如果觉得有用,不要吝啬你的star,反正又不要钱,O(∩_∩)O)

3. 服务端配置

在业务服务端,需要提供一些配置。
首先,需要配置一些Bean,如下提供了一个配置类(这里只列出了主要部分,完整代码参考: https://github.com/ronwxy/base-spring-boot)

Copy the code
public class Swagger2AutoConfiguration {

    @Bean
    public Docket restApi() {
        ParameterBuilder builder = new ParameterBuilder();
        builder.name("x-auth-token").description("授权token")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false);
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(groupName)
                .select()
                .apis(RequestHandlerSelectors.basePackage(apisBasePackage))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(Collections.singletonList(builder.build()))
                .apiInfo(apiInfo());
    }

    @Profile({"dev"})
    @Bean
    public CommandLineRunner swaggerRegistar(ConfigurableApplicationContext context) {
        return new SwaggerInfoRegistar(context);
    }

    /**
     * use to register swagger api info url to swagger api registry;
     *
     * @author liubo
     */
    public class SwaggerInfoRegistar implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            String url = buildLocalSwaggerDocsUrl();
            registerLocalSwaggerUrl(url);
        }

        /**
         * register the v2/api-docs url
         *
         * @param url
         */
        private void registerLocalSwaggerUrl(String url) {
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("project", getApiTitle());
            body.add("url", url);
            ResponseEntity<Map> re = restTemplate.postForEntity(getSwaggerRegisterUrl(), body, Map.class);
            if (HttpStatus.OK.equals(re.getStatusCode())) {
                logger.info("swagger api registered success to {}", getSwaggerRegisterUrl());
            } else {
                logger.warn("swagger api registered failed [{}]", re.getBody().get("msg"));
            }
        }
    }

}
Copy the code

该类完成了swagger的基本配置,同时将swagger的/v2/api-docs地址注册到了步骤2中介绍的注册服务。 

然后,因为要从注册服务端调用该业务服务的接口进行调试,存在跨域,因此服务需要做跨域支持,配置文件中添加如下定义,

Copy the code
@Bean
@ConditionalOnMissingBean(name = "corsFilterRegistrationBean")
public FilterRegistrationBean corsFilterRegistrationBean() {
    UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();

    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.applyPermitDefaultValues();
    corsConfiguration.setAllowedMethods(Arrays.asList(CorsConfiguration.ALL));
    corsConfiguration.addExposedHeader(HttpHeaders.DATE);

    corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);

    CorsFilter corsFilter = new CorsFilter(corsConfigurationSource);
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    filterRegistrationBean.setFilter(corsFilter);
    filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    filterRegistrationBean.addUrlPatterns("/*");

    return filterRegistrationBean;
}
Copy the code

 

Finally, configure some necessary properties in the properties in the configuration file application.yml,

Swagger: 
  API-title: Demo # title will be displayed in the drop-down list box, write the item name in general 
  api-description: Demo description, centralized registration 
  group-name: Demo project 
  apis-base-package: cn.jboost.springboot.swagger # API class where the package name 
  swagger-registry-path: http: // localhost: 11090 / swagger / register # 2 is registered in the service registration interface address

 

After configuration, you can write an interface class like most projects, plus swagger comment. When the project starts, it will automatically register with the registrar, the registrar of documents to refresh the page to see the drop-down list.

4. Summary

This paper introduces a centralized management interface documentation based on an enhanced version of swagger ui swagger-bootstrap-ui project implementation. With this realization, all the swagger online interface documentation centralized management, improve the efficiency of the front and rear end butt.

 

Guess you like

Origin www.cnblogs.com/Leo_wl/p/11106098.html