Generating Swagger documentation from existing Java code?

五迷三道 提交于 2021-01-02 07:58:19

问题


Is there a way to generate swagger documentation (in YAML format) from existing Java code?

I am currently using YAML file to generate Java API code, but I am interested whether the reversed process can be achieved. That is if I can generate a YAML file from the existing Java code?


回答1:


The process for generating YAML files from existing code is simple.

Add the following dependencies (I happen to use Maven):

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.9.2</version>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.9.2</version>
</dependency>

This adds a swagger-ui in your application that can be accessed with

http://<host>:<port>/swagger-ui.html

Hit the API documentation (/v2/api-docs) link and you will get a JSON file that can be easily converted to YAML file using http://editor.swagger.io (Edit -> Convert to YAML)




回答2:


Generating the swagger documentation from code is a feature proposed by swagger-core. You can add some Java annotations to your code in order to produce the YAML file.

Proposing both code generation and yaml generation is a great feature of swagger that let you choose between using an API-first or code-first approach.

You can find more about swagger annotations here : https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X



来源:https://stackoverflow.com/questions/38790709/generating-swagger-documentation-from-existing-java-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!