SharePoint Search REST API with Example

In this tutorial, I show you how to fetch data from the SharePoint Search REST API with Example. We look at how to use different methods, parameters that search rest API support –

SharePoint Search Rest API with Example

SharePoint Search is very power full and enables users to find relevant data based on their search query. Search indexed the content of site like – Site collection, Subwebs, List, Library, documents, folders, people profiles in SharePoint itself.

Search not only indexes the sites, documents, files but also indexed the metadata associated with them and this metadata includes – site title, author, created date, URL, count, etc.

There are various APIs provided by search to fetch data from SharePoint and populate the same on SharePoint UI. In this tutorial, I show you how to use SharePoint search REST API with some examples.

Before we see any search REST API example let first understand what SharePoint search returns into search results if a user query something. The search results only return the content which user have access to this is called security trimming in SharePoint context.

SharePoint Search REST API Methods –

Search service supports HTTP get and HTTP Post requests.

SharePoint Search REST API Get Request –

<url>/_api/search/query

Example –

var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var url = siteUrl + "/_api/search/query?querytext='contentclass:STS_Site'&rowlimit=500&TrimDuplicates=false&selectproperties='SiteTitle,Url'&sortlist='created:descending'"
$j.ajax({
  url: url,
  method: "GET",
  headers: { "Accept": "application/json; odata=verbose" },
  success: function (data) {
   var resultsColl = data.d.query.PrimaryQueryResult.RelevantResults;
   // manipulate the resultsColl as per requirement
   var resultsCollCount = data.d.query.PrimaryQueryResult.RelevantResults.RowCount;
   // in case you need results Count
},
error: function (data) {
  console.log("exception in search result call");
}
});

In the above example, I have fetched all the site collection exist in SharePoint. I have passed the below parameter to the search REST API call. Make sure you change the site URL value with your site.

1.querytext –

STS_Site indicated that I request for site collections only and if you need subsites you can pass STS_Web and if you required site collection and sub sites both then pass both like below

'contentclass:STS_Site contentclass:STS_Web'

2.RowLimit –

Limit the number of items returned by the query. Max 500 items are returned at a time by a single call if you pass 10 it returns 10 items if you pass nothing it returns 500 items by default.

If you want to fetch all the available items, it is recommended to pull them in batches of 500.

3.TrimDuplicates –

it an Optional attribute specifying how many items to keep for each set of duplicates. The default value is true.

4.selectproperties –

Pass the name of the field which you want to retrieve instead of all.

5. Sortlist –

Sorted the search result, in the above example, I have sorted the items based on the created date the lasted one come on top.

There are a few other parameters as well which you can use based on your requirement to filter out the search results.

SharePoint Search REST API POST Request –

<url>/_api/search/postquery

Example –

$.ajax(
{
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $j("#__REQUESTDIGEST").val()
},
data: JSON.stringify(postData),
url: _spPageContextInfo.webAbsoluteUrl + "/_api/search/postquery",
success: onQuerySuccess,
error: onQueryFail
});
function onQuerySuccess(data) {
 var results = data.d.postquery.PrimaryQueryResult.RelevantResults;
 // manipulate the resultsColl as per requirement
}
function onQueryFail(data) {
console.log("exception in search result post call");
}

The POST request has been passed in JSON format. The HTTP POST request of the Search REST service supports all parameters supported by the HTTP GET Request.

Here in the above example, I have fetched all existing site collections you can also use List and Document Library to fetch its items use List or Library ID in query text like below –

queryText = "ListId:039520V4-288B-4V26-T55E-C7752E1E4PAD AND Title: Test*";

It fetches all the items of the given List or Library where Title value starts from Test.

SharePoint Search REST API is ideal to use for client-side modern web parts. It always returns the JSON so you have to parse the result and manipulate it as per the requirement.

Conclusion

This is how you can fetch the search result set using the SharePoint Search REST API and bind the same on UI.

I hope this is helpful.