从资源 class 提供 swagger.json

serve swagger.json from resource class

我使用 swagger 来记录 resteasy API 的端点,并且我使用 servlet 提供 swagger.json 描述,方法如下:

public void init(ServletConfig config) throws ServletException
{
    super.init(config);
    BeanConfig beanConfig = new BeanConfig();
    beanConfig.setHost("localhost:8080");       
    beanConfig.setBasePath("/api");
    beanConfig.setResourcePackage("my.rest.resources");
    beanConfig.setScan(true);       
}

我可以在 localhost:8080/api/swagger.json 访问 swagger.json。 但是,我的合作者希望避免使用 resteasy servlet 以外的额外 servlet,我想知道我是否可以提供从资源 class 的方法生成 json 的 swagger,如下所示:

@GET
@Path("/myswagger")
@Produces("application/json")
public String myswagger(@Context UriInfo uriInfo) 
{
    Swagger swagger = new Swagger();
    // Do something to retrieve the Swagger Json as a string
    // ... 
    return(swaggerJsonString);
}

然后通过 localhost:8080/api/myswagger 访问 json 生成的 swagger。这可能吗?

假设您可以从 java 应用程序访问 json 文件,您应该只能读取 json 文件和 return 作为String return 方法的值。

作为一个超级简单的例子:

String swaggerJsonString = new String(Files.readAllBytes(Paths.get("swagger.json")));

您必须弄清楚如何在您的应用程序中找到该文件的路径。

所以您尝试使用 automatic scanning and registration.

将 swagger 连接到您的 resteasy 应用程序

When using automatic scanning, swagger-core is unable to detect the resources automatically. To resolve that, you must tell swagger-core which packages to scan. The suggested solution is to use the BeanConfig method (most likely as a Servlet).

你这样做了,但现在你想要同样的东西而不需要单独的 servlet。

您可能不应该尝试手动将 swagger 挂接到应用程序的每个资源和提供者中。你应该只用 @Api 注释它们(我假设你已经这样做了),然后,因为你使用 RESTEasy,你可以将你的 BeanConfig 移动到你现有的 resteasy Application,或者到一个自定义的,无论如何将由您现有的 resteasy servlet 处理。参见 using a custom Application subclass

import io.swagger.jaxrs.config.BeanConfig;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;

public class MyApplication extends Application {

    public MyApplication() {
        BeanConfig beanConfig = new BeanConfig();
        beanConfig.setVersion("1.0");
        beanConfig.setSchemes(new String[] { "http" });
        beanConfig.setTitle("My API"); // <- mandatory
        beanConfig.setHost("localhost:8080");       
        beanConfig.setBasePath("/api");
        beanConfig.setResourcePackage("my.rest.resources");
        beanConfig.setScan(true);
    }

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> set = new HashSet<Class<?>>();
        set.add(MyRestResourceFoo.class); // Add your own application's resources and providers
        set.add(io.swagger.jaxrs.listing.ApiListingResource.class);
        set.add(io.swagger.jaxrs.listing.SwaggerSerializers.class);
        return set;
    }
}

除了注释之外,您的资源和提供者应该保持干净的 Swagger 代码。例如,这是一个简单的回显服务:

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Api
@Path("/echo")
public class EchoRestService {

    @ApiOperation(value = "Echoes message back")
    @GET
    @Path("/{param}")
    public Response printMessage(@PathParam("param") String msg) {
        String result = "Echoing: " + msg;
        return Response.status(200).entity(result).build();
    }
}

然后访问http://localhost:8080/api/swagger.json得到JSON字符串(同.yaml)。

我已经推送 an example to GitHub,它非常简单,根据您现有的应用程序,您可能需要更多详细信息,但它可以帮助您入门。

可能而且非常简单

import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.*;
import io.swagger.jaxrs.Reader;
import io.swagger.models.Swagger;
import io.swagger.util.Json;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.net.HttpURLConnection;
import java.util.HashSet;
import java.util.Set;


@SwaggerDefinition(
        info = @Info(
                title = "title",
                version = "0.2",
                description = "description",
                termsOfService = "termsOfService",
                contact = @Contact(
                        name = "contact",
                        url = "http://contact.org",
                        email = "info@contact.org"
                ),
                license = @License(
                        name = "Apache2",
                        url = "http://license.org/license"
                )
        ),
        host = "host.org",
        basePath = "",
        schemes = SwaggerDefinition.Scheme.HTTPS
)
public class SwaggerMain {

    @Path("/a")
    @Api(value = "/a", description = "aaa")
    public class A {

        @GET
        @Path("/getA")
        @Produces(MediaType.APPLICATION_JSON)
        @ApiOperation(value = "Method for A.")
        @ApiResponses(value = {
                @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK"),
                @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
                @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"),
                @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems")
        })
        public String getA() {
            return "Hello, A";
        }

    }

    @Path("/b")
    @Api(value = "/b", description = "bbb")
    public class B {
        @GET
        @Path("/getA")
        @Produces(MediaType.APPLICATION_JSON)
        @ApiOperation(value = "Method for B.")
        @ApiResponses(value = {
                @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "OK"),
                @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
                @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"),
                @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems")
        })
        public String getA() {
            return "Hello, B";
        }
    }

    public static void main(String[] args) {
        Set<Class<?>> classes = new HashSet<Class<?>>();
        classes.add(SwaggerMain.class);
        classes.add(A.class);
        classes.add(B.class);
        Swagger swagger = new Reader(new Swagger()).read(classes);
        try {
            System.out.println(Json.mapper().writeValueAsString(swagger));;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

}

给出 json:

{
  "swagger": "2.0",
  "info": {
    "description": "description",
    "version": "0.2",
    "title": "title",
    "termsOfService": "termsOfService",
    "contact": {
      "name": "contact",
      "url": "http://contact.org",
      "email": "info@contact.org"
    },
    "license": {
      "name": "Apache2",
      "url": "http://license.org/license"
    }
  },
  "host": "host.org",
  "tags": [
    {
      "name": "a"
    },
    {
      "name": "b"
    }
  ],
  "schemes": [
    "https"
  ],
  "paths": {
    "/a/getA": {
      "get": {
        "tags": [
          "a"
        ],
        "summary": "Method for A.",
        "description": "",
        "operationId": "getA",
        "produces": [
          "application/json"
        ],
        "parameters": [],
        "responses": {
          "200": {
            "description": "OK"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          },
          "500": {
            "description": "Internal server problems"
          }
        }
      }
    },
    "/b/getA": {
      "get": {
        "tags": [
          "b"
        ],
        "summary": "Method for B.",
        "description": "",
        "operationId": "getA",
        "produces": [
          "application/json"
        ],
        "parameters": [],
        "responses": {
          "200": {
            "description": "OK"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          },
          "500": {
            "description": "Internal server problems"
          }
        }
      }
    }
  }
}