REST based API using WCF Services


Windows Communication Foundation, code named Indigo, was introduced in .NET framework 3.0. It provides features capable to handle the need of .NET Remoting , Web services, MSMQ etc, all in a single platform. Apart from these features, they provide a strong feature to create a REST based API.  Our main aim of this article will be to create a REST based service using WCF services.

What is REST ?

REST stands for REpresentational State Transfer. REST was first introduced and defined in 2000 by Roy Fielding at the University of California, Irvine, in his academic dissertation, “Architectural Styles and the Design of Network-based Software Architectures”.

REST is usually defined as a type of architecture style, which uses HTTP for communication between client and server. All the communication in a rest based api uses HTTP for sending and receiving data from the server. This is achieved with the use of http verbs like GET, POST etc. The data transfer is done using either XML or json format, which makes it easier to use with other platforms like JAVA, php etc. and also it consumes less network bandwidth, since it does not involves overhead of creating any type of metadata like header or envelope.

To understand the concept of REST, let’s take an example of a Web service, which provides LIVE cricket match scores(just an example), hosted at url like http:\\www.abc.com\scoreservice.asmx. If we were to use this service in our application, we would simply add a reference of this service url in our application, create a proxy object and call a method using the proxy object, to get the score, say GetScore().

Same goal can be achieved by using REST based service, where the user will not be required to create any proxy object, and not even add a reference to the service in his application. Our application will make a hit to a url like the follow http:\\www.abc.com\scoresservice.svc\GetScore, where GetScore is the name of the method which we want to call and get the data. In this case, our application needs to know about the location url where our service is located along with details like name of the method to be used, the parameters it expects, or type of format in which it returns the result etc. Similarly, we can have a method where we can submit the data using http POST.

This is the concept of REST architecture based api’s. There is a very good point that is used in relation to this architecture. It says :

Since World Wide Web itself is also based on HTTP, it can be viewed as a REST-based architecture.

After our discussion is complete, you will be able to relate this point to the REST architecture.

Why use REST ?

There are various reasons why REST based api’s. Nowadays, almost every application that we create, is required to be accessed by  mobile devices or .NET, JAVA and PHP based applications. Some of the applications may use .NET remoting, others may use SOAP based web services and so on, to achieve the same goal. So in order to cater the needs of all the systems with a single component, we may require to create different versions of it. Moreover, if a new system requires access to the api, our existing api system may again require changes or may not even work with it. These kind of problems can be easily avoided by use of REST based architecture.

Another big advantage these services provide is that they consume less network bandwidth, as they use xml and json based format for data transfer. Use of SOAP based services involve overhead of headers, soap body etc. And finally, can be easily accessed by directly sending url based requests.

Creating REST based WCF api 

To start with, Create a new project and add a WCF service in it. On adding this service, it will add a default interface and its concrete implementation class. We will rename it to ProductsService.svc and will remove the default methods and add two methods, one named GetProduct and other as GetAllProducts. As there names suggest itself, one will return details of a specific Product and other will return a list of all the Products. So our initial setup becomes like :

REST_WCF_1

Next, we add the concrete implementations of the methods we created above.

REST_WCF_7

These steps were nothing but simply creating methods, that we might have used on click of a button. But instead of creating them in a class library, we are adding them into a WCF service classes. Now that we have specified the methods that we want to use through the service, its time to configure our service and its methods, to make it a REST based api. We will divide this process in 2 steps

STEP 1 – Configure Service methods :

In order to expose our methods as an api, we need to set few parameters/attributes for these methods. It involves decorating our service methods with WebInvoke or WebGet attributes and add some properties to these attributes.

1. WebInvoke & WebGet : For each method that we would like to be available in the REST api, we need to add either WebInvoke or WebGet attribute to it. An operation, which involves fetching data from the api, use WebGet and any operation, where we need to send data to server for some processing, like create, update etc, use WebInvoke attribute. To a certain extent, these two attributes decide whether the method can be accessed via http using GET, PUT, POST etc. But still we need to set the Method parameters to these, which is discussed next.

2. Method parameter : After adding the above attributes, we need to specify the http verb which can be used with it. For example, if we add WebGet attribute on a method, then http GET verb is added, and if WebInvoke is used, we need to add verbs like POST, PUT, DELETE etc. An important point to note is that WebInvoke can be used for http GET, by explicitly specifying the Method as GET, but WebGet can only be used for GET and not for POST, PUT, DELETE etc. 

3. ResponseFormat parameter : This parameter is added to the WebGet and WebInvoke attributes. As the name suggests itself, it specifies the format in which the result will be sent back to the client. It can be either JSON or XML based only. By default, the response will be sent in XML based format.

4. UriTemplate parameter : Since REST based api involves making calls to urls, we need to specify a kind of template url for each method, which will represent that method, as a resource to the url which is being requested by browser. Client will make request to the method by keeping in mind the template defined for the method and add actual values to the template url. When this request is received in WCF, the url sent by the client browser will be mapped to the URI templates of the methods and appropriate method will be invoked.

For ex, a uri template like “GetProduct/{productId}” is added to a wcf method. Client will make REST based call like

http://abc.com/ProductsService.svc/GetProduct/231

Here, GetProduct  is a method name and 231 is a parameter passed to it. Now, when this call is received by WCF, it will try to match the url with the templates defined on different methods and will then invoke the appropriate method.

So  after applying these above parameters, our methods will look like :

REST_WCF_3

Step 2 – Configure service endpoint :

Next we need to configure our WCF service endpoint to support calls to these methods as a REST api. For this, we need to make changes in our configuration settings in the web.config of our application.

1. Endpoint binding type : WCF services have different binding types for different purposes they can achieve. In order use this service as a REST based api, it uses webHttpBinding. So we will have to change the binding of the endpoint to webHttpBinding.

2. Endpoint behavior : Next we need to add a behavior of type <webHttp /> in <endpointBehaviors> tag. This allows our endpoint to behave like an api and client code then make direct calls to the api like accessing a url. To link this behavior with the endpoint, we add a name attribute for this behavior and set behaviorConfiguration equal to this name, in the endpoint tag, that we configured in above step. See the code below.

REST_WCF_4

Now our service is ready to use. Right click on ProductsService.svc and select View in Browser. In the URL, append the GetProducts. This is to map our browser url to the URI template defined for this method, which added in step 1. Now press enter and see the results.

REST_WCF_5

Since we defined json as ResponseFormat, it returns the data in json format. For the same method, change response format to XML, re-build and browse the url again. This time, the results will be in XML format.
REST_WCF_6

Similarly, we can call the GetProduct method. This service can be now hosted using different hosting methods available for the these services.

To test this servicee, we will add a HTML page in the same application and use jquery to make calls to this service. The url, to which we need to make calls, will be service location in the same application. We will append the application root url with service name and then method name, to match it to the url template that identifies this method in wcf. The result can be then iterated and used as per requirements, after fetching.

REST_WCF_8

So here we simply make a url based call to the service running on a localhost. We append the name of the method to the service location, which matches a template uri defined for a method in the service. In our case, it is the GetAllProducts. So this method from the service is invoked and data is then returned to the client in the variable named data.

At the start of the article, we quoted a point that world wide web can be considered as based on REST architecture. The reason being, every resource request is done using direct url calss & http protocol and when the resource is requested by the browser, it actually involves the use of the http verbs like GET, POST etc for communication with remote server.

So this was about how we can use a WCF service as a REST based API. Hope you enjoyed reading it…!!!

Advertisements

About Jasminder

.Net developer and blogger by profession, keen to learn new technologies, love nature, music and cricket.
This entry was posted in WCF Services. Bookmark the permalink.

One Response to REST based API using WCF Services

  1. Jaskirat singh says:

    Thanks jas for this awesome explanation . Now at last after so many rnd I got to know the exact meaning of rest api. Well done brother.

I have a suggestion..

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s