SharePoint Dev Quick Tip - Quickly and Easily Building SharePoint REST API Query URLs

Have you ever tried to build the URL for a REST API service call and ended up confused and frustrated? The OData query syntax is well documented, it’s just not that intuitive. Well, if you want to query list data I have a little trick you can use to have the appropriate URL generated for you. Unfortunately this trick doesn’t work with the SharePoint 2013 _api service since it doesn’t expose metadata.

Step 1:
Create a Console application and add a Service Reference to the ListData.svc service for your SharePoint site. I set the Namespace to DemoProxy in my example.

Capture

Step 2:
Inside the Main method, create an instance of the data context and attach the default credentials.

var context = new DemoProxy.DemoDataContext(new Uri("http://win7virtualbox/sites/demo/_vti_bin/ListData.svc/"));
context.Credentials = System.Net.CredentialCache.DefaultCredentials;

Step 3:
Write a LINQ query that retrieves the data you want. My site has some data I brought over from Northwind so I’ll use that.

var products = from product in context.Products
                where product.UnitsInStock > 0 &&
                product.Category.Title == "Condiments"
                orderby product.UnitPrice
                select product;

Step 4:
Run your program in debug mode and use the data tip or the locals windows to get the generated query. You could also use Fiddler for this.

Capture

And viola, in a minute or two you have the query you want. For me it looked like this:

/_vti_bin/ListData.svc/Products()?$filter=(UnitsInStock gt 0) and (Category/Title eq 'Condiments')&$orderby=UnitPrice

This tip and much more can be found in my SharePoint 2010 Lists and Libraries for Developers course on Pluralsight.

Published Fri, Feb 1 2013 3:58 by windsor

Comments

# Technology Post Roundup–8th Edition

In Canada, we’re fortunate to have many community experts and MVPs. Throughout the month, they write

Monday, March 11, 2013 11:31 PM by Canadian Developer Connection