首页 文章

关于Swagger API的建议

提问于
浏览
1

我正在使用Java 8使用SpringBoot和Spring REST服务构建API . 我刚刚发现了Swagger API,现在我想使我的API Swagger兼容 .

到目前为止,我读到,Swagger是一个记录您的APIS的工具,但也提供了从规范生成客户端和服务器代码的功能(v2中的swagger.json),以及与您的API交互的漂亮的Web界面 .

现在,我想了解一些关于如何继续的建议,因为我已经有一个至少有15个控制器的现有API . 我应该从头开始编写整个规范(swagger.json文件),然后使用codegen生成服务器代码(控制器和对象)吗?或者最好用Swagger-core注释注释现有的控制器,然后从那里生成json规范?

第二种选择对我来说更有意义,但我不知道如何从现有的API生成swagger.json规范(如果可能的话) .

你能给我一些建议吗?

谢谢

2 回答

  • 0

    将swagger与 spring 靴或 spring Cloud 融为一体非常容易 .

    只需对现有REST API进行一些注释,它就会自动为您生成完整的swagger规范 . Swagger绝对是最受欢迎的REST API文档框架之一 .

    pom.xml依赖项

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.2.2</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.2.2</version>
        <scope>compile</scope>
    </dependency>
    

    在springboot应用程序中定义api信息

    @Bean
    public Docket newsApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("springboot")
                .apiInfo(apiInfo())
                .select()
                .paths(regex("/.*"))
                .build();
    }
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot REST API with Swagger")
                .description("SpringBoot REST API with Swagger")
                .termsOfServiceUrl("http://www-03.ibm.com/software/sla/sladb.nsf/sla/bm?Open")
                .contact("sanket**@au1.ibm.com")
                .license("Apache License Version 2.0")
                .licenseUrl("https://github.com/IBM-Bluemix/news-aggregator/blob/master/LICENSE")
                .version("2.0")
                .build();
    }
    

    注释

    @EnableSwagger2 为您的Application类

    注释您的REST API

    像这样的东西

    @RequestMapping(value = "/operate/add/{left}/{right}", method = RequestMethod.GET, produces = "application/json")
    @ApiOperation(value = "addNumbers", nickname = "addNumbers")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = Result.class),
            @ApiResponse(code = 401, message = "Unauthorized"), 
            @ApiResponse(code = 500, message = "Failure") })
    public Result add(@PathVariable("left") int left, @PathVariable("right") int right) {
    

    你完成了 . 默认情况下包含Swagger UI,您还可以访问JSON格式的swagger规范 . 访问 http://localhost:12001/swagger-ui.html#/

    有关更多详细信息,请参阅此代码库:https://github.com/sanketsw/SpringBoot_REST_API

  • 4

    我意识到这是迟到的,但是这里有一个替代方案供您考虑:您可以手工编写OpenAPI API描述,然后让您的实现在启动时读取它并自动配置,而不是从您的实现生成OpenAPI API描述 . 它的URL路由,响应类型等相应 .

    即从文档生成实现,而不是从实现生成文档 .

    我不知道 Spring 天会有多可行(对不起) . Python和WSGI并不难 .

    这是否是一个好主意只是你可以做出的判断 .

相关问题