Create first RESTFul Web Service using Jersey framework (CRUD operations)

What we discuss in this post?

  1. What is REST and RESTFul Web Service.
  2. Create RESTFul web service using Jersy framework.
  3. POST user defined object or POJO.
    • POST JSON of POJO to RESTFul web service.
  4. POST user defined object or POJO.
    • POST JSON of POJO to RESTFul web service.
    • Generate Response as XML.
  5. GET JSON of user defined object or POJO.
  6. GET XML of user defined object

1. What is REST (Representational State Transfer) ?

REST is architectural style which is mostly used to build RESTFul web services. In REST paradigm, we always think about the resources similarly like in OOPS, we always think about the objects. In REST architectural style, Server and client transfer information using standard protocol http(s) and resources are accessed using URI (Uniform Resource Identifiers).
Generally REST will have following CRUD operation, CRUD operations are typically mapped to http(s) methods

  • C (Create)    ->  POST
  • R (Retrieve)  -> GET
  • U (Update)    -> PUT
  • D (Delete)     -> Delete

We will create standard GET and POST resource in our service. We will also demonstrate how to pass object from client to service and vice versa. We will have following methods in our Service class

  1. GET Request will return the output in text format
  2. GET Request with http://localhost:9090/service/json
    • REST service will return, the object EmployeeModel in JSON format like
      • { name: “randomb808”, age: 90 }
  3. GET Request with http://localhost:9090/service/xml
    • REST Service will return object EmployeeModel in XML format like :
      • <Employee>
        <name>randomb808</name>
        <age>90 </age>
        </Employee>
  4. POST EmployeeModel object to Service:
    • Send EmployeeModel as JSON to service
    • The response will be send back as XML format, as shown in step 3.
    • This is example of consuming JSON as Object.
  5. POST request to send String parameter:
    • String is send as post parameter to REST service
    • The REST service will send the response like
      • Jersey Says :”what ever string passed from client”

2. Example of RESTFul web service exposing GET resource.

We will create class named Service, which will expose the GET and POST resources. These GET and POST resources will be used by REST client.

@Path("/service")
public class Service {
private static final String text = "status :Server is running " +
         "\ntime : %s";
@GET
@Consumes(MediaType.TEXT_PLAIN)
public Response getText() {
 String response = String.format(text, new Date());
 return Response.status(Response.Status.OK).entity(response).type(MediaType.TEXT_PLAIN).build();
}

@GET
@Path("/json")
@Produces(MediaType.APPLICATION_JSON)
public EmployeeModel getJson() {

 //...........db operation..
 //suppose we get these value from database
 //............
 String randomName = "random" + UUID.randomUUID().toString().substring(0,4);
 int randomAge = new Random().nextInt(100);

 //returns the value received from database
 return new EmployeeModel(randomName,randomAge);
 //return new EmployeeModel("Tom", 21);

}

3. Understand the important attributes of RESTFul web service

  1. The Service class will have @Path annotation, which will specify the root location of all the resources (which this class going to have). So, if we would like to access any of the resources within Service class it has to prefixed with /service path.
  2. The next important thing is @GET annotation, which is GET method of HTTP protocol. The getText resource is generating the output in TEXT_PLAIN format (in above function, we have used “type(MediaType.TEXT_PLAIN)”).
  3. Next resource of service class is getJson, it generates the output in the JSON format. Which we can guess by looking at its  annotation @Produces(MediaType.APPLICATION_JSON).
    • The function getJson has another important things.
      1. We are creating object EmployeeModel using randomName and randomAge.
      2. Serializing EmployeeModel object as JSON (using Jersey JSON serializer)
      3. Resource has @Produces(MediaType.APPLICATION_JSON) to generate JSON output
      4. We have jersey-media-json-jackson dependency to cater JSON serialization.

4. EmployeeModel class:

  • EmployeeModel class is model class of our application.
  • We will serialize EmployeeModel class using Jackson serialization.
@XmlRootElement (name = "Employee")
public class EmployeeModel {
    public String name;
    public int age;
    public EmployeeModel() {} // JAXB needs this
 
    public EmployeeModel(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

EmployeeModel class

  1. EmployeeModel has @XmlRootElement to specify the root name.
  2. jersey-media-json-jackson jar will converts EmployeeModel to JSON format.
    • Like: { name: “randomb808”, age: 90 }.

5. POST method RESTFul sercvice resource:

  • Service resource has postEmployee method, which will receive EmployeeModel Object.
  • The important attributes of postEmployee method is as follows:
    • We can access this resource using /service/json/object url
    • HTTP Method type is POST
    • Resource consumes JSON as input,
      • JSON will converted to EmployeeModel object during deserialization process.
        • Opposite of what happened in getJson or getXml method.
        • jersey-media-json-jackson will again come into play.
    • We performs certain operations in the resource
      • Generates the output in xml.
      • Resource has @Produces(MediaType.APPLICATION_XML).
@POST
@Path("/json/object")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_XML)
public EmployeeModel postEmployee(EmployeeModel employee) {
 //We receive the object from client
 //Client might have send the json string as {"name":"hello","age":"24"}
 //do some processing ..save in database
 //return the output in xml format....
 return employee;
}

6. Complete code of RESTFul Service resource (Java/ Jersey framework)

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Date;
import java.util.Random;
import java.util.UUID;


@Path("/service")
public class Service {

 private static final String text = "status :Server is running " +
          "\ntime : %s";
 @GET
 @Consumes(MediaType.TEXT_PLAIN)
 public Response getText() {
  String response = String.format(text, new Date());
  return Response.status(Response.Status.OK).entity(response).type(MediaType.TEXT_PLAIN).build();
 }

 @GET
 @Path("/json")
 @Produces(MediaType.APPLICATION_JSON)
 public EmployeeModel getJson() {

  //...........db operation..
  //suppose we get these value from database
  //............
  String randomName = "random" + UUID.randomUUID().toString().substring(0,4);
  int randomAge = new Random().nextInt(100);

  //returns the value received from database
  return new EmployeeModel(randomName,randomAge);
  //return new EmployeeModel("Tom", 21);

 }

 @GET
 @Path("/xml")
 @Produces(MediaType.APPLICATION_XML)
 public EmployeeModel getXml() {

  //...........db operation..
  //suppose we get these value from database
  //............
  String randomName = "random" + UUID.randomUUID().toString().substring(0,4);
  int randomAge = new Random().nextInt(100);

  //returns the value received from database
  return new EmployeeModel(randomName,randomAge);
  //return new EmployeeModel("Tom", 21);
 }

 @POST
 @Path("/json/object")
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_XML)
 public EmployeeModel postEmployee(EmployeeModel employee) {
  //We receive the object from client
  //Client might have send the json string as {"name":"hello","age":"24"}
  //do some processing ..save in database
  //return the output in xml format....
  return employee;
 }

 @POST
 @Path("/json/{name}")
 @Produces(MediaType.TEXT_PLAIN)
 public Response postPathParamValue(@PathParam("name") String name) {
  //Return what ever received from client
  String output = "Jersey Says :" + name;
  return Response.status(200).entity(output).build();
 }
}

With the above basics, we can go ahead and create RESTful web service using Jersey framework. We can download the complete code from below link. Once we download the zip file from below link, we can find the ReadMe.md file, under project directory. The ReadMe.md file contains the detail description about each resource call.

Download Code – RESTFul Web Service Jersey GET POST JSON Object

Scroll to Top