<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Search API Archives - Michael Soriano</title>
	<atom:link href="https://michaelsoriano.com/tag/search-api/feed/" rel="self" type="application/rss+xml" />
	<link>https://michaelsoriano.com/tag/search-api/</link>
	<description>I turn code into captivating user experiences for the web</description>
	<lastBuildDate>Sat, 16 Jan 2016 19:44:12 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.4</generator>
	<item>
		<title>Understanding SharePoint&#8217;s REST and Search API Part 1 &#8211; Selecting Items</title>
		<link>https://michaelsoriano.com/understanding-sharepoint-rest-api-part-1-selecting-items/</link>
					<comments>https://michaelsoriano.com/understanding-sharepoint-rest-api-part-1-selecting-items/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Sat, 16 Jan 2016 19:44:12 +0000</pubDate>
				<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Search API]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=5349</guid>

					<description><![CDATA[<p>SharePoint 2013 has a REST API that exposes plenty of information about users, lists and document libraries. For front end developers, this is a gold mine. A gold mine because of two things: 1) SharePoint&#8217;s out of the box UI is pretty bad, and 2) SharePoint&#8217;s out of the box UI is pretty bad. Update [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/understanding-sharepoint-rest-api-part-1-selecting-items/">Understanding SharePoint&#8217;s REST and Search API Part 1 &#8211; Selecting Items</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>SharePoint 2013 has a REST API that exposes plenty of information about users, lists and document libraries. For front end developers, this is a gold mine. A gold mine because of two things: 1) SharePoint&#8217;s out of the box UI is pretty bad, and 2) SharePoint&#8217;s out of the box UI is pretty bad.</p>
<div style="padding: 15px 20px; background: #fcffe6; border-radius: 4px; border: 1px solid #e5e9cd; margin-top: 20px; margin-bottom: 25px;"><strong>Update 3/2017:</strong> I&#8217;ve added Search API to this post as well. Continue reading below.</div>
<p>So plenty of room for improvement here. Now we can basically recreate SharePoint&#8217;s front end: entire new CRUD interfaces and such. And the base of it all &#8211; is its REST API.<br />
It is important to recognize that SharePoint REST API is using <a href="http://www.odata.org/">OData</a>, which is a widely used convention when in comes to RESTful web services. You can learn more about the syntax from their website.<br />
For this post I would like to cover <strong>Selecting Items</strong>.<br />
Note that I prefer using jQuery&#8217;s <strong>$.ajax</strong> method. So all my calls will look like below:</p>
<pre>$.ajax({
   url: url, //THE ENDPOINT
   method: "GET",
   headers: { "Accept": "application/json; odata=verbose" },
   success: function (data) {
        console.log(data.d.results) //RESULTS HERE!!
   }
});
</pre>
<p>All we&#8217;re doing is replacing the <strong>url</strong><br />
<strong>A special note on SP 2010 users:</strong> the querystring section of the examples below may be the same. The only difference I&#8217;ve seen is the endpoint part of the url. SP 2010 has below:</p>
<pre class="">"/_vti_bin/listdata.svc/" + querystring</pre>
<h3>1) Selecting all items, all columns</h3>
<p>The simplest way to grab list items is to get everything. This is done by using the endpoint below. Simply change the &#8220;list&#8221; value to your own:</p>
<pre class="">/_api/web/lists/getbytitle('listname')/Items?$select=*</pre>
<p>Again, this will select &#8220;almost&#8221; all columns that are available to the list.  Note that I said &#8220;almost&#8221;, because SharePoint&#8217;s REST API doesn&#8217;t really bring back everything. Things such as author information and values of lookups have to be queried differently (more on this below).</p>
<h3>2) Selecting all items, custom columns</h3>
<p>)I find it good practice to only grab the columns that I need. This makes the payload as lean as possible.</p>
<pre class="">/_api/web/lists/getbytitle('listname')/Items?$select=ID,Title</pre>
<p>This also makes it easier to find things because each Javascript object only contain the columns &#8220;ID&#8221; and &#8220;Title&#8221;. What I don&#8217;t understand is why &#8220;ID&#8221; and &#8220;Id&#8221; is present &#8211; maybe a configuration error with the list. But nevertheless, the result is more manageable:<br />
<img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-5453" src="https://michaelsoriano.com/wp-content/uploads/2016/01/rest-select-1.jpg" alt="rest-select-1" width="449" height="181" srcset="https://michaelsoriano.com/wp-content/uploads/2016/01/rest-select-1.jpg 449w, https://michaelsoriano.com/wp-content/uploads/2016/01/rest-select-1-300x121.jpg 300w" sizes="(max-width: 449px) 100vw, 449px" /></p>
<h3>3) Getting the total items in a list</h3>
<p>To get the number of items in a list, append the &#8220;ItemCount&#8221; in the end of your query sting.</p>
<pre class="">/_api/web/lists/getbytitle('listName')/ItemCount
</pre>
<p>I know that you can simply do a &#8220;.length&#8221; from the a regular call which brings you all of your results, but the above is useful for filtered results, or when paging. The output looks like below:<br />
<img decoding="async" class="alignnone size-full wp-image-5470" src="https://michaelsoriano.com/wp-content/uploads/2016/01/item-count1.jpg" alt="item-count1" width="340" height="125" srcset="https://michaelsoriano.com/wp-content/uploads/2016/01/item-count1.jpg 340w, https://michaelsoriano.com/wp-content/uploads/2016/01/item-count1-300x110.jpg 300w" sizes="(max-width: 340px) 100vw, 340px" /></p>
<h3>4) Retrieving specific list items</h3>
<p>Now this endpoint will only get the list item with the ID of &#8220;4&#8221; (I&#8217;ve removed the &#8220;_spPageContextInfo.webAbsoluteUrl&#8221; component for easier read&#8230;</p>
<pre class="">/_api/web/lists/getbytitle('listname')/items(4)</pre>
<p>A more powerful solution is using the <strong>$filter</strong> key. Not that this option allows you to get items with more flexibility. Check out this example which grabs items with the title equals to &#8220;example 1&#8221;. Note the use of single quotes! Almost all values in SharePoint REST use single quotes!</p>
<pre class="">/_api/web/lists/getbytitle('listname')/Items?$select=Title&amp;$filter=Title eq 'example 1'</pre>
<h3>5) Multiple $filter keys + values</h3>
<p>To get items that have Title that is equal to multiple values, use the endpoint below:</p>
<pre class="">/_api/web/lists/getbytitle('listname')/Items?$select=Title&amp;$filter=((Title eq 'example 1') or (Title eq 'example 2'))</pre>
<p>Notice that I used parenthesis to enclose the multiple parameters. This is completely optional &#8211; but improves readability.<br />
In the case of multiple &#8220;ANDs&#8221; and &#8220;ORs&#8221;, for a stricter and finer result set, you need to use the parenthesis to enclose filter sets. This example below:</p>
<pre class="">/_api/web/lists/getbytitle('ListName')/Items?$&amp;$select=Title&amp;$filter=((ContentType eq 'Operating Policy') or (ContentType eq 'Procedure')) and (Subject eq 'Safety')</pre>
<p>You see how we&#8217;re grabbing items with &#8220;ContentType&#8221; equaling to &#8220;Operating Policy&#8221; OR &#8220;Procedure&#8221; AND &#8220;Subject&#8221; equaling to &#8220;Safety&#8221;.</p>
<h3>6) Using &#8220;startswith()&#8221; and &#8220;substringof()&#8221; functions with $filter</h3>
<p>At times you need a more powerful filter in SharePoint REST API. See &#8220;eq&#8221; will only retrieve exact matches. If you want to get everything that starts with &#8220;test&#8221;, you use the &#8220;<strong>startswith()</strong>&#8221; function:</p>
<pre class="lang:default decode:true">/_api/web/lists/getbytitle('ListName')/Items?$filter=((startswith(column,'test')))</pre>
<p>Note that the &#8220;column&#8221; is the first parameter, then the value! This is a mistake that I&#8217;ve done several times because the <a href="https://social.technet.microsoft.com/wiki/contents/articles/35796.sharepoint-2013-using-rest-api-for-selecting-filtering-sorting-and-pagination-in-sharepoint-list.aspx#Filtering_items">documentation</a> is pretty weak.<br />
Now, if you want to get items that &#8220;contains&#8221; specific characters, you use the &#8220;<strong>substringof()</strong>&#8221; function.</p>
<pre class="lang:default decode:true">/_api/web/lists/getbytitle('ListName')/Items?$filter=((substringof('test',column)))</pre>
<p>Unlike startswith(), the substring() takes the &#8220;value&#8221; first, then the &#8220;column&#8221;. Again, note the difference between the two.</p>
<h3>7) Limiting your results</h3>
<p>The <strong>$top</strong> parameter basically limits your items to a specified number. The syntax is below:</p>
<pre class="">/_api/web/lists/getbytitle('listname')/Items?$select=Title&amp;$top=10</pre>
<p>This is also useful for creating paging systems &#8211; in combination with an offset option (below).</p>
<h3>8) Offsetting results (for paging)</h3>
<p>So you know how to limit your results, and you know how to get the total items. All you need is to offset your results. You do this with the &#8220;$skip&#8221; parameter.</p>
<pre class="">/_api/web/lists/getbytitle('listname')/Items?$top='10'&amp;$skip='20'
</pre>
<p>Again, note the use of single quotes. The above will get a set of 10 items, starting from the 20th in the list. Combined with the total, you can create your own paging mechanism.<br />
<strong>Update 8/10/2016:</strong> I just found out that the <a href="http://sharepoint.stackexchange.com/questions/126565/issue-with-skip-in-rest-api">$skip parameter doesn&#8217;t work</a> with list items. There is a property in the REST response that you can use &#8211; for paging. This is known as the &#8220;___next&#8221;. I will do another tutorial strictly on this subject &#8211; so stay tuned.</p>
<h3>9) Getting the Author Information</h3>
<p>You have to specify that using the &#8220;$expand&#8221; key. Also an additional parameter to the &#8220;$select&#8221; key is needed. For example, to grab the Id and the name of the author, simply append to your query:</p>
<pre class="">/_api/web/lists/getbytitle('listname')/Items?$select=Author/Title,Comment&amp;$expand=Author/Title</pre>
<p>The above will return the author information in it&#8217;s own node called &#8220;Author&#8221;.<br />
<img decoding="async" class="alignnone size-full wp-image-5455" src="https://michaelsoriano.com/wp-content/uploads/2016/01/rest-select-2.jpg" alt="rest-select-2" width="396" height="155" srcset="https://michaelsoriano.com/wp-content/uploads/2016/01/rest-select-2.jpg 396w, https://michaelsoriano.com/wp-content/uploads/2016/01/rest-select-2-300x117.jpg 300w" sizes="(max-width: 396px) 100vw, 396px" /></p>
<h3>10) Document Libraries</h3>
<p>SharePoint REST API supports querying document libraries. Remember, doc libs are also lists and for the most part, are handled through the same endpoint.</p>
<pre class="">/_api/web/lists/getbytitle('Document Library Name')/Items?$select=Title,FileLeafRef,EncodedAbsThumbnailUrl,EncodedAbsUrl</pre>
<p>The example above returns information about your file such as the name, full url and the internal &#8220;Title&#8221;:<br />
<img decoding="async" class="alignnone size-full wp-image-5417" src="https://michaelsoriano.com/wp-content/uploads/2015/12/rest-select2.gif" alt="rest-select2" width="531" height="160" /><br />
For instances where you want to know the &#8220;type&#8221; of document library it is (example Picture Library vs Document Library), use:</p>
<pre class="">/_api/web/lists/getbytitle('Document Library Name')/BaseTemplate</pre>
<p>Although some information regarding document libraries require an entirely new endpoint. This includes file paths, subfolders, thumbnails and such.</p>
<pre class="">/_api/web/GetFolderByServerRelativeUrl('"Folder Name"')/Files</pre>
<p>The above contains an entire new set of information regarding your library.</p>
<h3>11) Getting Current User information:</h3>
<p>At times you want to grab the current user&#8217;s information. Use the endpoint below:</p>
<pre class="">/_api/SP.UserProfiles.PeopleManager/GetMyProperties</pre>
<p>I&#8217;ve also used the more current endpoint below:</p>
<pre class="lang:js decode:true">/_api/web/currentUser</pre>
<p>Again, there may be additional information that is not returned by the above, such as user groups (below) which requires a different endpoint.</p>
<h3>12) Getting Current User Groups</h3>
<p>For some reason, this information is separate from getting the current user information described above. But in order to get the current user groups, you need to pass the ID:</p>
<pre class="lang:js decode:true">/_api/web/GetUserById('"+ userId +"')/Groups</pre>
<p>So you need to get the &#8220;userId&#8221; first, then do the above ajax call. Something like below:</p>
<pre class="lang:default decode:true">function getCurrentUser(){
   var ajax = $.ajax({
       url:   _spPageContextInfo.siteAbsoluteUrl + "/_api/web/currentUser",
       method: "GET",
       headers: { "Accept": "application/json; odata=verbose" },
       error: function (data) {
           console.log(data);
          }
        });
       return ajax;
}
function getUserGroups (userId) {
   var ajax = $.ajax  ({
        url:  _spPageContextInfo.siteAbsoluteUrl + "/_api/web/GetUserById('"   + userId + "')/Groups",
        method: "GET",
           headers: { "Accept": "application/json; odata=verbose" }
     });
    return ajax;
    }
getCurrentUser().done(function(userId){
   getUserGroups(userId.d.Id).done(function(groups){
       console.log(groups.d.results);
   });
});</pre>
<p>Above is an example of a &#8220;promise&#8221;. For more on that, read my <a href="https://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/">Working with jQuery’s AJAX, Promises and Deferred objects.<br />
</a></p>
<h3>13) Retrieving&#8221;Choice Column&#8221; values</h3>
<p>There are times when you want to build an application that requires you to drill down to a choice column, and grab it&#8217;s values. A &#8220;choice column&#8221; in SharePoint is a type of column where you add values for users to choose from.<br />
<img decoding="async" class="alignnone size-full wp-image-6088" src="https://michaelsoriano.com/wp-content/uploads/2016/01/Capture.png" alt="Choice column" width="487" height="190" srcset="https://michaelsoriano.com/wp-content/uploads/2016/01/Capture.png 487w, https://michaelsoriano.com/wp-content/uploads/2016/01/Capture-300x117.png 300w" sizes="(max-width: 487px) 100vw, 487px" /><br />
You retrieve the values by doing an ajax call to the SharePoint REST API endpoint, specifying the column name you want. Below is an example:</p>
<pre class="lang:js decode:true">/_api/web/lists/GetByTitle('LISTNAME')/fields?$filter=EntityPropertyName eq 'Subjects'</pre>
<p>The above will query the choice column &#8220;Subjects&#8221; from the list &#8220;LISTNAME&#8221;.</p>
<h6>**The __metadata object</h6>
<p>You will notice that each result will have this <strong>__metadata</strong> object tied to it.<br />
<img decoding="async" class="alignnone size-full wp-image-5458" src="https://michaelsoriano.com/wp-content/uploads/2016/01/3rd-screenshot-rest.gif" alt="3rd-screenshot-rest" width="492" height="265" /><br />
This contains important material that will help you later in update and delete operations. I&#8217;ll cover that in the next chapter.</p>
<h2><span style="text-decoration: underline;">Bonus: SharePoint Search API</span></h2>
<p>If you have Search features turned on, you will be able to do powerful queries against any of your content inside your SharePoint farm. SharePoint search crawls through your material such as Word documents, Excel, PDF, Lists, Webpages &#8211; anything that you&#8217;ve configured to be searchable &#8211; you can query against in the <strong>SharePoint Search API</strong>.<br />
Your application will go up an extra level &#8211; simply by integrating this capability. Here are a few common Search API calls &#8211; for selecting / querying items:</p>
<h3>1) A Standard Search</h3>
<p>Doing a regular is as simple as passing your search term to the endpoint below:</p>
<pre class="lang:js decode:true">/_api/search/query?querytext='"+ TERM +"'</pre>
<p>The tricky part is parsing the results.<br />
<img decoding="async" class="alignnone wp-image-6090 size-full" style="padding: 20px; border: 1px solid #ebebeb;" src="https://michaelsoriano.com/wp-content/uploads/2016/01/Capture-1.png" alt="Search API result" width="537" height="640" srcset="https://michaelsoriano.com/wp-content/uploads/2016/01/Capture-1.png 537w, https://michaelsoriano.com/wp-content/uploads/2016/01/Capture-1-252x300.png 252w" sizes="(max-width: 537px) 100vw, 537px" /><br />
Are you ready for this? The results are buried under: <strong>data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results</strong></p>
<div>The &#8220;results&#8221; property of &#8220;Rows&#8221; is an array of objects. This contains the data you want to display.</div>
<h3>2) Selecting specific Properties</h3>
<p>At times, you want the payload to remain small. The SharePoint Search API supports selecting only the properties you need. Below is a good way to achieve this:</p>
<pre class="lang:js decode:true">/_api/search/query?querytext='"+ TERM +"'&amp;selectproperties='Title,Path,FileExtension,IsContainer'</pre>
<p>Adding a &#8220;selectproperties&#8221; querystring along with a comma separated properties that we need will do the trick. Again, note the use of single-quotes.</p>
<h3>3) Offsetting Results (for paging)</h3>
<p>For instances where you want to return the set of rows that starts from a specific number:</p>
<pre class="lang:js decode:true">/_api/search/query?querytext='"+ TERM +"'&amp;startrow=10</pre>
<p>Adding the &#8220;startrow&#8221; querystring will do it. Note that SharePoint Search API has a complex algorithm of sorting and returning results. Therefore, the total and the actual values are approximates.</p>
<h3>4) Limiting Results</h3>
<p>You don&#8217;t want to return everything! You simply want to limit your search:</p>
<pre class="lang:js decode:true">/_api/search/query?querytext='"+ TERM +"'&amp;rowlimit=25</pre>
<p>The &#8220;rowlimit&#8221; querystring is your friend.</p>
<h3>5) Only Results from a Specific List or Document Library</h3>
<p>This one you will need the list Id. You can grab the list Id by going to your list / library, and clicking on &#8220;List Settings&#8221; or &#8220;Library Settings&#8221;. Once there, go to the URL and grab the value after &#8220;List=&#8221;. Note that this value is url encoded &#8211; with single quotes. So remove the leading &#8220;%7B&#8221;, and the trailing &#8220;%7D&#8221;. What you&#8217;re left with is the List Id.</p>
<pre class="lang:js decode:true">/_api/search/query?querytext='"+ TERM +"'&amp;sourceid='YOUR-LIST-ID'</pre>
<p>Remember to wrap your list id in single quotes. This query will only return items from the specific list that you&#8217;ve specified.</p>
<h3>6) Get People Results</h3>
<p>For this one, it&#8217;s exacly the same as above.</p>
<pre class="lang:js decode:true">/_api/search/query?querytext='"+ TERM +"'&amp;sourceid='b09a7990-05ea-4af9-81ef-edfab16c4e31'</pre>
<p>Simply replace the list id with this: &#8220;<strong>b09a7990-05ea-4af9-81ef-edfab16c4e31</strong>&#8220;. Yes it seems like it&#8217;s the same for everybody.</p>
<h3>7) Getting Best Bets</h3>
<p>&#8220;Best Bets&#8221; is SharePoint&#8217;s &#8220;elevated results&#8221;. These get pushed to the top of the result set, for specific queries. Note that these items are not included in the regular results &#8211; which means that it is not to be included in paging and filters and such.</p>
<pre class="lang:js decode:true">/_api/search/query?querytext='"+ TERM +"'&amp;processbestbets=true&amp;enablequeryrules=true</pre>
<p>The resultset you need to parse is in this property: <strong>data.d.query.SecondaryQueryResults.results[0].SpecialTermResults.Results.results</strong><br />
Haha! Ugly eh? Inside &#8220;results&#8221; is an array of objects you need. Note that the properties of each object may not be as complete as the primary results.</p>
<h3>8) Filtering Results</h3>
<p>Sometimes you don&#8217;t want the whole resultset to comeback. This is where filtering comes in. <strong>SharePoint Search API</strong> has &#8220;refinement filters&#8221; which does the job.</p>
<pre class="lang:default decode:true">/_api/search/query?querytext='TERM'&amp;refinementfilters='(FIELD:string("FILTERTERM", mode="phrase")'</pre>
<p>The above will search for &#8220;TERM&#8221;, filtered with the &#8220;FILTERTERM&#8221;  in the field called &#8220;FIELD&#8221;.</p>
<h3>9) Filtering Results in Multiple Fields</h3>
<p>So now we need to filter by many fields. Yes it&#8217;s possible, and we still use &#8220;refinement filters&#8221; in the Search API.</p>
<pre class="lang:default decode:true ">/_api/search/query?querytext='TERM'&amp;refinementfilters='and(COL1:string("COL1TERM", mode="phrase"),COL2:string("COL2TERM", mode="phrase"))'</pre>
<p>Just like the single filter, but instead we add &#8220;and&#8221; in the beginning (you can also use &#8220;or&#8221;), plus separating the columns and terms with a comma.</p>
<h3>10) Sorting Results</h3>
<p>At times, the sorting of SharePoint&#8217;s Search API is not what you&#8217;re looking for. Well we can sort it.</p>
<pre class="lang:default decode:true ">/_api/search/query?querytext='TERM'&amp;sortlist='LastName:ascending,FirstName:ascending'</pre>
<p>The example above shows the results being sorted by &#8220;LastName&#8221;, ascending first, then &#8220;FirstName&#8221; etc.</p>
<h3>Conclusion</h3>
<p>As I&#8217;ve mentioned, SharePoint&#8217;s REST AND SEARCH API has some very powerful features. And with OData&#8217;s standard&#8217;s, you can create quite advanced queries. I will try to keep this article updated with more <strong>Select</strong> related queries, but for now I have to go. Stay tuned for the next part.</p>
<p>The post <a href="https://michaelsoriano.com/understanding-sharepoint-rest-api-part-1-selecting-items/">Understanding SharePoint&#8217;s REST and Search API Part 1 &#8211; Selecting Items</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/understanding-sharepoint-rest-api-part-1-selecting-items/feed/</wfw:commentRss>
			<slash:comments>35</slash:comments>
		
		
			</item>
	</channel>
</rss>
