Getting Started using the OData REST API to Query a SharePoint List

SharePoint 2010 exposes list data via OData.  I’m currently working on an article around SharePoint and OData.  As part of this effort, at various points, I’ll blog some of my intermediate samples.  This post details the minimum number of steps to query a SharePoint list using OData.

This blog is inactive.
New blog: EricWhite.com/blog

Blog TOCThis post is one in a series on using the OData REST API to access SharePoint 2010 list data.

  1. Getting Started using the OData REST API to Query a SharePoint List
  2. Using the OData Rest API for CRUD Operations on a SharePoint List

By far, the easiest way to get started with SharePoint development is to use the 2010 Information Worker Demonstration and Evaluation Virtual Machine that runs using Hyper-V.  The instructions in this and future related posts will be for that virtual machine.  If you have setup your own development environment with a different machine name, it is easy enough to adjust these procedures to work with your own servers.

Procedure: Query a SharePoint list using OData

1.    Download, extract, and boot the virtual machine.  The download includes detailed instructions.

2.    Log into the virtual machine.  Use the username brads.  The password is pass@word1.

3.    Create a new list.  Name the list ‘Inventory’.  Create a two new columns: Description, and Cost.  Make the type of the Description column be ‘Single line of text’.  Make the type of the Cost column be ‘Currency’.  Enter a couple of rows of sample data.

After completing this task, my list looked like this:

 

4.    Start Visual Studio 2010 in the virtual machine.

5.    Create a new project.  Click File -> New -> Project.  Select a directory for the project.  Set the name of the project to Gears.  The New Project dialog box will look something like this:

 

6.    Right click on the References node in the Solution Explorer window, and click Add Service Reference.  Enter https://intranet/_vti_bin/listdata.svc for the address.  Change the namespace to Data.  The Add Service Reference dialog box will look like this:

 

Click OK.

7.    Copy and paste the following code into Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Gears.Data;

namespace Gears
{
class Program
{
static void Main(string[] args)
{
TeamSiteDataContext dc =
new TeamSiteDataContext(new Uri("https://intranet/_vti_bin/listdata.svc"));
dc.Credentials = CredentialCache.DefaultNetworkCredentials;
var result = from d in dc.Inventory
select new
{
Title = d.Title,
Description = d.Description,
Cost = d.Cost,
};
foreach (var d in result)
Console.WriteLine(d);
}
}
}

8.    Press F5 to run.  If everything worked, you will see something like the following: