5 Simple Steps to Create Your First RESTful Service

RESTful services are those that follow the Representational State Transfer (REST) architectural style.

Before implementing your first RESTful service, let's first understand the concept behind it. As we know, WCF allows us to make calls and exchange messages using SOAP over a variety of protocols, In other words HTTP, TCP, Named Pipes and MSMQ and so on. When we are using SOAP over HTTP, we are just utilizing HTTP as a transport. But HTTP is much more than just a transport. So, when we talk about REST architectural style, it dictates that "Instead of using complex mechanisms like CORBA, RPC or SOAP for communication, simply HTTP should be used for making calls".

RESTful architecture uses HTTP for all Read/Create/Update/Delete (CRUD) operations using simple HTTP verbs (like GET, POST, PUT, and DELETE). It's simple as well as lightweight. For the sake of simplicity, I am implementing only a GET request for which the service will return certain types of data (in other words Product data) in XML format.

The following procedure is the 5 simple steps to create your first RESTful service that returns data in XML.

  • Create a WCF Service Project.
  • Preparing the data (for example Product) to return.
  • Creating Service Contract
  • Implementing Service.
  • Configure Service and Behavior

Create a WCF Service Project

  • Open Visual Studio.
  • From "File" > "New Project" select WCF from the left and create a new WCF Service Application.

    1. Image.jpg

Preparing the data to return

Now add a class to the new project. Name it Products.cs.

2.1 Image.jpg

2.2 Image.jpg

Now this Products.cs file will contain two things. The first one is the Data Contract.

[DataContract]
public class Product
{
      [
DataMember]
      
public int ProductId { get; set; } 
      
      [
DataMember]
      
public string Name { get; set; }
      
      [
DataMember]
      
public string CategoryName { get; set; } 
      
      [
DataMember]
      
public int Price { get; set; }
}

The second one is a singleton implemented class that gets products data from a database and returns a list of products. In order to make it simple, we are preparing data inside this class instead of fetching from the database as follows:

public partial class Products
{
   
private static readonly Products _instance = new Products();
   
private Products() { }
   
public static Products Instance
    {
       
get { return _instance; }
    } 
   
public List<Product> ProductList
    {
       
get { return products; }
    } 
   
private List<Product> products = new List<Product>()
    {
        new Product() { ProductId = 1, Name = "Product 1", CategoryName = "Category 1", Price=10}, new Product() { ProductId = 1, Name = "Product 2", CategoryName = "Category 2", Price=5},
        new Product() { ProductId = 1, Name = "Product 3", CategoryName = "Category 3", Price=15}, new Product() { ProductId = 1, Name = "Product 4", CategoryName = "Category 1", Price=9}
    };
}

Creating Service Contract

Now add a new WCF Service to this project as follows:

3. Image.jpg

It will add a contract as well as service file to the project. The following is the code for the service contract, in other words IProductRESTService.cs.

public interface IProductRESTService
{
    [
OperationContract]
    [
WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml,
    BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetProductList/")]
   
List<Product> GetProductList();
}

IProductRESTService contains only one method, in other words GetProductList. The important points to understand about this method is the WebInvoke attribute parameters.

  • Method = "GET", represents an HTTP GET request.
  • ResponseFormat = WebMessageFormat.Xml, the response format will be XML here but we can return JSON as well by changing its value to WebMessageFormat.json.
  • BodyStyle = WebMessageBodyStyle.Wrapped, indicates that both the request and response are wrapped.
  • UriTemplate = "GetProductList/", it has two parts, URL path and query.

Don't forget to add "using System.ServiceModel.Web" at the top.

Implementing RESTful Service

In this step we will implement the service. Only one method GetProductList is defined in the contract, so implementing the service class will be as follows:

public class ProductRESTService : IProductRESTService
{
   
public List<Product> GetProductList()
    {
       
return Products.Instance.ProductList;
    }
}

Configure Service and Behavior

The last step is to configure the service and its behaviors using the configuration file. The following is the complete ServiceModel configuration settings.

<system.serviceModel>
       <
services>
             <
service name="MyRESTService.ProductRESTService" behaviorConfiguration="serviceBehavior">
                    <
endpoint address=""
                    binding="webHttpBinding"
                    contract="MyRESTService.IProductRESTService" behaviorConfiguration="web">
                    </
endpoint>
             </
service>
       </
services>
       <
behaviors>
             <
serviceBehaviors>
                    <
behavior name="serviceBehavior">
                           <
serviceMetadata httpGetEnabled="true"/>
                           <
serviceDebug includeExceptionDetailInFaults="false"/>
                    </
behavior>
             </
serviceBehaviors>
             <
endpointBehaviors>
                    <
behavior name="web">
                           <
webHttp/>
                    </
behavior>
             </
endpointBehaviors>
       </
behaviors>
       <
serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>


webHTTPBinding is the binding used for RESTful services.

Now, everything about creating the RESTful service is done. You can easily run and test it.

Right-click the ProductRESTService.svc file and click "View in Browser". You will see the following screen, that means the service is fine.

4. ServiceRunning.jpg

Just modify the URL in the browser and add "GetProductList/" to it. So, this is the UriTemplete we defined as a service contract method.

5. Result.jpg

Hopefully, this simple WCF tutorial will be helpful for the readers. To keep the things simple, I restrict it to just getting records using the HTTP GET verb. In my future article, I'll provide all Create, Read, Update, Delete (CRUD) operations using a RESTful service.


Similar Articles