Skip to main content

ReST - Representational State Transfer

ReST - Stands for Representational State Transfer

There are numerous notes available on net for developing ReSTful web services. If you go through each of them it feels like confusing and conflicting. Sometimes it is because of technology advancement or because of improper explanation. Whatever information I am providing today may not fit after few years J
So, I will start the discussion and will try my best to give accurate and reliable notes that will help you understanding the in and out of ReST services.

What is ReST?

People get confused whether its pattern or standard or architecture. As far as I have worked and understood, ReST is architecture for developing services. ReST services run over stateless protocol (mostly on HTTP). There are other technologies/standards are available for implementing services which will help connecting two different systems together (irrespective of their own implementation). For example we can achieve the same output using CORBA, RPC or SOAP etc. But compared to ReST these technologies are little complex and needs thorough understanding. But in-case of ReST, it takes less time and effort to start exposing services. ReST services support all the CRUD operations without any complex design. It is lightweight and supports all the functionality that is supported by SOAP/WSDL or RPC.

There will always be debate on practices and artifacts but ReST is fully featured and there's nothing you can do in Web Services that can't be done with a ReSTful implementation.

Some of the popular Companies that have implemented ReST services are:
-          Mirror API from Google is a pure ReST API
-          ReST APLI from Twitter has also gained so much popularity.
-          Amazon has been us9ing ReST services extensively.
-          There is service called ATOM which developed as ReST service and replacement for RSS.
-          Many more are there who are using ReSTful services.
-          Flickr also uses their ReST service

ReST is Lightweight:

I will say ReST is non XML web-based RPC.
Feature wise ReST services are not very different then other Web Service implementations. ReST Services are:
-          Operating System independent
-          Language implementation independent (.Net can interact with Java, C can interact with .Net etc),
-          Standards-based(runs on top of HTTP),
-          ReST does not provide any Security mechanism. We should be use some other mechanism to implement user credential encryption/decryption, session management (if any) etc.

ReST is Stateless:

There is client and there is server which fulfills the client request. Now when the request is raised by the client, the request is also associated with a state or it also contains a state. The request contains input parameters, body, headers etc. When the request goes to server, it tries to process the request and it completes the request by sending proper message via headers, status and response body. Server does not keep any information from any client. Each request is treated separately from Server (even if the multiple requests are coming from same client). In ReST, the user has to construct the request which includes all information for the server to fulfill the request, if there are multiple requests in one session then the state must span over each request. State is all that the server cares about to fulfilling a request in a given session. 

Rest does not have Cookie concept.

ReST is simple to implement:

  • In case of SOAP Web Services the service request will looks as below:



For REST service the request is as follows:

We are just sending the request using URL. This is GET request and it fetches the response over HTTP. The response could be returned in either in JSON or XML format.
  • With SOAP over HTTP we all have to Marshal/un-Marshal the data for further processing. Whether in case of ReST it’s just the client-server setup is required.  That’s all we can write our own test program to unit test the rest services. 
  • The ReST request could have simple or complex input parameters. It supports all the CRUD operations for GET, PUT, DELETE etc. 
  • As I told earlier the response could be in XML or JSON, but I personally belief that JSON output is much simpler and easy to work.  While XML needs somewhat more disciplined and structured development.
  • In case of SOAP based services, we always use to validate the input/output data against the XML validation and use to make sure that the data and data type are in sync.
Simple output of an JSON element will be as follows:
{
"countryCd":"101",
        "countryName":"UAE"
}


Driving components of REST architecture:

  • ReST is Resource based: Each resource is identified by URIs (called as resource identifiers). Resources are the key part of ReST architecture and are similar as we have operation/methods or services in SOAP or RPC based web services. So each request is termed as resource in ReST which contains all the required information. 
  • Client Oriented: In ReST the server sends some HTML, XML or JSON that represents some database records for the given input. User will have full control on representation layer and will not bother about any service side implementation. So client will bother about their implementation only. 
  • Client-Server Model: ReST works on client-server model. So each request will be initiated from client and will be processed by server.
  • Stateless: The server does not keep any state information about the ReST client. Each request from the client will be treated as new request (even though the same client sends multiple requests to the server).
  • Cacheable: Request should be cacheable as and when required. Client can cache the response using HTTP cache control headers. In headers we can specify the expiry time for each response. Also you can specify which request not to cache.
  The common Header Elements that can be used to control the caching are:
  1. Date - Finding out when this resource was generated
  2. Last Modified - Date and time when the server modified the resource/data
  3. Cache-Control - HTTP 1.1 header used to control caching, can contain directives
  4. Expires - Expiry date
  5. Age - Duration since the resource was fetched from server
  6. Cache-Control - Values can be tweaked to control if a cached result is still valid or stale.

Best Practices for Using REST Services:

  •  Provide Sensible Resource Names:
For example:
.....springservice?service=findCuntry&countryCd=101   ( Bad design)
.....springservice/findCuntry/101   (Good to have like this)

  • Avoid providing any wired location:

For example:

  • Avoid overloading the response: 

Try providing the data which makes sense to the client. For the response which returns Collections should be supported with pagination, 'first', 'last', 'next' and 'prev' links. If possible try providing links in the response.

  • Fine Grained Resources:

Instead of providing huge data with full complexity, try rolling out small resources which makes sense and can be useful for the client. Also you can break the response in such a way that the output of one resource can become input for another resource. This will give flexibility to the client to scale the application in future.

  • Use proper HTTP method for CRUD functions:

GET for reading and PUT for insert/update etc.

Versioning in ReST:

Versioning the API is always very useful and recommended for any application. I consider it very important because of following reason:
  • If your services are going to be used by more than one client. Then it’s always better to go with Versioning.
  • If your service is going to have multiple response type. I.e. Some clients may want JSON output, some may be comfortable with XML response or some may be looking for simple objects. So versioning become very important in this kind of situations.
  • Even if you have only one client but based on their recruitment they may be calling your service differently. For example sometime they may pass only 10 parameters in input, and sometime they will pass 15 input parameters. It all depends on their business case. So we have to be careful while designing our services.
  • Sometimes versioning is required for validating/skipping some business scenarios based on clients. For example some clients will not be interested in validating Phone Number while some will be.

Now we have seen couple of reasons for maintaining version of an API. But how easy and how good it is to go for versioning. Versioning means the contract is going to be changed. So the behavior of the API is going to change. The impact will be huge. Because the new API has to be consumed all over again for the entire existing customer. Again if all the customers are not negotiated well they may go out of their way and choose some other API (which we do not want). Now some may suggest that we shall duplicate the API functionality and change the behavior of new API as per requirement. As a developer we have to maintain the same code base for two API, which is not good. Again it is difficult to maintain the changes for new developer. This will not be good if you want to cut multiple versions of the same service for different clients. 

So now what is the best solution to overcome this?

There may be plenty of ideas and implementation available for Versioning of API. Below are some of the famous best practices that could be used for Versioning: 

  • Use content-negotiating approach:

The headers in the Web Services are very powerful and will be very useful in this concept. It contains the attributes which will suffice our requirement. Also version information could be added in headers. For example:
Request from Client goes like this:
GET /country/101 HTTP/1.1
Accept: application/com.springproject.country-v1+json

Response from Server will come as follows:
HTTP/1.1 200 OK
Content-Type: application/com.springproject.country.response-v1+json

{"countryCd":"101",
"countryName":"UAE"
}

Here if you see we are doing two thing, first is version number second is response type (its JSON in this case, you change it to XML or any other format).

  • Using URL for versioning:

Provide different URL for different versions of the services. For example:

First version of service has following URL
https://www.springproject.webservice/v1/findCountry/101

Now next version of the above service could be accessed using:
https://www.springproject.webservice/v2/findCountry/101


Each of the above implementation has its own advantage and disadvantages. It completely depend on the Architecture team to decide the better approach. There may be some other approaches


Happy reading ReST !!!!  Hope you enjoyed :) 

Comments

Popular posts from this blog

Know your Repository Statistics

Being in software development, everyone of us must be using some or the other repository to save our work( popularly know as check-in check-out :) ). Recently while working on one of my project I thought of finding out the statistics of our project repository for some management reports. While there are so many tools available in the market to explore the stats, I chose to go with Tortoise SVN tool with some plugins. Following are other tools that can be very useful based on scenarios: -Commit Monitor -Winmerge -Visual SVN -SVN Monitor -CM Synergy from Telelogic -Many more are there If you are using Tortoise SVN and want to know the details(for example : no of java classes checked-in, lines of codes written, developers name, total code base details and many more ) about your repository You can use the following steps to find the details: 1-check if the SVN has been installed and working properly or not by using following command: C:\>svn help It will output something ...

Testing your Webservice Applications using SOAP UI

SOAP UI is a standard desktop application for testing the Web Services projects. It provides full support for debugging, developing and testing of your web services applications. The tool support data driven development and also provides platform for creating test suites where you can create services for regression testing. For example if you want to test the complete flow of your SOA application, you can create Test Suites using SOAP UI and can perform end to end testing of your applications. The test suits can be configured to run in multiple environments (dev, sit, uat or production). Okay, let’s start the working on SOAPUI. I will show you the simple webservice testing that I developed in my last blog. Prerequisites: -You have developed your webservices -Webservice is ready and running on your local server -Installed SOAP UI tool Step-1 Download the SOAPUI tool Step-2 Open the soap UI Tool Setp-3 Right click on the project and choose New SOAP Pro...

It's All Mobile

In the digital era, where anything is available on finger tip and we want everything in our pocket, It will not be wrong to say that mobile devices have become our life line. These devices are impacting our lives on a daily basis. Today we have an app(as the modern world calls it) for everything. You name an application, its there on app store/play store. For any company(small or big), having a mobile application can be a smart way to connect with people and get started with their business very quickly.  I can say it has become a must first step for businesses to have mobile presence if they want to reach out to their customers easily and on time. This is high time for them to get their feet wet and jump into this App world. Today's world of technical innovation is taking business owners closer to their customers and giving them opportunity to know the customers need. This can be a good way to understand your customer instead of solving their problem. Demand for mobile software a...