如何使用 gradle 生成 swagger.json?如何使用、gradle、json、swagger

2023-09-08 09:18:06 作者:饱暖

我想使用 swagger-codegen 来生成 REST 客户端和可能的静态 HTML 文档.

I want to use swagger-codegen to generate REST clients and possibly static HTML documentation.

但是,swagger-codegen 需要 swagger.json 进行输入.

However, swagger-codegen needs swagger.json for input.

我知道,我可以从配备 Swagger 的正在运行的 REST 服务器获取此信息.

I am aware, that I can get this from a running REST server equipped with Swagger.

但是有没有办法直接从我的 Java 代码中获取 swagger.json - 即使用 gradle 从源代码生成它 - 无需在 Web 容器中运行应用程序,并指向 curl 还是浏览器呢?

But is there a way to obtain swagger.json directly from my Java code - i.e. to generate it with gradle from the source code - without the need to run the application in a web container, and pointing curl or a browser to it?

推荐答案

这有点老了,但我想知道完全一样... 总之我已经开始研究了:

This is a bit old but I was wondering exactly the same... In short I've started the research with:

一个展示简约 REST API 的示例 Spring Boot 应用;对 API 方法进行 Swagger 注释;春狐;Gradle 作为构建工具;

我设法使用两种不同的方法将 JSON 规范生成为构建工件:

I managed to generate the JSON spec as a build artifact using two different approaches:

通过使用 gradle 端口 的 kongchen的swagger-maven-plugin.(不确定这是否重要,因为它无论如何都会启动服务器)通过执行生成规范的集成测试(Spring 的模拟 MVC).我从这里借用了这个想法. By using a gradle port of the swagger-maven-plugin of kongchen. (Not sure if this counts, because it starts a server anyways) By executing an integration test (Spring's mock MVC) which generates the specification. I borrowed the idea from here.

我在一个位于这里的简单项目中总结了我的研究.请参阅 自动化 部分.包括代码和示例.

I've summarized my research in a simple project located here. See the Automation section. Code and examples are included.