Swami goes Techie

Here i would share my insights on technologies.

Sunday, August 30, 2009

RESTful implementation using .Net

Need REST from SOAP

Yes, we are tried of using SOAP and badly in need of REST;  Till date we would have mostly come across web services being implemented using SOAP (Simple Object Access Protocol) as messaging protocol for exchanging structured information (XML was chosen as the standard message structure) over HTTP (transporting medium). Though it has its own advantages, may get cumbersome due to its verbose XML format by adding soap headers and other meta-datas, thereby making it slower and also failing to utilize the power of HTTP to the fullest.

Lets REST

REST (Representational State Transfer Protocol) on the other hand defines identifiable resources (URIs - uniform Resource Identifiers), and methods for accessing and manipulating the state of those resources (HTTP verbs). Resources are like objects, they clearly differentiate each state very similar as in OOPs where each real-world entity is identified as an object having their own state (method) and attributes (properties).Resources can be identified using a single identifier scheme, typically a URL or URI. Once you have a handle/access to the resource, you can invoke methods (any http verb) and interact with it.

Few HTTP verbs,

  • GET: retrieve resource
  • POST: process resource
  • PUT: update resource representation
  • DELETE: delete resource

REST requests are modeled after the way a web browser (client) sends requests to a web server, typically a request for the REST services mostly goes in through url with query strings or in POST data block.

Typical REST request

A typical REST request for calling a web method GetInfo which takes integer ‘empid’ as the parameter will look similar to

http://domain.com/employeeprofile/GetInfo?empid=1

Each request starts with the hostname

http://domain.com

After the hostname is the service name

/employeeprofile/

Next is the method name followed by a question mark (?), followed by the actual query parameters, which take the form argument=value, where the arguments and values can be URL encoded if required. Multiple parameters are separated by an ampersand (&).

GetInfo?empid=1

Note:  

1. Method name is case sensitive

2. The order of method parameters is irrelevant and names are case insensitive.

3. If a web method takes some complex parameters, for e.g.) like array,

Public void SetNames(String [] empNames)

Then at the client program while calling the method, we pass the values as

http://localhost:3578/Service1.asmx/GetEmpInfo?empNames=Sethu&empNames=Ram&empNames=Kumar.

The REST service is intelligent enough to group up the query string params with name empNames into a string[] of empNames.

REST Implementation

In order make the .Net web service application to work as Restful services,

1. We need to configure web config file to add the required HTTP verbs.

<system.web>

    <webServices>

      <protocols>

        <add name="HttpGet"/>

        <add name="HttpPost"/>

      </protocols>

    </webServices>

</system.web>

2. Then we can go ahead and create normal web methods using c# .Net web service application as we do earlier.

[WebMethod]

public EmployeeList GetEmpInfo(int empid)

Input:

            empid: required integer paramter.

            If  empid = 0, then it will return the details of all the employees of domain(some x company).

            If  empid is any valid id number of the employee it would return his/her corresponding details.

Output schema:

EmployeeList: It’s basically a serialized list of employee object. (NAME and ID)

<Employees>

<Employee>

  <NAME>Anand</NAME>

  <ID>1</ID>

</Employee>

<Employee>

  <NAME>Abhishek</NAME>

  <ID>2</ID>

</Employee>

<Employee>

  <NAME>Jyothi</NAME>

  <ID>3</ID>

</Employee>

<Employee>

  <NAME>Sethuram</NAME>

  <ID>4</ID>

</Employee>

<Employees>

3. When it comes to accessing these web methods, its not require to create a proxy or stub at the consuming client. We can invoke the web methods using simple HttpWebRequest and HttpWebResponse objects and call the required service url along with parameters as below,

< http://localhost:3578/Service1.asmx/GetEmpInfo?empid=4>

string result = string.Empty;

string url = "http://localhost:3578/Service1.asmx/GetEmpInfo?empid=4";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

request.Method = "GET";

using(HttpWebResponse response = HttpWebResponse)request.GetResponse())

{

using (Stream responseStream = response.GetResponseStream())

                  {

using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))

                        {

                        XmlDocument xmlDocument = new XmlDocument();

                        xmlDocument.LoadXml(readStream.ReadToEnd());

                        }

                  }

}

Once we get the response output xml schema, we can load it either in XML DOM or parse it through a reader object.

REST Advantages

  • Human readable formats and results.
  • They are stateless.
  • Light weight as purely http.
  • No security issues with firewalls
  • Relative ease and quick to develop.

Companies using REST

  • Yahoo! - All Yahoo API's Web Services uses REST including Flickr etc
  • Google - Google Adsense Search and Google Maps are two good examples for RESTful services implemented by Google
  • Amazon
  • EBay
  • del.ico.us

I am sure this list to going to grow exponentially due to its simplicity to develop and ease of use.

Rest of REST in Rest

I hope I have thrown a bit of light on the RESTful design concepts. (I am sure REST will have a greater impact on the future of the World Wide Web). Here in this post, I have just briefed on the fundamentals of RESTful service, may be I can elaborate on the rest of RESTful design concepts in the rest of my blog posts to follow.

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home