Share via


SharePoint 2013: Applying REST Filter To Field With REST API

Introduction

SharePoint development using JavaScript for any time I require unique customization not possible using out of the box. One of the technical challenges we may come across in our travels is trying to perform a GET of list items and filtering where a column value. Seems pretty straightforward right?

Scenario

In old days working with SharePoint lists or library, many times we came across querying lists and applying the filter on list items using CAML Query. We all know constructing long CAML query gets confusing and many lines of chunks as well. 

But no worries REST is the lifesaver; with REST it’s very easy to filter lists and gives to flexibility using few lines or sometimes just online of code.

In this post, we will be showing how to use REST to filter or query on SharePoint lists and returns data as we want.

We’ll first start to craft your URI like the following:

https://<siteUrl>/_api/Web/Lists/GetByTitle(‘listname’)/items?$select*&$filter= Title eq ‘test’

  • $Select: Lets you select list columns you want to return
  • **$filter: **Condition based results.

Refer the following images and code for clear understanding.

https://csharpcorner-mindcrackerinc.netdna-ssl.com/UploadFile/sagarp/applying-rest-query-filter-to-field-with-the-sharepoint-2013/Images/divisions.jpg

Solution

1st Approach

Open the browser and add the following URL in the address bar:

https://hostssite/apps/TestAppsite/_api/Web/Lists/GetByTitle('Divisions')/items?$select=*&$filter=Title eq 'test1'

https://csharpcorner-mindcrackerinc.netdna-ssl.com/UploadFile/sagarp/applying-rest-query-filter-to-field-with-the-sharepoint-2013/Images/code.jpg

2nd Approach

**Step 1: **Navigate to the SharePoint 2013 site.

Step 2: From this page select the Site Actions | Edit Page.

Edit the page, go to the "Insert" tab in the Ribbon and click the "Web Part" option. In the "Web Parts“dialogue, go to the "Media and Content" category, select the "Script Editor" Web Part and click the "Add button".

Step 3: Once the Web Part is inserted into the page, you will see an "EDIT SNIPPET" link; click it. You can insert the HTML and/or JavaScript as in the following code snippet:

function Divsion ()  
{  
  
 var listName = "Divisions";  
 var itemId="";  
  
 var Ownurl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle(' Divisions’)/items?$select=OwnerEmailID&$filter=Title eq 'test1'";  
 $.ajax({  
  
 url: Ownurl,  
 headers: { Accept: "application/json;odata=verbose"  },  
 async:false,  
 success: function  (data) {  
 var items = data.d.results;  
 if (items[0].OwnerEmailID != "") {  
 itemId = items[0].OwnerEmailID;  
 }  
  
  
 },eror: function  (data) {  
 alert("An error occurred. Please try again.");  
}  
 });  
}