Java 为 REST API 生成 Swagger UI 文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30417089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating Swagger UI documentation for REST API
提问by
I have my REST API developed using JAX-RS/Jersey in Java. I want to convert to/generate Swagger based UI documentation for it. Can anyone please tell me precise/steps in simple way on how to do so? I m sorry but, steps given on their site are little vague for me.
我使用 Java 中的 JAX-RS/Jersey 开发了我的 REST API。我想为它转换为/生成基于 Swagger 的 UI 文档。谁能以简单的方式告诉我如何做到这一点的精确/步骤?我很抱歉,但是他们网站上给出的步骤对我来说有点模糊。
采纳答案by Ron
There are several ways to integrate swagger-core with your application, but based on your description, I'd just follow the wiki page as described either by https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-1.X-Project-Setup-1.5or https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5depending on the Jersey version you use.
有多种方法可以将 swagger-core 与您的应用程序集成,但根据您的描述,我只需按照https://github.com/swagger-api/swagger-core/wiki/Swagger 中所述的维基页面进行操作-Core-Jersey-1.X-Project-Setup-1.5或https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5取决于您使用的 Jersey 版本。
Those pages also link to a set of samples you can use for reference and see how they work. They also pull in swagger-ui directly into them so you can see a full set of interaction.
这些页面还链接到一组示例,您可以将其用作参考并查看它们是如何工作的。他们还将 swagger-ui 直接引入其中,以便您可以看到完整的交互集。
回答by ?lker Korkut
Swagger has nice documentation step by step implementations on github.
Swagger 在 github 上有很好的文档逐步实现。
You should use swagger annotations on your methods, resources, models. Then you should configure your web.xml as described here. After all these steps you can reach swagger-ui yourdomain/api-docs or another path which configured in web.xml ApiDeclarationServlet's listening path.
你应该在你的方法、资源、模型上使用 swagger 注释。然后您应该按照此处所述配置您的 web.xml。完成所有这些步骤后,您可以访问 swagger-ui yourdomain/api-docs 或在 web.xml ApiDeclarationServlet 的侦听路径中配置的其他路径。
There is a sample swagger app Jax-rs/Jersey
有一个示例 swagger 应用程序 Jax-rs/Jersey
Swagger UIis a dependency-free collection of HTML, Javascript, and CSS assets that dynamically generate beautiful documentation and sandbox from a Swagger-compliant API. Because Swagger UI has no dependencies, you can host it in any server environment, or on your local machine.
Swagger UI是 HTML、Javascript 和 CSS 资产的无依赖集合,可从符合 Swagger 的 API 动态生成漂亮的文档和沙箱。由于 Swagger UI 没有任何依赖项,因此您可以将其托管在任何服务器环境或本地计算机上。
- There is a nice discussion about to get statics dependency. Normally you need to copy and paste swagger-ui statics. https://github.com/swagger-api/swagger-ui/issues/758
- Swagger UI distribution https://github.com/swagger-api/swagger-ui/tree/master/dist
- Another example app which uses swagger: https://github.com/apache/camel/blob/master/examples/camel-example-servlet-rest-tomcat/src/main/webapp/WEB-INF/web.xml
- Simple reference about swagger implementation with springboot(Which is not needed web.xml in this situation).
- 有一个关于获得静态依赖的很好的讨论。通常你需要复制和粘贴 swagger-ui 静态。 https://github.com/swagger-api/swagger-ui/issues/758
- Swagger UI 分发 https://github.com/swagger-api/swagger-ui/tree/master/dist
- 另一个使用 swagger 的示例应用程序:https: //github.com/apache/camel/blob/master/examples/camel-example-servlet-rest-tomcat/src/main/webapp/WEB-INF/web.xml
- 关于使用 springboot 实现 swagger 的简单参考(在这种情况下不需要 web.xml)。
回答by Master Mind
You should use roaster: you can do source code modification to add new annotations. Here is an example to illustrate how to use it in your case:
您应该使用Roaster:您可以修改源代码以添加新注释。这是一个示例,用于说明如何在您的情况下使用它:
package ma.cars.iscraper;
import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.source.*;
import java.util.List;
public class Main {
public static void main(String[] args) {
String originalClassSourceCode = "@Path(\"user\")\n public class SomeClass { @GET\n" +
" @Path(\"{userId}\")\n public Response getUserById() {\n return null; \n}";
System.out.println("Before : \n" + originalClassSourceCode);
JavaClassSource javaClass =
Roaster.parse(JavaClassSource.class,originalClassSourceCode );
String pathValue = null;
// extract Path annotation value
List<AnnotationSource<JavaClassSource>> listAnnotations = javaClass.getAnnotations();
for (AnnotationSource annotation :listAnnotations) {
if (annotation.getName().equals("Path")) {
pathValue = annotation.getStringValue();
}
}
AnnotationSource<JavaClassSource> apiAnnotation = javaClass.addAnnotation("com.wordnik.swagger.annotations.Api");
apiAnnotation.setLiteralValue("\"" + pathValue + "\"") ;
List<MethodSource<JavaClassSource>> methods = javaClass.getMethods();
for (MethodSource<JavaClassSource> method: methods) {
for (AnnotationSource annotation: method.getAnnotations()) {
if (annotation.getName().equals("DELETE") || annotation.getName().equals("GET")
|| annotation.getName().equals("POST") || annotation.getName().equals("PUT")) {
String returnTypeClass = method.getReturnType().getQualifiedName();
AnnotationSource<JavaClassSource> apiOperation = method.addAnnotation("com.wordnik.swagger.annotations.ApiOperation");
apiOperation.setLiteralValue("value", "\"value\"");
apiOperation.setLiteralValue("response", "\"" + returnTypeClass + ".class\"");
}
}
}
System.out.println(javaClass);
}
}
And here is the output:
这是输出:
Before :
@Path("user")
public class SomeClass { @GET
@Path("{userId}")
public Response getUserById() {
return null;
}
After :
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;@Path("user")
@Api("user")
public class SomeClass { @GET
@Path("{userId}")
@ApiOperation(value = "value", response = "Response.class")
public Response getUserById() {
return null;
}
回答by dubes
The easiest way I know is to use the JAXRS Analyzer maven plugin. Which can be found on GitHub
我知道的最简单的方法是使用 JAXRS Analyzer maven 插件。可以在GitHub上找到
<plugin>
<groupId>com.sebastian-daschner</groupId>
<artifactId>jaxrs-analyzer-maven-plugin</artifactId>
<version>0.4</version>
<executions>
<execution>
<goals>
<goal>analyze-jaxrs</goal>
</goals>
<configuration>
<!-- Available backends are plaintext (default), swagger and asciidoc -->
<backend>plaintext</backend>
<!-- Domain of the deployed project, defaults to example.com -->
<deployedDomain>example.com</deployedDomain>
</configuration>
</execution>
</executions>
This creates the swagger json for you with mvn clean install. To the best of my knowledge it does not need any manipulation of the web.xml etc. as it does it via bytecode analysis.
这会使用 mvn clean install 为您创建 swagger json。据我所知,它不需要对 web.xml 等进行任何操作,因为它是通过字节码分析来完成的。
Source: Adam Bien weblog entry& his demo in one of the airhacks session
资料来源:Adam Bien 博客条目和他在一次空中黑客会议中的演示
Bonus: a 9 minute videoby the creator of the plugin explaining the usage
奖励:插件创建者解释用法的 9 分钟视频