Skip to main content

Swagger APIs Server - Complete Description and Integration with JAX-RS, MAVEN and JBoss Server

In the world there are various languages are used to communicate, But it is impossible to learn whole languages, So anyone who go to any corner of the world and know at-least one common language like "English" then he can communicate easily.Means there is made a common international language to communicate with each other.
"For millions of people to communicate, there needs to be a common vocabulary." 
Today Software industries becoming vast on day by day. So if we see on perspective of development then we see that today each software industry uses APIs landscape.It is a best way to connect and share data through APIs.
In software industry they develop the APIs by self or generally they use other's APIs like Google APIs, or any other industry's APIs and integrate in their project on the basis of of the requirements.

So before moving forward let me little introduce about API.
API(Application Program Interface) provides a communication channel between the server and client.
It has a set of protocols, rules and guidelines.
For instance, here we can know about the API through a very basic routine example: 
When we go to any restaurant then the waiter come and ask for serve, then after deciding with our self we call to waiter and order our selective menu items, then simply waiter go t to kitchen room and tell them our order for prepare and after prepared items he come back with our order.
So here if we see "we" is act as a "client", "kitchen-room" is act as  a "server" and waiter is act as a "API".
So we are not direly interact or communicate with kitchen guys we communicate with waiter.

There are various way to implement API, but today REST APIs is a most popular, Basically it provides a REST architecture to create web service.
So if we create any restful project then before going to whole implementation we document these APIs which contains all APIs description like URL, Request-Methods, Content-Type, Request and Response param etc, and after implementation done we also need to discuss with API consumer guys who are simply use and integrate our APIs in their project.
So here if we see there are a lot of times wast for document and also discuss with APIs consumers.
APIs are supposed to connect engineers and allow for sharing of great developments.In some company like Twilio API add value to other products and create ecosystem of shared knowledge.But an APIs is only valuable if it is accessible and working fine otherwise it is totally useless.
So to know about any APIs description it needs a clear and best documentation.Terrible documentation is just as useless as a clock that tells wrong time.So developers have worked hard to find a way to standardized the vocabulary surroundings APIs, that's where Swagger come in.So now it's time to know details about the Swagger.
Swagger: Swagger is basically set of rules(specifications) and tooling for how to semantically define describe APIs.Practically it's a language-agnostic tool that gets everyone on same page.

Swagger is a framework for describing your APIs using a common language that everyone can easily understand.Think of it's as a blueprint for a house, you can use whatever building materials you like but you can not step outside the parameters of the blueprint.

There are other frameworks such as RAML, APIBlueprint and Summation, that have gained some popularity but Swagger provide more benefits than just helping create clear documentation.
Advantage of Swagger: 
We know that each the day there is new technology realized so before using any of new technology
we also required to know about the advantages and disadvantages of this.
So Swagger has a lots a of advantages, we are mentioned some important advantages:

1. It's comprehensible for developers and non-developers: In any company Product Managers, partners, and even potentials client can have inputs into design in your APIs, because thy can see it clearly mapped out in this friendly UI.
2. It's human readable and machine readable:This means that not only can be shared with your team internally, but the same documentation can be used to automate API dependent process means in code implementation.
3. It's is easily adjustable: This makes it great for debugging and testing purposes, it is very helpful for QA people.

These three benefits not only make developers's lives easier, but the make the APIs more consumable.Any API that that adheres to the Swagger spec is easy to read, easy to iterate, and easy to consume.That's why we also need to jumped on Swagger train.

Design Approaches: With this blueprint in mind, there are two ways to take advantage of Swagger.
1.  Top-down Approach(Design first): In this you are using Swagger to design your APIs before you have written any actual code.
2. Bottom-up Approach(Code First): This means you have already written the code for your APIs, and you will be using Swagger to document your APIs.
In early days, it was popular for APIs to be created code first.This is much easier because you can make adjustments as you go, and it fits nicely into an Agile delivery process.But because you are not thinking about the design, this can make for an API that's difficult to understand and document well. 
The push for clear, easy-to-read  documentation has popularized the design-first approach. Not only can more people have input on your documentation, but it actually result in cleaner code, you are forced to think simple, more concise, and easy to follow. 
 The Swagger Specification:  
 At the heart of Swagger is its specification.The Swagger spec is rulebook  that standardizes API practices (how to define parameters, path, responses, models, etc) and every other parts of  Swagger is just a way of appropriating or creating API documentation that works with this rules. Swagger Tools:
 Here are some beautiful and amazing tools for using Swagger. 
1. Swagger-Editor (editor.swagger.io)
2. Swagger- codegen(swagger-codegen/)
3. Swagger-UI(Swagger-UI )
Lets introduce each tools in brief here.
1. Swagger-Editor: The swagger-editor is a convenient tool that addresses this issue.You can write up your documentation in YAML( YAML stands for YAML Ain't Markup Language) or JSON and have it automatically compared with against the Swagger spec. Any mistakes are flagged, and alternatives are suggested.This way when you publish you documentation, you can be sure that it's error-free.You can used this Swagger-editor on http://editor.swagger.io. Here are some following samples for Swagger-Editor.

1. How to document APIs using YAML in Swagger-Editor-


 2.If any error occurred then it's automatically showing and suggesting:

2. Swagger-codegen: Swagger-codegen is use to generate client side libraries in over different languages(java, html, ..) for your APIs.You can see here -



3. Swagger-UI: After generating swagger.jsosn or swagger.yaml file we can see this APIs swagger documentation using Swagger UI it can be found as chrome extension.So just down load chrome extension for Swagger UI and you can use this.

  
Here is a sample example for Swagger UI-





Here one thing is very interesting, you can see that all APIs is mapped with an entity level like plans, stocks, etc you can click on each entities and see all APIs with method name.
Each method(GET,POST,DELETE,PUT...) is expandable. By clicking Expand Operations you will get a full descriptions with request parameters and parameters and you can also test each API using try it.
Implementation of Swagger in Server Code( Bottom-Up or Code First): 
Now its time to use Swagger in our development code.
So before implementing this in our code, we first introduce with some common Swagger annotations and use of these.
Swagger Annotations: Here are some important annotations which very useful during implementation.
@Api- Api annotation is used to declare a Swagger Resource API.
it serves a double purposes- it affect the Resource listing and the API Declaration.
Important:only classes that are annotated with @Api will be scanned by swaager. 
In the Resource Listing, the annotation will translate to the Resource Object.
In the API Declaration, it will basically serves as the basic for the API Declaration  itself.
JAX-RS Example:
@Path("/swagger")
@Api(value="/swagger" tags="swagger: Swagger")
@Produces(application/json)
public class Swagger{
-------------------------
-------------------------
}

Here we have a "swagger" resource that is exposed on /swagger.The @Api here states that  the documentation of this resource will be hosted under under /swagger.tags will give the description about this particular API. Produce and Consume Media Type Swagger automatically pick up.                          Operation Declaration-
@ApiOperation: The @ApiOperation is used to declare a single operation within an API resource. An operation is considered a unique combination of a path and a HTTP method. Only methods that are annotated with @ApiOperation will be scanned and added the API Declaration.
The annotation will affect two parts of the Swagger output, the API Object, which would be created one per path, and the Operation Object, which would be created one per @ApiOperation. Remember that when using Servlets, the @Api would affect the API Object instead as it sets the path.
A JAX-RS usage would be:
  @GET                                                         @Path("/findByStatus")                                           @ApiOperation(value = "Finds Pets by status",notes = "Multiple status values can be provided with comma seperated strings",response = Pet.class,responseContainer = "List")        public Response findPetsByStatus(...) { ... }
@ApiResponses, @ApiResponse: It's a common practice to return errors (or other success messages) using HTTP status codes. While the general return type of an operation is defined in the @ApiOperation, the rest of the return codes should be described using these annotations.
The @ApiResponse describes a concrete possible response. It cannot be used directly on the method and needs to be included in the array value of @ApiResponses (whether there's one response or more).If the response is accompanied with a body, the body model can be described as well (one model per response).
There's no difference in usage between usages (JAX-RS, Servlets or otherwise):                                                               @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied"),@ApiResponse(code = 404, message = "Pet not found") })                                           
public Response getPetById(...) {...}
@ApiParam: The @ApiParam is used solely with the JAX-RS parameterannotations(@PathParam@QueryParam@HeaderParam@FormParam and in JAX-RS 2, @BeanParam). While swagger-core scans these annotations by default, the @ApiParam can be used to add more details on the parameters or change the values as they are read from the code.
In the Swagger Specification, this translates to the Parameter Object.Swagger will pick up the value() of these annotations and use them as the parameter name, and based on the the annotation it will also set the parameter type. For the body parameter (the single input parameter of a JAX-RS method), the name will automatically be set as body (as required by the Swagger Specification).
Swagger will also use the value of @DefaultValue as the default value property if one exists.
@Path("/{username}")
@ApiOperation(value = "Updated user",notes = "This can only be done by the logged in user.")
public Response updateUser(
@ApiParam(value = "name that need to be updated", required = true
@PathParam("username") String username,
@ApiParam(value = "Updated user object", required = true) User user) {...}
Here we have two parameters. The first, username which is a part of the path. The second is the body, in this case a User object. Note that both parameters have the required property set to true. For the @PathParam, this is redundant as it is mandatory by default and cannot be overridden.
@ApiImplicitParams,@ApiImplicitParam:
You may wish you describe operation parameters manually. This can be for various reasons, for example:
  • Using Servlets which don't use JAX-RS annotations.
  • Wanting to hide a parameter as it is defined and override it with a completely different definition.
  • Describe a parameter that is used by a filter or another resource prior to reaching the JAX-RS implementation.
Since there can be several parameters to be included, the @ApiImplicitParams allows for multiple @ApiImplicitParam definitions.
In the Swagger Specification, these translate to the Parameter Object.
When defining parameters implicitly, it's important to set namedataType and paramType for Swagger's definitions to be proper.
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "User's name", required = true, dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "email", value = "User's email", required = false, dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "id", value = "User ID", required = true, dataType = "long", paramType = "query")
})
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {...}
Model Declaration:
@ApiModel:At its basic functionality, you an use @ApiModel to change the name of the model and add a description to it:               @ApiModel(value="DifferentModel", description="Sample model for the documentation")                                                               public class OriginalModel {...}
@ApiModelProperty:
While swagger-core will introspect fields and setters/getters, it will also read and process JAXB annotations. The @ApiModelProperty allows controlling Swagger-specific definitions such as allowed values, and additional notes. It also offers additional filtering properties in case you want to hide the property in certain scenarios.
For information about this in the Swagger Spec, check out the Property Object.                                   @ApiModelProperty(value = "pet status in the store", allowableValues = "available,pending,sold")                            public String getStatus() {                                                        
return status;
                                      }
This is a simple example of adding a short description to the model property. It can also be observed that while status is a String, we document it as having only three possible values.
Implementation:
Required Maven Dependencies:
1. <dependency>
      <groupId>io.swagger</groupId>
      <artifactId>swagger-jersey2-jaxrs</artifactId>
      <scope>compile</scope>
      <version>1.5.12</version>
</dependency>
2.<dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.1.7</version>
      <scope>compile</scope>
</dependency>
3.<dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-core</artifactId>
      <version>1.1.7</version>
      <scope>compile</scope>
</dependency>
4.<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
</dependency>
5.<dependency>
      <groupId>org.glassfish.jersey.containers</groupId>
      <artifactId>jersey-container-servlet-core</artifactId>
      <version>2.23.1</version>
</dependency>
6.<dependency>
      <groupId>org.glassfish.jersey.media</groupId>
      <artifactId>jersey-media-multipart</artifactId>
      <version>2.23.1</version>
</dependency>
7.<dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-joda</artifactId>
      <version>2.8.7</version>
</dependency>
8.<dependency>
      <groupId>com.fasterxml.jackson.jaxrs</groupId>
      <artifactId>jackson-jaxrs-json-provider</artifactId>
      <version>2.8.7</version>
</dependency>
9.<dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
        <scope>provided</scope>
</dependency>
Web.xml:- 
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.resources</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.providers</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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,
io.swagger.sample.resource,
com.oneassist
com.oneassist.partnerpanel.webservice.resources,
com.oneassist.eretail.webservice.resources,
</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.wadl.disableWadl</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<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.title</param-name>
<param-value>Partner Panel APIs with Swagger Server</param-value>
</init-param>
<init-param>
<param-name>swagger.api.basepath</param-name>
<param-value>http://localhost:8080/partnerpanel.webservice</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>Bootstrap</servlet-name>
<servlet-class>com.oneassist.Bootstrap</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>ApiOriginFilter</filter-name>
<filter-class>com.oneassist.ApiOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ApiOriginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Sonatype-snapshots repositories:
Add this sonatype-snaphot repositories in pom.xml file.
<repositories>
<repository>
<id>sonatype-snapshots</id
<url>https://oss.sonatype.org/content/repositories/snapshots</url
<snapshots>

<enabled>true</enabled>

</snapshots>

</repository>

</repositories>

If you are using jboss server for deployment then add jboss-deployment-structure.xml file in WEB-INF folder.
jboss-deployment-structure.xml:-
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>

    <deployment>

        <exclusions>

            <!-- Exclude RestEasy conflicts -->

            <module name="javaee.api" />

            <module name="javax.ws.rs.api"/>

            <module name="org.jboss.resteasy.resteasy-jaxrs" />

        </exclusions>

    </deployment>

</jboss-deployment-structure>

Simple Swagger Project:
Here now I am going to create a simple swagger implementation using JAX-RS and maven in java.
Step 1. Create a Dynamic webapp maven project in using following command-
mvn archetype:generate -DgroupId=com.oneassist.swagger -DartifactId=swagger.webservice -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

Step 2: Use following command to build class path.
mvn eclipse:clean
mvn eclipse:eclipse

Step 3: Now add all required maven dependencies in pom.xml, we have added all and following pom.xml be-
pom.xml: 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.oneassist.swagger</groupId>
  <artifactId>swagger.webservice</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>swagger.webservice Maven Webapp</name>
  <repositories>
<repository>
<id>sonatype-snapshots</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jdk.version>1.7</jdk.version>
<jersey-version>2.23.1</jersey-version>
<jackson-version>2.8.7</jackson-version>
    <junit-version>4.12</junit-version>
    <logback-version>1.1.7</logback-version>
    <servlet-api-version>2.5</servlet-api-version>
    <swagger-core-version>1.5.12</swagger-core-version>
</properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.swagger</groupId>
      <artifactId>swagger-jersey2-jaxrs</artifactId>
      <scope>compile</scope>
      <version>${swagger-core-version}</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>${logback-version}</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-core</artifactId>
      <version>${logback-version}</version>
      <scope>compile</scope>
    </dependency>
     <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>${servlet-api-version}</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish.jersey.containers</groupId>
      <artifactId>jersey-container-servlet-core</artifactId>
      <version>${jersey-version}</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish.jersey.media</groupId>
      <artifactId>jersey-media-multipart</artifactId>
      <version>${jersey-version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-joda</artifactId>
      <version>${jackson-version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.jaxrs</groupId>
      <artifactId>jackson-jaxrs-json-provider</artifactId>
      <version>${jackson-version}</version>
    </dependency>
     <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey-version}</version>
</dependency>
  </dependencies>
  <build>
    <finalName>swagger.webservice</finalName>
  </build>
</project>

Step 4: Now run following commands to add all maven dependency from maven central repositories.
mvn clean install
Now you can see all dependencies will be added.

Step 5: Now create three seperared package- models, resources, and services.
com.oneassist.swagger.resources
com.oneassist.swagger.services
com.oneassist.swagger.models

Step 6: Create Employee class in com.oneassist.swagger.models package-
Employee.java
package com.oneassist.swagger.models;

/**

 * Employee model

 * 

 * @author Sanjeev Gupta

 *

 */

public class Employee {

 private String name;

private String dateOfBirth;

private int age;

private int employeeId;

private String jobProfile;



/**

* @return the name

*/

public String getName() {

return name;

}

/**

* @param name

*            the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the dateOfBirth
*/
public String getDateOfBirth() {
return dateOfBirth;
}
/**
* @param dateOfBirth
*            the dateOfBirth to set
*/
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age
*            the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the employeeId
*/
public int getEmployeeId() {
return employeeId;
}
/**
* @param employeeId
*            the employeeId to set
*/
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
/**
* @return the jobProfile
*/
public String getJobProfile() {
return jobProfile;
}
/**
* @param jobProfile
*            the jobProfile to set
*/
public void setJobProfile(String jobProfile) {
this.jobProfile = jobProfile;
}
}

Step 7: Create EmployeeResource class in com.oneassist.swagger.resources package.
EmployeeResource.java

package com.oneassist.swagger.resources;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.oneassist.swagger.models.Employee;
import com.oneassist.swagger.services.EmployeeService;

/**
 * This class is just for showing employee details.
 * @author Sanjeev Gupta
 *
 */
@Path("/employees")
@Api(value="/employees", tags="employee: Get all employee details")
public class EmployeeResource {

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value="create new employee" ,notes = "Create a new employee account", response=Response.class)
@ApiResponses({
@ApiResponse(code = 201, message = "Successfully created"),
@ApiResponse(code=400, message= "Please enter required fields"),
@ApiResponse(code=500, message="Internal error server")
})
public Response createEmployee(
@ApiParam(value="employee details", required=true)
Employee employee){
EmployeeService employeeService = new EmployeeService() ;
Employee createdEmployee = employeeService.createEmployee(employee);
if( createdEmployee.getEmployeeId() == 0){
return Response.status(Status.BAD_REQUEST).entity(createdEmployee).build();
}
return Response.status(Status.CREATED).entity(createdEmployee).build();
}
}

Step 8: Create EmployeeService class in com.oneassist.swagger.services package.
EmployeeService.class
package com.oneassist.swagger.services;

import java.util.Random;
import com.oneassist.swagger.models.Employee;

/**
 * 
 * @author Sanjeev Gupta
 *
 */
public class EmployeeService {
public Employee createEmployee(Employee employee) {
if (employee != null && employee.getName() != null
&& employee.getJobProfile() != null && employee.getAge() != 0) {
employee.setEmployeeId(getRandomNo());
}
return employee;
}

/**
* Generate random number
*/
public int getRandomNo() {
Random rand = new Random();
return rand.nextInt(50) + 1;
}
}

Step 9: Create Bootstrap class in com.oneassist.swagger package
Bootstrap.java
package com.oneassist.swagger;



import io.swagger.jaxrs.config.SwaggerContextService;

import io.swagger.models.Info;

import io.swagger.models.License;

import io.swagger.models.Swagger;



import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;



/**

 * 

 * @author Sanjeev Gupta

 *

 */

public class Bootstrap extends HttpServlet {

private static final long serialVersionUID = 1L;



@Override

public void init(ServletConfig config) throws ServletException {

Info info = new Info()

.title("Swagger APIs Server")

.description(

"This is Swagger Tool for APIs here you can test the all APIs with proper requests and responses")
.license(
new License().name("OneAssist").url(
"http://www.oneassist.in"));

Swagger swagger = new Swagger().info(info);
new SwaggerContextService().withServletConfig(config).updateSwagger(
swagger);
}
}

Step 10: Create ApiOriginFilter class in com.oneassist.swagger package
ApiOriginFilter.java:
package com.oneassist.swagger;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2017-05-04T07:01:50.247Z")
public class ApiOriginFilter implements javax.servlet.Filter {

    public void doFilter(ServletRequest request, ServletResponse response,

            FilterChain chain) throws IOException, ServletException {

        HttpServletResponse res = (HttpServletResponse) response;

        res.addHeader("Access-Control-Allow-Origin", "*");

        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

        res.addHeader("Access-Control-Allow-Headers", "Content-Type");

        chain.doFilter(request, response);

    }



    public void destroy() {}



    public void init(FilterConfig filterConfig) throws ServletException {}
}

Step 11: Now add web.xml file: 
web.xml
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
<param-name>resteasy.scan</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.resources</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>resteasy.scan.providers</param-name>
<param-value>false</param-value>
</context-param>
<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,
io.swagger.sample.resource,
com.oneassist.swagger,
com.oneassist.swagger.resources
</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.wadl.disableWadl</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<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.title</param-name>
<param-value>Swagger APIs Server</param-value>
</init-param>
<init-param>
<param-name>swagger.api.basepath</param-name>
<param-value>http://localhost:8080/swagger.webservice</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>Bootstrap</servlet-name>
<servlet-class>com.oneassist.swagger.Bootstrap</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>ApiOriginFilter</filter-name>
<filter-class>com.oneassist.swagger.ApiOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ApiOriginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

Step 12: Create jboss-deployment-structure.xml file into WEB-INF folder.  
jboss-deployment-structure.xml:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
    <deployment>
        <exclusions>
            <!-- Exclude RestEasy conflicts -->
            <module name="javaee.api" />
            <module name="javax.ws.rs.api"/>
            <module name="org.jboss.resteasy.resteasy-jaxrs" />
        </exclusions>
    </deployment>
</jboss-deployment-structure>

Now you can see project structure will be show as following-

Step 13: Now build the project and create war file using following commond:
mvn clean install
now you can created
swagger.webservice.war
will be created.
Step 14: Now you can test this API in using postman


now you can see that API is successfully working.

Step 14: Now open Swagger-UI ( If you don`t have you can download it from chrome extension).
explore http://localhost:8080/swagger.webservice/swagger.json URL in Swagger-UI. You can see now your APIs in this UI.



Click on List Operations, now you can see all APIs with entity level path and method-
Click on Expand Operations and you can see details about your API, like request param and possible responses with HTTP Status code.
You can consume API using Try it out!.

Download Source Code: You can download the source code from the GitHub using link-https://github.com/worldsanjeev600/RestWebservice.git 

In new post I am going to provide how to write YAML (OpenAPI) for API creation.




Comments