REST WebServices Statelessness

The Statelessness means not having any state, REST means Representational State Transfer, which boils down to the same things that the server hosting REST does not store any state about the client session on its side.

Each request from the client to server must contain all of the information necessary to understand the request, and it cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client. Client is responsible for storing and handling all application state related information on client side.

To maintain statelessness, one should not store authorization details of client on the server, each request to the server should contain all the required details. As each request is considered to be a new request.

Advantages of REST being Stateless :

  1. It has drastically reduced the code – by reducing the code of server side snychronization logic.
  2. East to scale up, as there are no sessions to maintain so any server can handle multiple requests.
  3. Easy to cache as well.
  4. Server knows about each request by each client as the client carries all required information with each request, and can be tracked.
  5. Web services need not maintain the client’s previous interactions.

Summary

In this tutorial we learnt about the statelessness of REST apis and its advantages.
I hope you liked it !


REST Jackson API Hello World REST API Example

In this article we will learn how to use JACKSON api in a jersey based rest web services project in java. Jersey uses Jackson to convert object to / form JSON. In this tutorial, we show you how to convert a “Track” object into JSON format, and return it back to user.

Tools used

Maven
JDK 1.8 (even 1.6 would work fine)
Eclipse/IntelliJ(you can use whichever you are comfortable with)
Tomcat Server 8

These steps are followed in this tutorial,

it’s Damn Easy !

Step 1: create a java web project in eclipse and convert it to maven project.
Step 2: add jersey jackson dependency in pom.xml and update the project.
Step 3: create an API class.
Step 4: in the web.xml add the servlet and servlet mapping.
Step 5: Just run the project, Hurray !

POM Dependencies

<properties>
    <jersey2.version>2.28</jersey2.version>
    <jaxrs.version>2.0.1</jaxrs.version>
</properties>

<dependencies>
  <!-- JAX-RS -->
      <dependency>
          <groupId>javax.ws.rs</groupId>
          <artifactId>javax.ws.rs-api</artifactId>
          <version>${jaxrs.version}</version>
      </dependency>
      <!-- Jersey 2.28 -->
      <dependency>
          <groupId>org.glassfish.jersey.containers</groupId>
          <artifactId>jersey-container-servlet</artifactId>
          <version>${jersey2.version}</version>
      </dependency>
      <dependency>
          <groupId>org.glassfish.jersey.core</groupId>
          <artifactId>jersey-server</artifactId>
          <version>${jersey2.version}</version>
      </dependency>
      <dependency>
          <groupId>org.glassfish.jersey.inject</groupId>
          <artifactId>jersey-hk2</artifactId>
          <version>2.28</version>
      </dependency>

      <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/
        jersey-media-json-jackson -->
      <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.28</version>
      </dependency>
</dependencies>
  

Note: What happens when you do not add jersey-media-json-jackson jar in pom.xml ? The API when hit returns a SEVERE exception:
SEVERE: MessageBodyWriter not found for media type=application/json, type=class com.programmertoday.restjersey.model.Department, genericType=class com.programmertoday.restjersey.model.Department.
Because the resource is trying to produce an object of type json, but it does not find any convertor which converts Object into a json, hence adding the above jackson jar resolves this issue.

1. API code

package com.programmertoday.restjersey.api;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/api")
public class JerseyResource {

  @GET
  @Path("/department")
  @Produces(MediaType.APPLICATION_JSON)
    public Department getDepartment()
    {
          return new Department("IT","Information Technology");
    }
}
   

2. Model Class

package com.programmertoday.restjersey.model;

public class Department {

  private String depName;
  private String depCode;

  public Department(String a, String b) {
    this.depCode = a;
    this.depName = b;
  }

  public String getDepName() {
    return depName;
  }

  public void setDepName(String depName) {
    this.depName = depName;
  }

  public String getDepCode() {
    return depCode;
  }

  public void setDepCode(String depCode) {
    this.depCode = depCode;
  }
}
    

3. Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
id="WebApp_ID" version="3.0">

<display-name>RESTful_Project</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
              <param-name>jersey.config.server.provider.packages</param-name>
              <param-value>com.programmertoday.restjersey.api</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
      
</web-app>
      

TEST the code

Add a tomcat server and run the project !!

Using any REST client OR any web browser like google chrome open the below url to hit the api.

http://localhost:8080/RESTful_Project/rest/api/department

{"depName":"Information Technology","depCode":"IT"}

Summary

In this article we learnt how to create a simple Jersey based REST API with JACKSON, which leverages us to convert the model class to JSON on the fly. There is no need to write a JSON Array explicitly for this. It’s Super simple and easy !.
Hope you liked the article !


REST Jersey Hello World REST API Example

In this tutorial we will learn how to make a jersey based rest web services project in a java. And if you are new to rest web services this tutorial will also help you create your first basic sample rest api project.

Libraries used

Jersey 2.28

Note : Jersey 2.28 library has been released and is available in maven central! Jersey 2.28, the first Jakarta EE implementation of JAX-RS 2.1 has finally been released.
https://jersey.github.io/

Tools used

Maven
JDK 1.8 (even 1.6 would work fine)
Eclipse/IntelliJ(you can use whichever you are comfortable with)
Tomcat Server 8

These steps are followed in this tutorial.

it’s Damn Easy !

Step 1: create a java web project in eclipse and convert it to maven project.
Step 2: add jersey dependency in pom.xml and update the project.
Step 3: create an API class.
Step 4: in the web.xml add the servlet and servlet mapping.
Step 5: Just run the project, Hurray !

POM Dependencies

<properties>
    <jersey2.version>2.28</jersey2.version>
    <jaxrs.version>2.1.1</jaxrs.version>
</properties>

<dependencies>
  <!-- JAX-RS -->
      <dependency>
          <groupId>javax.ws.rs</groupId>
          <artifactId>javax.ws.rs-api</artifactId>
          <version>${jaxrs.version}</version>
      </dependency>
      <!-- Jersey 2.28 -->
      <dependency>
          <groupId>org.glassfish.jersey.containers</groupId>
          <artifactId>jersey-container-servlet</artifactId>
          <version>${jersey2.version}</version>
      </dependency>
      <dependency>
          <groupId>org.glassfish.jersey.core</groupId>
          <artifactId>jersey-server</artifactId>
          <version>${jersey2.version}</version>
      </dependency>

<!-- add the below dependency for the below reason, otherwise it throws Injection Exception -->
      <dependency>
          <groupId>org.glassfish.jersey.inject</groupId>
          <artifactId>jersey-hk2</artifactId>
          <version>2.28</version>
      </dependency>
</dependencies>
  

Here is the reason. Starting from Jersey 2.26, Jersey removed HK2 as a hard dependency. It created an SPI as a facade for the dependency injection provider, in the form of the InjectionManager and InjectionManagerFactory. So for Jersey to run, we need to have an implementation of the InjectionManagerFactory. There are two implementations of this, which are for HK2 and CDI.

1. API code

package com.programmertoday.restjersey.api;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/api")
public class JerseyResource {

  @GET
  @Path("/message")
    public String getMyMessage()
    {
          return "Hello World - its Jersey 2 REST API";
    }
}
 

2. Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
id="WebApp_ID" version="3.0">
  
  <display-name>RESTful_Project</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
              <param-name>jersey.config.server.provider.packages</param-name>
              <param-value>com.programmertoday.restjersey.api</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
      
</web-app>
      

TEST the code

Add a tomcat server and run the project !!

Using any REST client OR any web browser like google chrome open the below url to hit the api.

http://localhost:8080/RESTful_Project/rest/api/message

http://localhost:8080/RESTful_Project/rest/api/message

Summary

In this article we learnt how to create a simple Jersey based REST API Project and how to run it, its Super simple and easy !.
Hope you liked the article !


RESTful HTTP Status Codes

Http code Standards:

1xx: Informational – Communicates transfer protocol-level information
2xx: Success -Indicates that the client’s request was accepted successfully.
3xx: Redirection – Indicates that the client must take some additional action in order to complete their request.
4xx: Client Error – This category of error status codes points the finger at clients.
5xx: Server Error – The server takes responsibility for these error status codes.

Use HTTP status codes

200 – OK – Eyerything is working
201 – OK – New resource has been created
204 – OK – The resource was successfully deleted
304 – Not Modified – The client can use cached data
400 – Bad Request – The request was invalid or cannot be served. The exact error should be explained in the error payload. E.g. „The JSON is not valid“
401 – Unauthorized – The request requires an user authentication
403 – Forbidden – The server understood the request, but is refusing it or the access is not allowed.
404 – Not found – There is no resource behind the URI.
422 – Unprocessable Entity – Should be used if the server cannot process the enitity, e.g. if an image cannot be formatted or mandatory fields are missing in the payload.
500 – Internal Server Error – API developers should avoid this error. If an error occurs in the global catch blog, the stracktrace should be logged and not returned as response.

Summary

In this tutorial we learnt about REST Http Status Codes, the Most used Http status codes and its meaning.
Hope you liked the article !