Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serve swagger.json from resource class

I use swagger for documenting endpoints of a resteasy API, and I serve the swagger.json description using a servlet with a method like this:

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);       
}

and I can access the swagger.json at localhost:8080/api/swagger.json. However, my collaborators would like to avoid extra servlets other than the resteasy servlet, and I wonder if I can serve the swagger generated json from a method from a resource class, something like this:

@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);
}

and then access the swagger generated json via localhost:8080/api/myswagger. Is this possible?

like image 400
user1981275 Avatar asked Aug 23 '17 14:08

user1981275


People also ask

Where is swagger JSON file located?

JSON file is located at http://{root}/swagger/docs/swagger this.


Video Answer


1 Answers

Possible and pretty simple

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 = "[email protected]"
                ),
                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();
        }
    }

}

Gives json:

{
  "swagger": "2.0",
  "info": {
    "description": "description",
    "version": "0.2",
    "title": "title",
    "termsOfService": "termsOfService",
    "contact": {
      "name": "contact",
      "url": "http://contact.org",
      "email": "[email protected]"
    },
    "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"
          }
        }
      }
    }
  }
}
like image 110
egorlitvinenko Avatar answered Oct 08 '22 09:10

egorlitvinenko