Rest Based API Using WCF Services

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

What REST is

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 architectural style, that 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 done with the use of HTTP verbs like GET, POST and so on. The data transfer is done using either XML or JSON format, that makes it easier to use with other platforms like Java, PHP and so on. It also consumes less network bandwidth, since it does not involve the 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, that provides live cricket match scores (just an example), hosted at the URL like http:\\www.abc.com\scoreservice.asmx. If we were to use this service in our application then we would simply add a reference for this service URL to our application, create a proxy object and call a method using the proxy object, to get the score, say GetScore().

The same can be done using a 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 following:

http:\\www.abc.com\scoresservice.svc\GetScore

Where GetScore is the name of the method that 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 the name of the method to be used, the parameters it expects, or type of format in which it returns the result and so on. Similarly, we can have a method where we can submit the data using HTTP POST.

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

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

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

Why to use REST

There are various reasons for REST-based APIs. Nowadays, nearly 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 do the same thing. So to cater to the needs of all the systems with a single component, we may require to create various 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 kinds of problems can be easily avoided using REST based architecture.

Another big advantage these services provide is that they consume less network bandwidth, since they use a XML and JSON based format for data transfer. Use of SOAP based services involve overhead of headers, a SOAP body and so on. And finally, they can be easily accessed by directly sending URL based requests.

Creating a REST based WCF API

To start with, create a new project and add a WCF service to 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 the other GetAllProducts. As their names suggest itself, one will return the details of a specific Product and the other will return a list of all the Products. So our initial setup becomes:



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



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

STEP 1: Configure Service methods

In order to expose our methods as an API, we need to set a 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 and WebGet

For each method to be available in the REST API, we need to add either the WebInvoke or WebGet attribute to it. An operation that involves fetching data from the API and that uses WebGet and any operation, where we need to send data to the server for some processing, like create, update and so on, uses the WebInvoke attribute. To a certain extent, these two attributes decide whether the method can be accessed via HTTP using GET, PUT, POST and so on. But still we need to set the Method parameters to these, that is explained next.

2. Method parameter

After adding the preceding attributes, we need to specify the HTTP verb that can be used with it. For example, if we add a WebGet attribute on a method, then the HTTP GET verb is added, and if WebInvoke is used then we need to add verbs like POST, PUT, DELETE and so on. 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 and so on.

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 returned 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 a REST based API involves making calls to URLs, we need to specify a kind of template URL for each method that will represent that method, as a resource to the URL that is being requested by the browser. The client will make a 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 an appropriate method will be invoked.

For example, a URI template like "GetProduct/{productId}" is added to a WCF method. The client will make a 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 various methods and will then invoke the appropriate method.

So after applying the preceding parameters, our methods will look like :



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 to our configuration settings in the web.config of our application.

1. Endpoint binding type

WCF services have various binding types for the various purposes they can do. To use this service as a REST based API, it uses webHttpBinding. So we will need to change the binding of the endpoint to webHttpBinding.

2. Endpoint behavior

Next we need to add a behavior of type <webHttp /> in the <endpointBehaviors> tag. This allows our endpoint to behave like an API and client code then makes 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 the above step. See the code below.



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, that was added in Step 1. Now press Enter and see the results.



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


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

To test this servicee, we will add a HTML page to the same application and use jQuery to make calls to this service. The URL, to which we need to make calls, will be the 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.



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 that 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 stating that the World Wide Web can be considered to be based on the REST architecture. The reason being, every resource request is done using a direct URL class and HTTP protocol and when the resource is requested by the browser, it actually involves the use of the HTTP verbs like GET, POST and so on for communication with the remote server.

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

Up Next
    Ebook Download
    View all
    Learn
    View all