RESTful WebServices – Fundamentals

REST stands for REpresentational State Transfer. REST is an architetured style of designing applications. It’s a request response model in which data can be transferred in multiple formats such as JSON, XML etc. In a REST based architecture everything is a resource, a resource can be accessed through a common interface based on http standard methods. Every resource is identified by a an id called a URL.

JAX-RS – Java API for RESTful Web Services

JAX-RS : defined in JSR 311 – is a Java programming language API spec that provides support in creating web services according to the Representational State Transfer (REST) architectural pattern. It uses annotations, they include annotations like (@Path, @Get, @Put, etc).

Http methods are :

  1. GET − Provides a read only access to a resource. A resource is never changed hence called idempotent.
  2. PUT − creates a new resource. It must also be idempotent.
  3. DELETE − Used to remove a resource.
  4. POST – updates an existing resource or creates a new resource, hence not idempotent.

There are two main implementation of JAX-RS API.
1. Jersey
2. RESTEasy

How to construct standard URIs/URLs ?

some important points to consider while designing an api url are:

  1. Use Plural Noun to define resources
  2. Use Lowercase letters as a good practice
  3. Do not use spaces – instead use underscores or hypens, eg: products_list
  4. Use HTTP verb – use annotations like GET, PUT etc, and do not use getDetails like uri
  5. Must have backward compatibility – Incase old public uri changes then it should never be made unavailable , good practice is to redirect it to the new uri using http code 300.

Difference between SOAP and REST webservices

S.NoSOAPREST
1SOAP is a protocol (Simple Object Access Protocol).REST is an architectural style.
2SOAP can’t use REST because it is a protocol.REST can use SOAP WS because it is just an architecture and can work in protocols like Http, SOAP.
3SOAP uses services interface to expose business logicREST uses urls to expose business logic
4Requires more bandwidth, Since SOAP Messages contain a lot of information inside of it, the amount of data transfer using SOAP is generally a lot.Requires less bandwidth and resources than SOAP
5SOAP allows only xml data formatREST allows different data format such as Plain text, HTML, XML, JSON etc.

When to use REST and when to use SOAP ?

Below are some of the key factors that determine when should one use either one of the technology for web services.

REST services should be used in the following situations :

1. Limited resources and bandwidth – Since SOAP messages are heavier in content and consume a far greater bandwidth, REST should be used in instances where network bandwidth is a constraint.
2. Statelessness – If there is no need to maintain a state of information from one request to another then REST should be used. If you need a proper information flow wherein some information from one request needs to flow into another then SOAP is more suited for that purpose. We can take the example of any online purchasing site. These sites normally need the user first to add items which need to be purchased to a cart. All of the cart items are then transferred to the payment page in order to complete the purchase. This is an example of an application which needs the state feature. The state of the cart items needs to be transferred to the payment page for further processing.
3. Caching – If there is a need to cache a lot of requests then REST is the perfect solution. At times, clients could request for the same resource multiple times. This can increase the number of requests which are sent to the server. By implementing a cache, the most frequent queries results can be stored in an intermediate location. So whenever the client requests for a resource, it will first check the cache. If the resources exist then, it will not proceed to the server. So caching can help in minimizing the amount of trips which are made to the web server.
4. Ease of coding – Coding REST Services and subsequent implementation is far easier than SOAP. So if a quick win solution is required for web services, then REST is the way to go.

SOAP should be used in the following situations :

1. Asynchronous processing and subsequent invocation – if there is a requirement that the client needs a guaranteed level of reliability and security then the new SOAP standard of SOAP 1.2 provides a lot of additional features, especially when it comes to security.
2. A Formal means of communication – if both the client and server have an agreement on the exchange format then SOAP 1.2 gives the rigid specifications for this type of interaction. An example is an online purchasing site in which users add items to a cart before the payment is made. Let’s assume we have a web service that does the final payment. There can be a firm agreement that the web service will only accept the cart item name, unit price, and quantity. If such a scenario exists then, it’s always better to use the SOAP protocol.
3. Stateful operations – if the application has a requirement that state needs to be maintained from one request to another, then the SOAP 1.2 standard provides the WS* structure to support such requirements.

Examples : REST sample apis with/without Response as return type


1. Http GET – to get collection/List of entity

@GET
@Path("/employees")
@Produces(MediaType.APPLICATION_XML)
public Employees getAllEmployees()
{
	Employees list = new Employees();
	list.setEmployeeList(new ArrayList<Employee>());
		
	list.getEmployeeList().add(new Employee(1, "Maverick"));
	list.getEmployeeList().add(new Employee(2, "Batman"));
	list.getEmployeeList().add(new Employee(3, "Robin"));
		
	return list;
}

2. Http GET – to get a single entity

@GET
@Path("/employees/{id}")
@Produces(MediaType.APPLICATION_XML)
public Response updateEmployeeById(@PathParam("id") Integer id)
{
	if(id  < 0){
			return Response.noContent().build();
	}
	Employee emp = new Employee();
		
	emp.setId(id);
	emp.setName("Batman");
		
	GenericEntity<Employee> entity = 
			new GenericEntity<Employee>(emp, Employee.class);
	return Response.ok().entity(entity).build();
}

3. Http POST – to add a single entry in an entity

@POST
@Path("/employees")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response addEmployee( Employee e ) throws URISyntaxException
{
	if(e == null){
	return Response.status(400).entity("Please add employee details !!")
	.build();
	}
		
	if(e.getName() == null) {
	return Response.status(400).entity("Please provide the employee name !!")
	.build();
	}
		
return Response.created(new URI("/rest/employees/"+e.getId()))
.build();
}

REST webservices Hello world tutorial

Next Follow this – tutorial and learn how to create REST webservices using Jersey(library).

Summary

In this article we learnt about RESTful Webservices, REST sample apis, Soap Vs REST apis, When to use what?.
Hope you liked the article !


Leave a Comment