5 simple steps to create your first RESTful service

By | September 22, 2013

RESTful services are those which follow the REST (Representational State Transfer) architectural style. Before implementing your first RESTful service, lets first understand the concept behind it. As we know that WCF allows us to make calls and exchange messages using SOAP over a variety of protocols i.e. HTTP, TCP, Named Pipes and MSMQ etc. In a scenario, if 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”.


::::: Practical Guide To WCF RESTful Service :::::


WCF RESTful ServiceRESTful architecture use HTTP for all CRUD operations like (Read/Create/Update/Delete) using simple HTTP verbs like (GET, POST, PUT, and DELETE).It’s simple as well as lightweight. For the sake of simplicity, I am going to implement only a GET request for which service will return certain types of data (i.e. Product data) in XML format.


MCSD Exam: 70-487

Following are 5 simple steps to create your first RESTful service that returns data in XML.

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

You can download the complete source code for this article here.

1. Create a WCF Service Project

  •  Open Visual Studio.
  •  From File -> New Project.  Select WCF from left and create a new WCF Service Application.WCF Service Application

2. Preparing the data to return

  • Now add a class to newly created project. Name it to Products.cs.Prepare Data For WCF Service
    WCF Products Class
Now this Products.cs file will contain two things.First one is Data Contract as follows:WCF Data Contract
Second one is a singleton implemented class that gets products data from a database and return list of products. In order to make it simple, we are preparing data inside this class instead of fetching from the database as follows:Product Singleton for RESTful Service

3. Creating Service Contract

Now add a new WCF Service to this project as follows:WCF Service Contract
It will add contract as well as service file to project. Following is the code for service contract i.e. IProductRESTService.cs.RESTful Service Contract

IProductRESTService contains only one method i.e. GetProductList. Important points to understand about this method is WebInvoke attribute parameters.

  • Method = “GET”, represents an HTTP GET request.
  • ResponseFormat = WebMessageFormat.Xml, response format will be XML here but we can return JSON as well by changing its value to WebMessageFormat.json.
  • BodyStyle = WebMessageBodyStyle.Bare, indicates neither the request and nor response are wrapped. Other possible values for BodyStyle are Wrapped, WrappedRequest, WrappedResponse.
  • UriTemplate = “GetProductList/”, it has two parts, URL path and query.

Don’t forget to add using System.ServiceModel.Web at top.

4. Implementing RESTful Service
In this step we are going to implement the service. Only one method GetProductList is defined in the contract, so implementing service class will be as follows:RESTful Service Implementation

5. Configure Service and Behavior
The last step is to configure the service and its behaviors using the configuration file. 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 RESTful service is done. You can easily run and test it.
 

Right click ProductRESTService.svc file and click “View in Browser“. You will see the following screen, that means service is fine.Running RESTful WCF Service

An important point to consider here is that in Service Behavior Configuration, we have setted httpGetEnabled=”true” for serviceMetadata that’s why we are getting above service screen with wsdl option.

WSDL for RESTful ServiceThis is what we do normally for SOAP-based services. REST-based services only uses HTTP verbs on a resource, so we can disable WSDL in this case by simply setting httpGetEnabled=”false”. Now if we run the service again, we will get the following screen.WCF REST Service Output

Just modify the URL in browser and add “GetProductList/” to it. So, this is the UriTemplete we defined as service contract method.Fetching Data from WCF REST
Hopefully, this simple WCF tutorial will be helpful for the readers. To keep the things simple, I restrict it to just getting records using HTTP GET verb. But you can find a complete implementation for all CRUD (Create, Read, Update, Delete) operations using RESTful service in another WCF RESTful Service tutorial here.

Download Complete Source Code for this WCF Service Tutorial


Other Related Articles:

Top 10 Interview Questions and Answers Series:

Category: Uncategorized Tags:

About IMRAN ABDUL GHANI

Imran Abdul Ghani is working as Software Developer(Senior) with extensive knowledge in Web development technologies especially C#, ASP.NET, MVC, WCF, Web API, ADO.NET Entity Framework, jQuery etc. He has several years of experience in designing/developing enterprise level applications. He is Microsoft Certified Solution Developer for .NET (MCSD.NET) since 2005. You can reach his blogging at www.webdevelopmenthelp.net, www.topwcftutorials.net, and www.sharepointfordummies.net.

37 thoughts on “5 simple steps to create your first RESTful service

  1. Prashant Jagdale

    public static string PostServiceRequest(string url, string JSONFilter)
    {
    string result = string.Empty;
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = “text/json”;
    httpWebRequest.Method = “POST”;

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
    streamWriter.Write(JSONFilter);
    streamWriter.Flush();
    streamWriter.Close();
    }
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
    result = streamReader.ReadToEnd();
    }
    return result;
    }

  2. neo

    Thanks for this Tutorial , how can i pass a parameter before i can get the data in this tutoral and how can i make my Restful WCF Service

  3. Sami Akram

    Explaination is good here too, but Code at this link works fine with same easy steps as here but with working result

  4. jj

    Why does my REST service created throught this method has a wsdl ? I was under the impression that RESt services wouldnt have a wsdl . The Url for REST works fine and I’m able to see the XML output . Yet when i put the url with ?wsdl it shows up ….

  5. jrobinson6274

    Running into a problem with:

    public List ProductList

    The error states: Using the generic type ‘System.Collections.Generic.List’ requires 1 Type argument.

    1. WebdevTutorial

      Hi jrobinson,
      I have updated this WCF Tutorial to resolve the issue for certain versions. You can follow the steps to have a clean implementation for WCF RESTful service.

      Hopefully, I’ll upload source code for the implementation shortly, so you will have a Visual Studio solution with complete source of the project.

      Thanks for your valuable feedback.
      Regards,
      Imran

  6. Suganth

    how can i do this using xml data, pls help me

    1. WebdevTutorial

      Can you please elaborate your question? As it’s already using xml as response to render XML data.

      Please see the service contract as:

      ResponseFormat = WebMessageFormat.Xml

      1. Suganth

        Yes, How can i pass the xml data to service in PUT or POST Method which means RequestFormat = WebMessageFormat.Xml

        I know how to call the service using jquery ajax call and pass the json datas, but don’t know how to pass the xml values.

        Is it possible to pass the xml datas to service using jquery or any other language should i use ?

        1. WebdevTutorial

          yes it’s possible with following piece of sample code.

          ———————————————————
          string postData = SampleXml.ToString();

          // convert xmlstring to byte using ascii encoding
          byte[] data = encoding.GetBytes(postData);

          // declare httpwebrequet wrt url defined above
          HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);

          // set method as post
          webrequest.Method = “POST”;

          // set content type
          webrequest.ContentType = “application/x-www-form-urlencoded”;

          // set content length
          webrequest.ContentLength = data.Length;

          // get stream data out of webrequest object
          Stream newStream = webrequest.GetRequestStream();
          newStream.Write(data, 0, data.Length);
          newStream.Close();

          // declare & read response from service
          HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
          ——————————————————–

          This answer is available at following URL.
          http://stackoverflow.com/questions/19906692/how-to-send-xml-via-post-with-wcf

          1. Suganth

            Thank you for your valuable answer, i have already tried this code, but still i m getting 400 bad request error..

  7. bryan

    this dont work

    public List ProductList
    {
    get { return products; }
    }

    1. jrobinson6274

      Hi Bryan,

      Was this question answered?

  8. anil

    Give me one more table class like Order,
    Combining both Products and Orders classes data want to get,
    How can i do?
    please give that example

    1. WebdevTutorial

      Dear Anil,
      I’ll do the above mentioned in later tutorial here. We come up with a complete example. Please revisit or just register by email.

    2. Najam Khan

      Create a class as below format:
      public class PostAlbumListRequest
      {
      public List Album { get; set; }
      public User User { get; set; }
      public string UserToken { get; set; }

      }

      [OperationContract]
      [WebInvoke(Method = “POST”, UriTemplate = “PostAlbum”,
      RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
      PostAlbumResponse PostAlbum(PostAlbumRequest request);

      var album = {
      AlbumName: “PowerAge”,
      Entered: “1/1/1977”
      }
      var user = {
      Name: “Rick”
      }
      var userToken = “sekkritt”;

      $.ajax(
      {
      url: “http://localhost/Rest/RestServiceImpl.svc/PostAlbum”,
      type: “POST”,
      contentType: “application/json”,
      data: JSON.stringify({ Album: album, User: user, UserToken: userToken }),
      success: function (result) {
      alert(result.Result);
      }
      });

  9. Howard Payne

    Hi,

    Using VS 2013 Express
    Created WCF Service Application project
    Works great…

    thanks

  10. WebdevTutorial

    Let me clear one thing as I mentioned in post step 1. You will create a new project using template “WCF Service Application”. Later in Step 3, you right click your project and add a new “WCF Service” to it.

  11. David Gray

    Hi,
    I’m using VS2012. The WCF tab when creating a new project has; WCF Service Library, WCF Service application, WCF workflow service application & sysndication service libray.

    This is using the .net framework 4.

  12. WebdevTutorial

    David,
    WCF Service or WCF Service Application template are available. I am not sure which version of Visual Studio you are using…

  13. Anonymous

    The code is missing
    [ServiceContract] attribute
    public interface IProductRESTService { [OperationContract

    1. imranghani

      Dear,
      Please verify you follow the step 5. Please confirm following in your configuration file.
      serviceMetadata httpGetEnabled=”true”

    1. Anonymous

      i agree that web api is easier but this can be helpful if your org dont have enough fundings to upgrade to iis 7 or iis 8.

Comments are closed.