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
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
http://localhost/restservices/MyRestServices.svc
In below discussion I am going to design the URL presentation for each operation
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}
http://localhost/restservices/MyRestServices.svc/Employees/{employeeid}
Note : In above URL {EmployeesID} is get replaced by ID of Employee.
http://localhost/restservices/MyRestServices.svc/Employees/{employeeid}
Note : In above URL {EmployeesID} is get replaced by ID of Employee.
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
Delete Employee
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
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
Following methods serve data which is requested using GET method of HTTP.
Following method allow to insert new data and update existed using HTTP method PUT.
Delete Mehtod
Method allow to remove data using HTTP method DELETE.
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.
GetEmployee
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
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.
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.
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
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
- List of Employees
- A Employee by Id
- Create Employee
- Update Employee
- Delete Employee
http://localhost/restservices/MyRestServices.svc
In below discussion I am going to design the URL presentation for each operation
- List Employees
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
http://localhost/restservices/MyRestServices.svc/Employees/{employeeid}
Note : In above URL {EmployeesID} is get replaced by ID of Employee.
- Update Employee
http://localhost/restservices/MyRestServices.svc/Employees/{employeeid}
Note : In above URL {EmployeesID} is get replaced by ID of Employee.
- Delete Employee
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
- PUT - http://localhost/restservices/MyRestServices.svc/Employees/{employeeid}
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 MethodsFollowing methods serve data which is requested using GET method of HTTP.
- GetEmployees
[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
[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
[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.
- 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 $.ajaxGetEmployee
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.
Beautiful post, mnogosmyslenny ...
ReplyDeleteYou should talk about Cross Domain problem with JSONP and Allow Options
ReplyDeleteWhere is the code
ReplyDeleteFrom the last couple of days I was learning REST API in C#.NET.
ReplyDeleteI have successfully created some methods.
But I have got the following requirement
campaigns.svc/xml/apikey/filters?parameter=value¶meter2=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
From the last couple of days I was learning REST API in C#.NET.
ReplyDeleteI have successfully created some methods.
But I have got the following requirement
campaigns.svc/xml/apikey/filters?parameter=value¶meter2=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
Hey,
ReplyDeleteI 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
great post
ReplyDeleteWhat changes should I do for JSONP? In case of JSONP, my wcf service always returns failed. Any idea?
ReplyDelete"Following methods serve data which is requested using GET method of HTTP."
ReplyDeleteThen you use Method="POST"
nice blog
ReplyDeleteCode download link is not working..
ReplyDeleteGreetings! I know this is kinda off topic nevertheless I'd figured I'd ask.
ReplyDeleteWould 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
I almost never drop remarks, however i did a few searching and
ReplyDeletewound 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
I think the admin of this website
ReplyDeleteis in fact working hard for his web site, for the reason that here
every stuff is quality based material.
This post will help the internet viewers for creating new web site or even
ReplyDeletea blog from start to end.
Feel free to visit my website - visit link
Paragraph writing is also a fun, if you be familiar with after that you can write or else it is difficult to write.
ReplyDeleteHere is my blog post click here
My brother suggested I might like this web site. He was entirely right.
ReplyDeleteThis post actually made my day. You can not imagine just how much time I had spent for this information!
Thanks!
My webpage ... know more
I visited several web sites but the audio feature for audio songs present at this website is really superb.
ReplyDeleteMy web page :: Visit Link
I have learn several excellent stuff here.
ReplyDeleteCertainly 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
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.
ReplyDeleteHere is my weblog :: visit link
If some one needs to be updated with hottest technologies then he must be pay a quick visit this site and
ReplyDeletebe up to date everyday.
Review my website :: addiction therapy Cape Town
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
ReplyDeletesure 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
What's up, of course this piece of writing is really good and I have learned lot of things from it concerning blogging. thanks.
ReplyDeleteVisit my weblog :: business payroll services Gauteng
Good day! Would you mind if I share your blog with my zynga group?
ReplyDeleteThere'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
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".
ReplyDeleteI 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
Your mode of telling everything in this piece of writing
ReplyDeleteis in fact nice, every one be capable of without difficulty understand it, Thanks a lot.
Here is my homepage; architecture Gauteng
My programmer is trying to persuade me to move to .
ReplyDeletenet 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
Interesting article. It is very unfortunate that
ReplyDeleteover 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
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
ReplyDeleteour whole community will likely be grateful to you.
My webpage ... virtual dating
Thanks for the various tips discussed on this weblog.
ReplyDeleteI 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
I have come to understand that rates for online degree experts tend to be a fantastic value.
ReplyDeleteLike 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
I have come across that today, more and more
ReplyDeletepeople 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
'member merchants'.
ReplyDeleteAlso visit my homepage :: fuckbook
I have discovered some significant things through your blog post.
ReplyDeleteOne 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
Woah! I'm really enjoying the template/theme of this blog. It's simple, yet effective.
ReplyDeleteA 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
I have not checked in here for some time as I thought it was getting boring, but
ReplyDeletethe 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
Hiya very cool web site!! Guy .. Beautiful ..
ReplyDeleteAmazing .. 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
I have observed that over the course of developing a relationship with real estate proprietors,
ReplyDeleteyou'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
Thanks for ones marvelous posting! I certainly
ReplyDeleteenjoyed 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
Thanks a lot for sharing this with all of us you actually know what you are talking about!
ReplyDeleteBookmarked. Kindly also visit my website =).
We could have a link exchange contract between us!
Feel free to visit my web blog fuckbook
Hey! Someone in my Facebook group shared this website with us so
ReplyDeleteI 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
google law firm
ReplyDelete