Posts Tagged ‘REST’


Posted: December 14, 2008 in WCF, WebService
Tags: , ,

For the past few years we have seen the growing popularity of blogs,wiki,social networking sites as a part of the Web 2.0 paradigm.Most of these sites are exposing API or services which are accessible over web to enhance the level of collaboration.From technical perspective these APIs are of two types:

  1. Services complying to the WS-* protocols exchanging data as XML based SOAP format.
  2. Simple HTTP APIs exchanging data in POX(Plain Old XML)/JSON(JavaScript Object Notation) format.

The WS-* protocols and SOAP has evolved as part of SOA where the main goal was to achieve a platform/vendor neutral mechanism of distributed computing organizing the architecture around the concept of service.

With advent of Web 2.0 the second category of services I mentioned above are growing in popularity because of their lightweight nature and ease of use.Whenever I discuss about this kind of services with my friends they refer to the term RESTful services.This I feel is not correct.All HTTP based services that does not use SOAP should not be referred to as RESTful.A service is RESTful or not depends upon how you conceptualise the design of the service rather than what technology or data format you use.This is what I would like to substantiate in this post.To make this difference clear and crisp I need to discuss about REST first.


Why we call Intenet as WorldWideWeb?.This is because it is a web of linked resources,we request for a particular resource and what we get is a representation of that resource.This representation may contain a link to another resource and thus we navigate from one resource to another.This is the basic concept of REST.REST is how the WWW actually works.

The term REST (Representation State Transfer) was coined by Roy T Fielding in his PhD dissertation paper entitled “Architectural Styles and the Design of Network-based Software Architecture”. There he described REST as

“Representational State Transfer (REST) architectural style for distributed hypermedia systems, ..”

So REST is the architectural style around which WWW is built.

The key constraints of REST are

  1. Client & Server – This separates the UI from data processing and storage.
  2. Stateless – This implies that each client request must contain all necessary information to process the request.No state is maintained by the server.This improves reliability as state of a request is not preserved and hence no need to recover in case of failure.This improves scalability taking away overhead of state management from server.
  3. Cached – Response for a particular request can be identified as cacheable or non-cacheable.If it is cacheable then client can reuse the response to the same request.This improves efficiency.
  4. Layered – This allows the system to be decomposed into hierarchy of layers where each layer depends on the service provided by the layers below and provides some service to the layers above in the hierarchy.This helps to reduce system complexity but adds to latency which can be balanced by caching.
  5. Uniform Interface – This implies loose coupling between services provided and their implementations so that they can evolve independently of each other.

Resource is the major abstraction in REST.A Resource can be document ,image or a service which is uniquely identified by it’s Uniform Resource Identifier(URI).Each resource has an associated sequence of bytes for it’s Representation and Representation Metadata describing the representation e.g. representation can be a document and it’s representation metadata might be content type of the document.

Now the obvious question how do we achieve the Uniform Interface?.This is provided by the Hypertext Transfer Protocol or HTTP.HTTP is the well established application level protocol for WWW and provides well defined operations and status codes.The listing below shows the HTTP methods and their correspondence with the CRUD operations.

Method Name Description CRUD operation
GET Retrieves representation of a resource READ
POST Submits data to be processed by a resource UPDATE
PUT Creates a new resource or representation CREATE
DELETE Deletes a resource DELETE

RESTful Services

So how do we apply REST in terms of services.REST defines the way we human beings interact with the Web so if we apply the same style in defining the way programs interact over the Web we will be able to design RESTful services.

Let us proceed with the design considering a web application exposing services to maintain personal contacts where list of contacts or a single contact can be retrieved,new contacts can be added,existing can be updated and deleted.

  • Identify the Resources – To identify the resources we need to focus on the entities in the problem domain i.e. Nouns.Here the two entities are
    • Contacts – All contacts
    • Contact  – Individual contact present in the list.This is a part of Contacts itself.
  • Design the URI
  • Map with CRUD operations as per requirement
HTTP Method URI Service Provided
GET View All Contacts
PUT Add new contact
GET Get details of contact with id=100
POST Update contact with id=100
DELETE Delete contact with id=100
  • The content type of the representation of these resources can be POX/JSON.

RPC Style Services

For the same application to design RPC style services the design approach will be different.We will be concentrating on the operations to be provided by the service i.e. actions or Verbs.

Differences Summary

  • RPC focuses on actions/verb while REST focuses on resources/entities/nouns.
  • RPC defines an custom interface with operations and REST defines a resource with URI and actions are defined by uniform interface of HTTP.

WCF Web Model – POX/JSON Support

Posted: October 28, 2008 in .NET, WCF
Tags: , , , ,

For the past few days I was studying the details of the Web Programming Model of WCF.This feature enables WCF services to be called using simple HTTP requests i.e. without the messages wrapped in SOAP format.The messages can be POX(Plain Old XML) or JSON(JavaScript Object Notation).So the client for this kind of services does not need any specific proxy or WSDL.But how client is made aware of the service metadata is still a question to me.However parking that question aside for now let us get into, step by step how this feature is built using the extensibility points provided by WCF infrastructure.

Client Side

Let us first think of what the client is going to send to the service?Just a HTTP request.The method may be GET or POST.Suppose I am trying to access a service operation Add(int i,int j) .The client code in C# will be something like as shown below:

HttpWebRequest  request =  HttpWebRequest.Create(http://localhost:9001/Test/Add/?i=1&j=1) as HttpWebRequest;
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
request.Method = “GET”;
request.ContentType = “text/xml”;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Before we proceed into the details of the service side let me note the down the questions that initially occurred to my mind.

  1. How the HTTP message will read and parsed in the service side?
  2. How from the URI the name of the method Add will be read and request will be dispatched to the correct operation?
  3. How the parameters will be parsed from the querystring?

In the subsequent sections I will try to answer these questions.

Service Side


In the server side there should be some program listening to a particular socket waiting for bytes to arrive.This is the job of the ChannelListener as I had discussed in one of my earlier posts titled ServiceHost & Channels.This ChannelListener should be able to read raw bytes and create channels to process the HTTP requests.But the channels are created by the specified binding.So we need a binding which can handle HTTP Transport and encode/decode POX and JSON messages.For this we have a binding provided by WCF called WebHttpBinding.This binding is primarily composed of HttpTransportBindingElement and WebMessageEncodingBindingElement.This WebMessageEncodingBindingElement inherits from TextMessageEncodingBindingElement and is a composite encoder which can handle plain text,XML,JSON and raw binary data.

So to make WCF Services available for basic HTTP clients we need to expose an endpoint with WebHttpBinding.


Now we have an service endpoint ,message is processed by channels created by WebHttpBinding and routed to the EndpointDispatcher via the ChannelDispatcher.But who reads the URI of the message and decides which service operation this is intended for?How the parameters values are parsed from the querystring?

The parsing of URI and determination of operation is done by public string SelectOperation( ref Message message ) method of a  WebHttpDispatchOperationSelector class implementing the IDispatchOperationSelector interface.

The querystring parsing and parameter processing is done by a dispatch formatter class implementing the IDispatchFormatter interface with methods:

void DeserializeRequest(Message message, object[] parameters)
Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)

How these two classes gets attached to the DispatchRuntime of the EndpointDispatcher.WCF allows to modify the behaviour of an endpoint using endpoint behaviours.The classes intending to so needs to implement the IEndpointBehavior interface.WCF provides WebHttpBehavior class for modifying the endpoint behavior to suit the needs of POX/JSON messages.This class has three methods to get the operation selector and formatters.

protected virtual WebHttpDispatchOperationSelector GetOperationSelector(ServiceEndpoint endpoint)
protected virtual IDispatchMessageFormatter GetReplyDispatchFormatter(OperationDescription operationDescription,ServiceEndpoint endpoint)
protected virtual IDispatchMessageFormatter GetRequestDispatchFormatter(OperationDescription operationDescription,ServiceEndpoint endpoint)

In the operation ApplyDispatchBehavior these components are added to the DispatchRuntime

public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher)

      endpointDispatcher.DispatchRuntime.OperationSelector = …

How the WebHttpBehavior is added to the ServiceEndPoint??


WCF provides a class called WebServiceHost to host services for web based clients send POX/JSON messages.This class inherits from the ServiceHost class.This class makes sure that WebHttpBinding is properly used and attaches the WebHttpBehavior to the ServiceEndPoint.

Now the last things that I need to mention is the two Operation Behavior attributes that need to be applied to the Service operations:WebInvokeAttribute and WebGetAttribute.These two attributes are passive operation behavior and adds some additional metadata to the operation description.This information is used by the WebHttpBehavior for processing.WebGetAttribute allows only HTTP GET requests whereas WebInvokeAttribute has one Method parameter.This parameter is set to POST by default and can accept GET and PUT as well.

The method signature of the Service operation will look something like:

int Add(int x, int y);

We have covered almost the entire flow of POX/JSON messages from client to service.

In the next post I will discuss how to extend this framework and plug in custom functionalities…