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

Published on Author Rob WindsorLeave a comment

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.

Capture301

 

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.

Capture302

 

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.

Leave a Reply

Your email address will not be published. Required fields are marked *