从资源类中提供swagger.json

时间:2017-08-23 14:16:14

标签: java servlets swagger resteasy swagger-2.0

我使用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);       
}

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

@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访问swagger生成的json。这可能吗?

3 个答案:

答案 0 :(得分:5)

可能而且很简单

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"
          }
        }
      }
    }
  }
}

答案 1 :(得分:2)

因此,您尝试使用automatic scanning and registration将重复招摇连接到您的resteasy应用程序。

  

使用自动扫描时,swagger-core无法自动检测资源。要解决这个问题,您必须告诉swagger-core要扫描哪些软件包。建议的解决方案是使用BeanConfig方法(最有可能是Servlet)。

所以你这样做了,但现在你需要相同而不需要单独的servlet。

你可能不应该尝试手动将swagger挂钩到每个资源和&amp;您的申请提供者。您应该使用@Api对其进行注释(我假设您已经这样做了),然后,由于您使用了RESTEasy,因此您可以将BeanConfig移至现有的resteasy Application ,或任何自定义的servlet将由您现有的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;
    }
}

您的资源&amp;除注释外,提供者应保持Swagger代码的清洁。例如,这是一个简单的echo服务:

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,这非常简单,根据您现有的应用程序,您可能需要更多详细信息,但它可以帮助您入门。

答案 2 :(得分:1)

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

作为一个非常简单的例子:

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

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