Contact Us
Please fill out the form below and we will get in touch within four business hours.

*
*
*
*
*
*
*Interested In:
(Check all that apply)



 
 
Synergy Corporate Technologies
Synergyonline > Blog > Posts > Overview of using REST in SharePoint 2010
December 18

Overview of using REST in SharePoint 2010

REST (or Representational State Transfer) is an easy way to easily get or post items to a server-side web service.  It is used in situations where you would use a web service but do not want the overhead and tightly-coupled nature of SOAP. With REST, it’s just a simple, client-server-like request using HTTP to retrieve or send information.  Technically, REST is not a protocol, but an architectural style.

SharePoint 2010, being based on WCF in the .NET 3.5 Framework, has built-in RESTful web services which allow us to take advantage of this simplicity in custom applications we write.  It is one of the many data access mechanisms used in SharePoint 2010 development.  REST is intended for remote applications (i.e. not running physically on the SharePoint server) that need basic read/write capabilities to SharePoint’s list and library data.

(Technical Note: At the time of writing, this was based on SharePoint 2010 beta 2. For this to work, you need to download and install the v1.5 CTP2 version of ADO.NET data services on your SharePoint web front ends).

To help demonstrate some examples, let’s just go into the browser and make some get requests.  First off, here is a simple way to retrieve the lists and libraries in a web site.  (In my examples these will come from a SharePoint teamsite.)

http://sp2010a/teamsite/_vti_bin/listdata.svc

To retrieve information for a single list

http://sp2010a/teamsite/_vti_bin/listdata.svc/Contacts

Or perhaps just a single contact (in this case, the one with ID = 1)

http://sp2010a/teamsite/_vti_bin/listdata.svc/Contacts(1)

 

The output result comes back as an XML-based ATOM feed which is similar to RSS but having some notable advantages such as supporting binary object types.  By default, your browser may by default render this in a friendly HTML-way.  If you want to see the raw XML output--and for this demostration, we do--you’ll need to tell your browser otherwise.  For IE version 8 go to Tools –> Internet Options –> Content tab –> Feeds and web slices Settings.  In this dialog, clear the Turn on feed reading view checkbox as shown here:

image_2_77095443 

When you do that and issue the request again, here is the output you’ll see below.  This one was for a single contact (click image to enlarge).  You’ll notice you’re getting the actual data contents for this contact plus the metadata (column name, data type, etc).  So, you’re basically getting a strongly typed data set.

image_4_77095443 

As you might expect, there are plenty of options to filter and sort.  Such as

http://sp2010a/teamsite/_vti_bin/listdata.svc/Contacts?$filter=LastName eq 'Smith'

and

http://sp2010a/teamsite/_vti_bin/listdata.svc/Contacts?$orderby=LastName desc

To learn more about the other querystring options, here is a great MSDN article that walks through many of them and other REST details:  http://msdn.microsoft.com/en-us/library/cc907912.aspx

Using the browser this way is great for learning and testing, but what if we want to consume this in a real application?

Consuming Rest in a Real Application

Go into Visual Studio 2010 and create a new project.  For my demo, I’m going to create a new C# Windows Forms application.  To consume a RESTful web service in Visual Studio, you can go to the Data menu and click Add New Data Source.  In the dialog box, choose SharePoint as shown here:

image_6_77095443  

In the Add Service Reference dialog, add the Url to a SharePoint 2010 web site.  Since you chose SharePoint data source, you do not need to specify the _vti_bin/listdata.svc.  Visual Studio will do that for you.  In my case, I add http://sp2010a/teamsite.  After I click the Go button, here is what I am shown:

image_8_77095443  

For those that have consumed web services (either SOAP .asmx or WCF .svc ones), this should look familiar.  Visual Studio will be creating a proxy class for you that represents the strongly-typed nature of all of these lists.  Click OK to continue and a new proxy class will be created for you.

Before I go any further, since I am working on Beta code, I need to replace the older ADO.NET data services client DLL.  To do that, go to the project references for the project and remove the System.Data.Services.Client entry.  Replace it with the DLL found in C:\Program Files (x86)\ADO.NET Data Services V1.5 CTP2\bin. 

Next step is to go to the Data menu again and this time, select Show data sources.  From the list choices, I’m going to drag and drop Contacts onto my form.  This will create a GridView control and bind all of the columns based on the contacts type.  Since I only want to display a few columns, I’ll click on the GridView and edit the columns (see the Columns the properties window for the GridView object).  When I’m done, here is what I see:

image_10_77095443  

Ok, enough design work.  Let’s write some code.  Go into the code for the form.  Add two using clauses to the top (you might need to rename the first one based on your project name and the name you gave to your service reference). 

using RestDemo.ServiceReference1;
using System.Net;

 

Next, create a new class-level variable to hold the data context.  This is one of the proxy-class objects that was created that represents your interface to all the lists for the web site.  Notice that you also need to initialize it with the desired Url.  (Note: while you can change this to a different SharePoint Url, you must make sure that the list(s) that you intend on working with exist and have the same schema).

TeamSiteDataContext context = new TeamSiteDataContext(new Uri(http://sp2010a/teamsite/_vti_bin/listdata.svc));

Next, in the Form_Load event, add the following two lines.

context.Credentials = CredentialCache.DefaultCredentials;
contactsBindingSource.DataSource = context.Contacts;
The first line will authenticate to SharePoint using your current logged-in account.  Of course, other login methods are available.  The second references the Contacts entity.  The contactsBindingSource is an object automatically created by Visual Studio when you added the Contacts list to your form. The data source for the GridView automatically points to this data source, so we can simply use it to wire everything up.  Simple, right?
 
Note: In this example, I have not specified columns or rows.  In other words, give me everything which is not very efficient, sort of like a “select * from table” SQL command.  This is great for a simple demo, but not practical for large lists.  Here’s how it looks.

image_12_77095443 

We’ve seen above that REST allows you filter and sort.  What if you wanted to be more efficient and filter and sort in our application. You can and one way you can do this is with LINQ.  Here is the modified code that I use instead.

var q = from c in context.Contacts
where c.ID > 100
orderby c.FirstName
select new { c.FirstName, c.LastName, c.EMailAddress, c.BusinessPhone };

contactsBindingSource.DataSource = q;

Notice that I’m just selecting a subset of contacts, sorting by first name and only returning the columns that I’m using in my GridView.  Better, right?  Now I get 100 rows (instead of 200 shown in the first one), properly sorted.

image_14_77095443  

For those curious sorts (like me!), you might be interested in what the REST query looked like.  Here it is (as extracted from Fiddler):  http://sp2010a/teamsite/_vti_bin/listdata.svc/Contacts()?$filter=ID gt 100&$orderby=FirstName&$select=FirstName,LastName,EMailAddress,BusinessPhone

We’re not quite done yet.  As I started off at the top of the article, I briefly mentioned that REST supports sending information back.  Among others, it supports insert and update operations.  This is also very easy to do.

 

Sending updates back to the server

Let’s first start by enabling our Save icon for the GridView control.  To do this, just click the save icon in the designer and set the Enabled property to True.  Now, double click the icon and add this line of code into the save event.

context.SaveChanges();
 
Next, create a new method for the CurrentItemChanged event on the contactsBindingSource object.  To do this, go to design view for your form and select the contactsBindingSource object (you’ll find it just underneath the GridView).  In the properties panel, click the events icon (it looks like a lightning bolt).  You’ll get something like this shown here. 
 
image_20_77095443  

Now, double click the entry next to CurrentItemChanged.  This will create a new event handler and take you to the code behind file.  Add this one line into this method.

context.UpdateObject(contactsBindingSource.Current);
 
We’re nearly done, but have one small problem.  In order to update an item back on the server, it needs all of the columns.  This is so SharePoint can compare if there was a column-level conflict in the editing.  (Note: if a conflict does occur, this will be caught an an exception will be thrown in your client application).  So, we just make a minor change to our LINQ query.  This is a bit less efficient, but necessary for editing this way.
 
var q = from c in context.Contacts
where c.ID > 100
orderby c.FirstName
select c;

Notice that I’m selecting the whole record, not just certain columns.  As written, this will update the data context with the most recent item that has changed.  When you click the save button (coded above), this modified item will be send back to the server.  For those curious about what exactly does this do, this sends an HTTP merge request back to the server with the payload of the newly modified record.  Here is the XML that was posted.  

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<entry xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" 
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" 
xmlns="http://www.w3.org/2005/Atom">
<category scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" 
term="Microsoft.SharePoint.DataService.ContactsItem" />
<title />
<author>
<name />
</author>
<updated>2009-12-18T05:01:07.5478515Z</updated>
<id>http://sp2010a/teamsite/_vti_bin/listdata.svc/Contacts(201)</id>
<content type="application/xml">
<m:properties>
<d:Address m:null="true" />
<d:BusinessPhone m:null="true" />
<d:City m:null="true" />
<d:Company m:null="true" />
<d:ContentType>Contact</d:ContentType>
<d:ContentTypeID>0x01060028B781066EBD3A4E93FE3073BAD6D104</d:ContentTypeID>
<d:CountryRegion m:null="true" />
<d:Created m:type="Edm.DateTime">2009-12-18T12:42:05</d:Created>
<d:CreatedByID m:type="Edm.Int32">1</d:CreatedByID>
<d:EMailAddress m:null="true" />
<d:FaxNumber m:null="true" />
<d:FirstName>Mickey</d:FirstName>
<d:FullName>Mickey Mouse</d:FullName>
<d:HomePhone m:null="true" />
<d:ID m:type="Edm.Int32">201</d:ID>
<d:JobTitle m:null="true" />
<d:LastName>Mouse</d:LastName>
<d:MobileNumber m:null="true" />
<d:Modified m:type="Edm.DateTime">2009-12-18T12:59:25</d:Modified>
<d:ModifiedByID m:type="Edm.Int32">1</d:ModifiedByID>
<d:Notes>&lt;div&gt;&lt;/div&gt;</d:Notes>
<d:Owshiddenversion m:type="Edm.Int32">8</d:Owshiddenversion>
<d:Path>/teamsite/Lists/Contacts</d:Path>
<d:ProjectID m:type="Edm.Int32" m:null="true" />
<d:StateProvince m:null="true" />
<d:Version>1.0</d:Version>
<d:WebPage m:null="true" />
<d:ZIPPostalCode m:null="true" />
</m:properties>
</content>
</entry>

 

With that, I’ll bring this post to a close.  You now have an introductory knowledge on using REST in your SharePoint 2010 applications.  Have fun with it!

Don't forget to check out our SharePoint Development Blog Library from Synergy Team for the latest news, tricks and tips in SharePoint Development World. 

Comments

Re: Overview of using REST in SharePoint 2010

Thanks for your sample xml content posted
 on 11/16/2011 9:28 PM

sandy

thanks a lot
 on 2/22/2012 3:12 AM

Half the text is off the page

Making this a difficult article to read
 on 5/16/2012 6:45 AM

Re: Half the text is off the page

Thanks for noticing it. Fixed :)
 on 5/16/2012 11:27 AM

This has been a great help

Exactly what I needed to learn how to work with the system.
 on 6/6/2012 1:35 PM

Re: Overview of using REST in SharePoint 2010

excellent and useful
 on 10/25/2012 1:58 AM

Add Comment

Items on this list require content approval. Your submission will not appear in public views until approved by someone with proper rights. More information on content approval.

Title


Body *


Captcha

 

Attachments


United States
55 Greens Farms Road
Westport, CT 06880
 
1050 Bishop St.
Suite 176
Honolulu, HI 96813
United Kingdom
Unit 13 Elder Way Waterside Drive Langley Berkshire SL3 6EP
United Kingdom
Singapore
Level 37
Ocean Financial Centre
10 Collyer Quay
Singapore 049315
Asia Pacific
Level 6
115 Pitt Street
Sydney NSW 2000
Australia 
+1800-930-4771
+44 (0)1753 541 000
+(65) 6232 2329
+61 2 9113 7243
United States
United Kingdom
Singapore
Australia
This web page conforms to W3C's "Web Content Accessibility Guidelines 1.0" Level "A" © 2014 Synergy Corporate Technologies
This site is best viewed in IE8 or above. Some features may not render properly if you are using an older browser.