Sunday, February 11, 2018

Using Jersey2Config to generate Swagger 2.0 definition files

Swagger Core Jersey 2.X Project Setup 1.5


Generating swagger.json using Swagger core required some patience.  Following the documentation at https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5#using-the-application-class using Servlet 3.1 finally was able to create swagger.json.  https://github.com/htotapally/Spring5.git is the link to source code.  web.xml contains the swagger initialization code, shown below:

<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">


<servlet>
<servlet-name>Jersey2Config</servlet-name>
<servlet-class>io.swagger.jersey.config.JerseyJaxrsConfig</servlet-class>
<init-param>
<param-name>api.version</param-name>
<param-value>1.0.0</param-value>
</init-param>
<init-param>
<param-name>swagger.api.basepath</param-name>
<param-value>/tt/api</param-value>
</init-param>
<init-param>
<param-name>swagger.api.title</param-name>
<param-value>My Awesome API</param-value>
</init-param>

<load-on-startup>2</load-on-startup>
</servlet>

<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
            io.swagger.jaxrs.listing,com.sbt
        </param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>

</web-app>

Used the command: mvn clean install -Dp.type=war to generate the war file to be deploy in Tomcat.
Once deployed http://localhost:8080/tt/api/swagger.json provided the description of the Rest services provided in the EmployeeResource.  Finally used to Swagger plugin to Chrome to test the API.  All worked out as expected once the Swagger project was set up correctly

No comments:

Post a Comment