Wednesday, March 2, 2011

Create REST service with WCF and Consume using jQuery

Shout it kick it on DotNetKicks.com
Code
What is REST ?
Rest=Representational state transfer which is an architecture design to represent the resources. Rest provide the uniform interface through additional constraints around how to identify resources, how to manipulate resources through representations, and how to include metadata that make messages self-describing.
Rest is not tied with any platform and technology but WEB is only platform which satisfy the all constrain. So any thing you build using Rest constrain, you do it on Web using HTTP.

Following are the HTTP methods which are use full when creating Rest Services.


HTTP Mehtods
  • GET - Requests a specific representation of a resource
  • PUT - Create or update a ersoure with the supplied representation
  • DELETE - Deletes the specified resource
  • POST - Submits data to be processed by the identified resource
  • HEAD - Similar to GET but only retrieves headers and not the body
  • OPTIONS - Returns the methods supported by the identified resource
In this article I am going discuss how to design and consume REST web service using WCF framework of .net service. As Example I am going to create  REST service which create, update and select Employee. Now start following the steps given below.

Designing of the URI
To designing Rest services you need to design URI, so for that you need to list out the resources that going to be exposed by the service.  As I am going to design Employee Create,updae and select service, so resource is
  • Employee
Now to be more specific towards the operation
  • List of Employees
  • A Employee by Id
  • Create Employee
  • Update Employee
  • Delete Employee
For example service is hosted on on local IIS server  and URL to locate it is
        http://localhost/restservices/MyRestServices.svc
In below discussion I am going to design the URL presentation for each operation
  • List  Employees 
         URL is to get list of all employee
               http://localhost/restservices/MyRestServices.svc/Employees
         But there are no. of Employee in system and to apply filter on Employees
              http://localhost/restservices/MyRestServices.svc/Employees?type = {type}
         Note : In above url get list of employee of the type specified {type} of url.
         To Get single Emplyee by using uniqid of Employee.
              http://localhost/restservices/MyRestServices.svc/Employees/{EmployeesID}
         Note : In above URL {EmployeesID} is get replaced by ID of Employee.
         Extension to above scenario, If want to get employee by using id with the type
              http://localhost/restservices/MyRestServices.svc/Employees/{EmployeesID}?type = {type}
  • Create Employee
          URL is to create employee is
             http://localhost/restservices/MyRestServices.svc/Employees/{employeeid}
         Note : In above URL {EmployeesID} is get replaced by ID of Employee.
  • Update Employee
          URL to update employee is
             http://localhost/restservices/MyRestServices.svc/Employees/{employeeid}
         Note : In above URL {EmployeesID} is get replaced by ID of Employee.
  • Delete Employee
         URL to delete employee is
             http://localhost/restservices/MyRestServices.svc/Employees/{EmployeeID}
        Note : In above URL {EmployeesID} is get replaced by ID of Employee.

As you can see here the URL for Create, Update and Delete are same but it makes actual difference when you combile this URL with specific HTTP methods.

Now Combine the url(s) with the HTTP methods

List Employees
  • GET - http://localhost/restservices/MyRestServices.svc/Employees
Create/Update  Employee
  • PUT - http://localhost/restservices/MyRestServices.svc/Employees/{employeeid}
Note : Both Create/Update employee use the same url but when you create employee employeeid =0 and when you update employee empoloyeeid=anynumeircvalue or GUID. This URL can be differ in you implementation this just example.

Delete Employee
  • DELETE - http://localhost/restservices/MyRestServices.svc/Employees/{EmployeeID}


Designing WCF with REST
Article link to get understanding about WCF service Create, Host(Self Hosting, IIS hosting) and Consume WCF servcie

To design Rest WCF service first start to design Class to represent Employee
[DataContract]
    public class Employee
    {
        [DataMember]
        public string Employeename { get; set; }
        [DataMember]
        public string Designation { get; set; }
        [DataMember]
        public string Address { get; set; }
        [DataMember]
        public string Email { get; set; }
    }
as you see Employee class DataContaract attribute so that is going to serve data to client i.e going to work as data exchanger.

Now start with Creation of WCF service which going to serve data to the client i.e going to work as REST full service.
You need to decorate each method in your Servercie interface with the WebInvoke attribute in addition to OperationContract, which allows user to bind method with UrlTemplate and HTTP method. Lets look the each method of interface one by one
public interface IService1
{
Get Methods
Following methods serve data which is requested using GET method of HTTP.
  • GetEmployees
Allow to get all employees. "tag" allow user to filter data because some times system contains more no. of employee which increase traffice and slow down respose, so by specifing tag=manager or tag=senior you will get specific set of employee.
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,UriTemplate = "?tag={tag}")]
  [OperationContract]
  Employees GetEmployees(string tag);
  • GetEmployee
Allow to get the employee with specific id. "Employee_id" of the uritemplate get replace with the employeeid.
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "Employees/{Employee_id}")]
  [OperationContract]
  Employee GetEmployee(string Employee_id);
Create and Update Method
Following method allow to insert new data and update existed using HTTP method PUT.
  • PutEmployeeAccount
This method allow to insert new employee into system and to update existed employee. "Employee_Id" of the uritemplate get replaced by employee id if update is there and 0 if new employee require to create.
[WebInvoke(Method = "PUT", ResponseFormat = WebMessageFormat.Json, UriTemplate = "Employees/{Employee_Id}")]
  [OperationContract]
   string PutEmployeeAccount(Employee Employeeobj,string Employeename );    

Delete Mehtod
Method allow to remove data using HTTP method DELETE.
  • DeleteEmployeeAccount
Method allow to delete employee from system. "Employee_Id" of the uritemplate get replace by the employee id.
[WebInvoke(Method = "DELETE", UriTemplate = "Employees/{Employee_Id}")]
  [OperationContract]
  void DeleteEmployeeAccount(string Employeename);
}
WebInvoke
  • The WebInvokeAttribute determines what HTTP method that a service operation responds to I.e Http post, get or delete.
  • Indicates a service operation is logically an invoke operation and that it can be called by the REST programming model.
UriTemplate
  • An URI template is a URI-like String that contained variables marked of in braces ({, }), which provides a consistent way for building and parsing URIs based on patterns.
  • UriTemplates are composed of a path and a query. A path consists of a series of segments delimited by a slash (/). Each segment can have a literal value, a variable value (written within curly braces [{ }] .query part is optional. If present, it specifies same way as querystring name/value pairs. Elements of the query expression can be presented as (?x=2) or variable pairs (?x={val}).
  • One of the reason to add this class in .net is to support the REST architectural style used by developers today.


Consume WCF RESTfull service
Before you start following reading below its better to know that how to configure and consume WCF service using jQuery : Steps to Call WCF Service using jQuery

Below is jQuery code to consume web service.
var Type;
var Url;
var Data;
var ContentType;
var DataType;
var ProcessData;
var method;
//Generic function to call WCF  Service
function CallService() {
   $.ajax({
      type: Type, //GET or POST or PUT or DELETE verb
      url: Url, // Location of the service
      data: Data, //Data sent to server
      contentType: ContentType, // content type sent to server
      dataType: DataType, //Expected data format from server
      processdata: ProcessData, //True or False
      success: function(msg) {//On Successfull service call
       ServiceSucceeded(msg);
      },
   error: ServiceFailed// When Service call fails
  });
 }

function ServiceFailed(result) {
   alert('Service call failed: ' + result.status + '' + result.statusText);
   Type = null; 
   Url = null; 
   Data = null; 
   ContentType = null; 
   DataType = null; 
   ProcessData = null;
}
Code above declare and initializes variables which are defined above to make a call to the service. CallService function sent request to service by setting data in $.ajax
GetEmployee
function GetEmployee() {
   var uesrid = "1";
   Type = "POST";
   Url = "Service1.svc/Employees/1";
   ContentType = "application/json; charset=utf-8";
   DataType = "json"; ProcessData = false;
   method = "GetEmployee";
   CallService();
}
GetEmployee method used to get employee with specific id. URL to make call to service is
Service1.svc/Employees/1
in this 1 is employeeid that which is example in turn this function call the RESTfull service function which is having URLTemplate Employees/{Employee_Id} and method type is POST.
CreateEmployee
function CreateEmployee() {
   Type = "PUT";
   Url = "Service1.svc/Employees/0";

    var msg2 = { "Employeename": "Denny", "Designation": "engg.", "Address": "vadodara", "Email": "pr@ab.com" };

   Data = JSON.stringify(msg2);
   ContentType = "application/json; charset=utf-8";
   DataType = "json";
   ProcessData = true;
   method = "CreateEmployee";
   CallService();
}
this method used to create employee. URL to make call to service is
Service1.svc/Employees/Denny
in this 0 is employeeID (0 because I am creating new employee) that which is example in turn this function call the RESTfull service function which is having url template Employees/{Employee_Id} and method type is POST.
In the createemployee method I am creating Employee object with the property require which is going to be consume by service to create employee.

The following code checks the result.GetUserResult statement, so your result object gets the property your service method name + Result. Otherwise, it will give an error like object not found in Javascript.
function ServiceSucceeded(result) {
   if (DataType == "json") {
     if(method == "CreateEmployee")
     {
        alert(result);
     }
     else
     {
        resultObject = result.GetEmployeeResult;
        var string = result.Employeename + " \n " + result.Designation + " \n " +          result.Address + " \n " + result.Email;
        alert(string);
     }
             
   }         
}

function ServiceFailed(xhr) {
   alert(xhr.responseText);
   if (xhr.responseText) {
      var err = xhr.responseText;
      if (err)
          error(err);
      else
          error({ Message: "Unknown server error." })
   }
      return;
 }

$(document).ready(
         function() {
             CreateEmployee();
         }
);
So in this article I am just showed example of CreateEmployee and GetEmployee because this is enough to understand how to consume the method of WCF RESTfull service. Now can create other methods by downloading code and to understand it better way.

Summary
Its quite easy to Create RESTfull service using .net WCF framework. But it must require to understand how you represent your resource i.e design URL template to represent your resource on WEB.

46 comments:

  1. Beautiful post, mnogosmyslenny ...

    ReplyDelete
  2. You should talk about Cross Domain problem with JSONP and Allow Options

    ReplyDelete
  3. From the last couple of days I was learning REST API in C#.NET.
    I have successfully created some methods.

    But I have got the following requirement

    campaigns.svc/xml/apikey/filters?parameter=value&parameter2=value2/start/limit

    so, in the above we are sending four parameters

    1. KEY
    2. Filter options
    3. Start value
    4. Limit value

    Can I know how to build a method, where I can access set of FILTER options

    ReplyDelete
  4. From the last couple of days I was learning REST API in C#.NET.
    I have successfully created some methods.

    But I have got the following requirement

    campaigns.svc/xml/apikey/filters?parameter=value&parameter2=value2/start/limit

    so, in the above we are sending four parameters

    1. KEY
    2. Filter options
    3. Start value
    4. Limit value

    Can I know how to build a method, where I can access set of FILTER options

    ReplyDelete
  5. Hey,
    I am having some trouble in fetching JSON string from WCF Service via JQuery.

    http://stackoverflow.com/questions/9546338/unable-to-return-json-string-from-wcf-service-from-jquery#comment12097852_9546338

    Please help.
    Salil

    ReplyDelete
  6. What changes should I do for JSONP? In case of JSONP, my wcf service always returns failed. Any idea?

    ReplyDelete
  7. "Following methods serve data which is requested using GET method of HTTP."

    Then you use Method="POST"

    ReplyDelete
  8. Code download link is not working..

    ReplyDelete
  9. Greetings! I know this is kinda off topic nevertheless I'd figured I'd ask.

    Would you be interested in trading links or maybe guest writing a blog article
    or vice-versa? My blog covers a lot of the same topics as yours and I feel we could
    greatly benefit from each other. If you happen to be interested
    feel free to shoot me an email. I look forward to hearing from you!
    Awesome blog by the way!

    Visit my webpage: scuba diving Gauteng

    ReplyDelete
  10. I almost never drop remarks, however i did a few searching and
    wound up here "Create REST service with WCF and Consume using jQuery".
    And I do have 2 questions for you if it's allright. Could it be just me or does it look as if like a few of the responses look like written by brain dead individuals? :-P And, if you are posting at other social sites, I would like to keep up with everything new you have to post. Could you make a list of all of your social sites like your twitter feed, Facebook page or linkedin profile?

    Here is my homepage :: website

    ReplyDelete
  11. I think the admin of this website
    is in fact working hard for his web site, for the reason that here
    every stuff is quality based material.

    ReplyDelete
  12. This post will help the internet viewers for creating new web site or even
    a blog from start to end.

    Feel free to visit my website - visit link

    ReplyDelete
  13. Paragraph writing is also a fun, if you be familiar with after that you can write or else it is difficult to write.


    Here is my blog post click here

    ReplyDelete
  14. My brother suggested I might like this web site. He was entirely right.
    This post actually made my day. You can not imagine just how much time I had spent for this information!
    Thanks!

    My webpage ... know more

    ReplyDelete
  15. I visited several web sites but the audio feature for audio songs present at this website is really superb.


    My web page :: Visit Link

    ReplyDelete
  16. I have learn several excellent stuff here.
    Certainly price bookmarking for revisiting. I wonder how much effort you place to make this sort of
    excellent informative web site.

    Here is my page; visit link

    ReplyDelete
  17. I've been exploring for a little for any high-quality articles or weblog posts on this sort of space . Exploring in Yahoo I finally stumbled upon this web site. Studying this info So i'm happy to show that I've a very excellent uncanny feeling I came upon just what I needed. I most no doubt will make sure to don?t overlook this web site and provides it a glance on a constant basis.

    Here is my weblog :: visit link

    ReplyDelete
  18. If some one needs to be updated with hottest technologies then he must be pay a quick visit this site and
    be up to date everyday.

    Review my website :: addiction therapy Cape Town

    ReplyDelete
  19. Hi just wanted to give you a quick heads up and let you know a few of the pictures aren't loading correctly. I'm not
    sure why but I think its a linking issue.
    I've tried it in two different web browsers and both show the same outcome.

    Here is my webpage :: site

    ReplyDelete
  20. What's up, of course this piece of writing is really good and I have learned lot of things from it concerning blogging. thanks.

    Visit my weblog :: business payroll services Gauteng

    ReplyDelete
  21. Good day! Would you mind if I share your blog with my zynga group?
    There's a lot of folks that I think would really enjoy your content. Please let me know. Cheers

    Feel free to surf to my webpage ... marquee hire Gauteng

    ReplyDelete
  22. I tend not to create a ton of comments, however I looked through some remarks here "Create REST service with WCF and Consume using jQuery".

    I actually do have some questions for you if you do not mind.
    Could it be just me or do some of the comments appear as if
    they are left by brain dead people? :-P And, if you are writing at additional online
    sites, I'd like to keep up with you. Would you list of the complete urls of your social community sites like your linkedin profile, Facebook page or twitter feed?

    Also visit my site :: party venue hire Sussex

    ReplyDelete
  23. Your mode of telling everything in this piece of writing
    is in fact nice, every one be capable of without difficulty understand it, Thanks a lot.


    Here is my homepage; architecture Gauteng

    ReplyDelete
  24. My programmer is trying to persuade me to move to .

    net from PHP. I have always disliked the idea because of the costs.
    But he's tryiong none the less. I've been using Movable-type on a variety of
    websites for about a year and am anxious about switching
    to another platform. I have heard fantastic things
    about blogengine.net. Is there a way I can import all my wordpress
    content into it? Any kind of help would be really appreciated!


    Also visit my page; facebook sex

    ReplyDelete
  25. Interesting article. It is very unfortunate that
    over the last one decade, the travel industry has had to tackle terrorism,
    SARS, tsunamis, bird flu virus, swine flu,
    plus the first ever true global economic collapse. Through
    it the industry has really proven to be robust, resilient along with dynamic, acquiring new methods to deal with adversity

    Stop by my web-site ... pulheimarchiv.zohren.net

    ReplyDelete
  26. We're a gaggle of volunteers and starting a new scheme in our community. Your site offered us with helpful info to paintings on. You've done an impressive activity and
    our whole community will likely be grateful to you.

    My webpage ... virtual dating

    ReplyDelete
  27. Thanks for the various tips discussed on this weblog.
    I have noticed that many insurance carriers offer clients generous deals if they favor to insure multiple cars with them.
    A significant volume of households own several automobiles
    these days, in particular those with elderly teenage still living at home, as
    well as the savings upon policies may soon begin. So it makes sense to look for a bargain.


    Review my blog; www.iphonerecoveryspecialist.com

    ReplyDelete
  28. I have come to understand that rates for online degree experts tend to be a fantastic value.

    Like a full 4-year college Degree in Communication from The
    University of Phoenix Online consists of 60 credits
    from $515/credit or $30,900. Also American Intercontinental University Online comes with a
    Bachelors of Business Administration with a overall education course requirement of 180 units and a price of $30,
    560. Online learning has made obtaini higher education
    degree been so detailed more than before because you could earn your own degree in the comfort in your home and when you finish from work.
    Thanks for all the other tips I've learned from your site.

    my blog post ... free date services

    ReplyDelete
  29. I have come across that today, more and more
    people will be attracted to video cameras and the
    issue of photography. However, as a photographer, you should first spend so much time period
    deciding the model of camera to buy plus moving
    store to store just so you can buy the least expensive camera of the
    brand you have decided to pick out. But it doesn't end generally there. You also have to consider whether you can purchase a digital digital camera extended warranty. Many thanks for the good ideas I received from your blog site.

    Feel free to surf to my weblog ... skype sex

    ReplyDelete
  30. 'member merchants'.

    Also visit my homepage :: fuckbook

    ReplyDelete
  31. I have discovered some significant things through your blog post.
    One other point I would like to say is that there are numerous games in the marketplace designed particularly
    for toddler age young children. They include pattern
    identification, colors, animals, and shapes.
    These often focus on familiarization rather than memorization.

    This makes children occupied without having the experience like they are learning.
    Thanks

    My blog: adult sex

    ReplyDelete
  32. Woah! I'm really enjoying the template/theme of this blog. It's simple, yet effective.
    A lot of times it's very difficult to get that "perfect balance" between superb usability and appearance. I must say that you've
    done a amazing job with this. In addition, the blog loads
    extremely quick for me on Firefox. Excellent Blog!

    Here is my weblog: skype sex

    ReplyDelete
  33. I have not checked in here for some time as I thought it was getting boring, but
    the last several posts are good quality so
    I guess I�ll add you back to my daily bloglist.
    You deserve it friend :)

    My weblog compassspace.com

    ReplyDelete
  34. Hiya very cool web site!! Guy .. Beautiful ..
    Amazing .. I will bookmark your website and take the feeds also�I am glad to
    search out numerous useful information right here in the post, we want work out
    more techniques on this regard, thanks for
    sharing. . . . . .

    Feel free to surf to my web site - www.24-7press.com

    ReplyDelete
  35. I have observed that over the course of developing a relationship with real estate proprietors,
    you'll be able to come to understand that, in every real estate deal, a commission rate is paid. Finally, FSBO sellers do not "save" the commission. Rather, they try to earn the commission through doing an agent's occupation.
    In completing this task, they devote their money in addition to
    time to conduct, as best they're able to, the tasks of an real estate agent. Those tasks include displaying the home through marketing, showing the home to buyers, building a sense of buyer urgency in order to prompt an offer, making arrangement for home inspections, tak qualification checks with the lender, supervising fixes, and aiding the closing.

    Feel free to surf to my web page ... facebook sex

    ReplyDelete
  36. Thanks for ones marvelous posting! I certainly
    enjoyed reading it, you will be a great author.I will make sure to bookmark
    your blog and will often come back later on. I want to
    encourage yourself to continue your great writing, have a nice weekend!



    my blog: adult finder

    ReplyDelete
  37. Thanks a lot for sharing this with all of us you actually know what you are talking about!
    Bookmarked. Kindly also visit my website =).
    We could have a link exchange contract between us!



    Feel free to visit my web blog fuckbook

    ReplyDelete
  38. Hey! Someone in my Facebook group shared this website with us so
    I came to take a look. I'm definitely enjoying the information. I'm book-marking and will be tweeting this to my followers!
    Fantastic blog and excellent design.

    Here is my homepage :: fuck book

    ReplyDelete
  39. Нey this is κіnd of οf
    off topіc but I ωaѕ wοndering if blogs usе WYSIWYG
    eԁitοrs ог іf you havе to mаnually cοԁe ωith HTML.
    I'm starting a blog soon but have no coding expertise so I wanted to get advice from someone with experience. Any help would be enormously appreciated!

    My web-site: diamondlinks review

    ReplyDelete
  40. Can you please let me know how to use WCF rest using xml as input from Jquery

    vikas

    ReplyDelete
  41. Nice article..

    But I have another simple example to call a WCF RestFul Service using jQuery AJAX Call, please refer to link below:- http://www.etechpulse.com/2014/03/how-to-consume-wcf-restful-service-in.html

    Thanks

    ReplyDelete
  42. Remarkable! Its actually awesome article, I have got much clear idea concerning from this post.


    Stop by my web site ... language translation algorithm

    ReplyDelete