java - 关于 Swagger API 的建议

标签 java api swagger swagger-ui spring-rest

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

据我所知,Swagger 是一个记录 APIS 的工具,但还提供了从规范(v2 中的 swagger.json)生成客户端和服务器代码的功能,此外还有一个很好的 Web 界面来与你的 API 交互.

现在,鉴于我已经有一个包含至少 15 个 Controller 的现有 API,我想要一些关于如何进行的建议。 我是否应该从头开始编写整个规范(swagger.json 文件),然后使用 codegen 生成服务器代码( Controller 和对象)?还是用 Swagger-core 注解对现有 Controller 进行注解,然后从那里生成一个 json 规范会更好?

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

你能给我一些建议吗?

谢谢

最佳答案

将 swagger 与 Spring Boot 或 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 用于您的应用程序类

注释您的 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

关于java - 关于 Swagger API 的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34307496/

相关文章:

java - 如何将 SVG 路径 (SVGOMPathElement) 转换为点数组?

用于谷歌游戏商店抓取的 Python API

java - CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES 未反射(reflect)在 swagger.json 中

java - 如何以编程方式获取 jar 中的所有 *.json 文件?

java - 异步任务卡住 UI

java - 供供应商生成 IntStream 的 Lambda 表达式

php - 在 Google Cloud Vision for PHP 中放置 API key 的位置

ruby-on-rails - 如何在没有 "root"节点和 rabl 的情况下使用不同的模板进行收集

c# - 在架构定义中找不到类型名称

Django rest swagger_auto_schema 自定义响应体