生成REST API的Swagger UI文档

30

我使用Java中的JAX-RS/Jersey开发了自己的REST API。我想将其转换为Swagger基于UI的文档。请问有人能告诉我如何以简单明了的方式精确地进行操作吗?很抱歉,他们网站上给出的步骤对我来说有些含糊。


我无法真正实现Swagger所想要的功能;最终我使用了iodocs: https://github.com/mashery/iodocs。你可以看一下,作为另一种选择。 - Rots
请查看这个教程,它提供了逐步指导,帮助您为API生成UI文档。 - Srini
Swagger是一种规范。你已经决定使用哪个Swagger实现了吗?如果是,它是什么?如果没有,你想使用swagger-springmvc吗? - DolphinJava
4个回答

6
有几种方法可以将swagger-core与您的应用程序集成,但根据您的描述,我建议您按照wiki页面上的说明进行操作,具体取决于您使用的Jersey版本,请参阅以下链接:https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-1.X-Project-Setup-1.5https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5
这些页面还链接到一组示例,供您参考并了解其工作原理。它们还直接引入swagger-ui,因此您可以看到完整的交互集合。

1
请注意,只有带有 @Api 注解的类才会被 Swagger 扫描。 - Alex R
@AlexR - 默认情况下是的。不过这是可以更改的。 - Ron
您可以将ReaderConfig.scanAllResources的值设置为true。请查看https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X的第一部分以获取更多详细信息。 - Ron

6
我知道的最简单的方法是使用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>

这将通过mvn clean install为您创建swagger json。据我所知,它不需要对web.xml等进行任何操作,因为它是通过字节码分析完成的。
来源:Adam Bien博客entry和他在airhacks会议中的演示
奖励:插件创作者的9分钟video视频,解释其用法。

如何在Eclipse上进行配置? - user3767923
如果你有一个Maven项目,那么你只需要添加依赖项,Eclipse会接管。如果没有使用Maven,我将不得不检查如何使用它。 - dubes
我添加了依赖,但是我遇到了这个错误。插件com.test.webservices:jaxrs-analyzer-maven-plugin:0.4或其某个依赖项无法解析:在http://repo.maven.apache.org/maven2中找不到com.test.webservices:jaxrs-analyzer-maven-plugin:jar:0.4,已经在本地存储库中缓存,直到中央的更新间隔过去或强制更新后才会重新尝试解决。 - user3767923
似乎Maven无法找到插件,我将不得不查看其托管的存储库。 - dubes
@SystemMGR,你能再检查一下你的mvn pom文件吗?我发现group id不正确。你需要在pom文件的插件部分添加这个。我会编辑答案来显示这个条目。 - dubes
我现在遇到了这个错误。无法执行目标org.apache.maven.plugins:maven-compiler-plugin:3.1:compile(default-compile)在项目RESTfulWebServiceExample上:编译失败。 - user3767923

2
你应该使用烘焙器:你可以对源代码进行修改以添加新的注释。下面是一个例子,说明如何在你的情况下使用它:
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);

    }
}

这是输出结果:
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; 
}

1
Swagger在GitHub上提供了很好的文档逐步实现。
您应该在方法、资源和模型上使用Swagger注释。然后,您应该按照这里描述的方式配置web.xml。完成所有这些步骤后,您可以通过yourdomain/api-docs或在web.xml中配置的ApiDeclarationServlet侦听路径到达swagger-ui。
这里有一个样例swagger应用程序Jax-rs/Jersey

Swagger UI是一个无依赖的HTML、Javascript和CSS资源集合,可从符合Swagger规范的API动态生成美观的文档和沙盒。由于Swagger UI没有依赖性,因此您可以在任何服务器环境或本地计算机上托管它。


很抱歉,但是关于配置web.xml的链接是错误的,并且与问题中的配置无关。 - Ron
有一个样例应用jax-rs/jersey,它还配置了web.xml文件,顺便说一下,我没有尝试过它。 - İlker Korkut

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接