This post was most recently updated on July 31st, 2024
Hello
Today we will cover SharePoint Search with REST API. In this tutorial, I will explain SharePoint Search API with the Query Text parameter. In my next article, I will cover Query parameters with different data types like SelectProperties, RefinementFilters, Properties etc. The Search REST service supports both HTTP POST and HTTP GET requests. We will cover both requests. You can use the Search REST service to submit Keyword Query Language (KQL) or FAST Query Language (FQL) queries. Free text-keywords—words or phrases.
Before we go ahead I recommended you to download the SharePoint Search Query Tool. This tool will help to build an HTTP search query and debug search queries. You can also try different data types of query parameters. It can be used to query both SharePoint 2013/2016 On-Premise and SharePoint Online.
The tool has multiple authentication methods Sharepoint online, WIndows, From based and forefront gateway.
After running the HTTP search query, you can view all types of result sets returned; Primary Results, Refinement Results, Query Rules Results, Query Suggestions, in addition to the actual raw response received from the Search service.
See the below screenshot for more info.
GET requests
Construct the URL for query GET requests to the Search REST service as follows:
https://[your site url]/_api/search/query
For GET requests, you specify the query parameters in the URL. You can construct the GET request URL in two ways:
https://[your site url]/_api/search/query?query_parameter=value&query_parameter=value
https://[your site url]/_api/search/query(query_parameter=value&query_parameter=<value>)
POST requests
You can construct the URL for query POST requests to the Search REST service as follows:
https://[your site url]/_api/search/postquery
Endpoint | |
GET requests | POST requests |
https://[your site url]/_api/search/query?querytext=sharepoint | https://[your site url]/_api/search/postquery |
I used SP.RequestExecutor object (sp.requestexecutor.js) for a Web request to the server and get a response from the server. I just added two different code snippet for GET and POST method which will call on jQuery click event. I just get only search results “Title” and “Link” values, both are the simple examples.
Both requests have a different response object. You can add column name to return specific column in “selectproperties”.
GET Method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
var siteurl = _spPageContextInfo.webAbsoluteUrl; //MAKE GLOBAL $(document).ready(function () { //SEARCH CLICK $("body").on('click', '.your_search_btn_class', function (e) { e.preventDefault(); var inputSearchValue = $('.your_search_input').val(); getTheSearchResult(inputSearchValue); }); }); function getTheSearchResult(searchTerm) { var executor = new SP.RequestExecutor(_spPageContextInfo.webAbsoluteUrl); var searchQueryURL = siteurl + "/_api/search/query?querytext='" + searchTerm + "'"; executor.executeAsync({ url: searchQueryURL, method: "GET", async: false, headers: {"Accept": "application/json; odata=verbose"}, contentType: "application/json; odata=verbose", success: onGetSearchResultsSuccess, error: onGetSearchResultsFail }); } function onGetSearchResultsSuccess(data) { var jsonObject = JSON.parse(data.body); var relevantResults = jsonObject.d.query.PrimaryQueryResult.RelevantResults; var results = relevantResults.Table.Rows.results;//GET THE ALL RESULTS var totalRows = relevantResults.TotalRows; //TOTAL RETURN RESULTS var getMethodSearchResultsHtml = '', title = '', link = ''; if (relevantResults.RowCount === 0) {//CHECK IF SEARCH RESULT RETURN ANY ITEM //NO RECORD FOUND } else { $.each(results, function (index, result) { title = result.Cells.results[2].Value; link = result.Cells.results[3].Value; getMethodSearchResultsHtml += "<div class='resultItem'>"; getMethodSearchResultsHtml += "<a target='_blank' href='" + link + "'>" + title + "</a>"; getMethodSearchResultsHtml += "</div>"; }); $('.SP-resultsWrapper').html(getMethodSearchResultsHtml);//ADD RETURN DATA TO ELEMENT } } function onGetSearchResultsFail(data, errorCode, errorMessage) { console.log(errorMessage); } |
Below screenshot shows the search results of GET method response object.
POST method
For POST requests, you can pass the query parameters in the request in JavaScript Object Notation (JSON) format.
The HTTP POST version of the Search REST service supports all parameters supported by the HTTP GET version. However
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
var siteurl = _spPageContextInfo.webAbsoluteUrl; //MAKE GLOBAL $(document).ready(function () { //SEARCH CLICK $("body").on('click', '.your_search_btn_class', function (e) { e.preventDefault(); var inputSearchValue = $('.your_search_input').val(); getTheSearchResult(inputSearchValue); }); }); function getTheSearchResult(searchTerm) { var executor = new SP.RequestExecutor(_spPageContextInfo.webAbsoluteUrl); var searchQuery = { 'request': {'Querytext': SearhcTerm} }; executor.executeAsync({ method: 'POST', async: false, url: siteurl + "/_api/search/postquery", headers: { "Accept": "application/json", "Content-Type": "application/json", "X-RequestDigest": $("#__REQUESTDIGEST").val() }, body: JSON.stringify(searchQuery), //USED BODY INSTEAD DATA success: onGetSearchResultsSuccess, error: onGetSearchResultsFail }); } function onGetSearchResultsSuccess(data) { var jsonObject = JSON.parse(data.body); var relevantResults = jsonObject.PrimaryQueryResult.RelevantResults; var results = relevantResults.Table.Rows;//GET THE ALL RESULTS var totalRows = relevantResults.TotalRows; //TOTAL RETURN RESULTS var postSearchResultsHtml = '', title = '', link = ''; if (relevantResults.RowCount === 0) {//CHECK IF SEARCH RESULT RETURN ANY ITEM //NO RECORD FOUND } else { $.each(results, function (index, result) { title = result.Cells[3].Value; link = result.Cells[6].Value; postSearchResultsHtml += "<div class='resultItem'>"; postSearchResultsHtml += "<a target='_blank' href='" + link + "'>" + title + "</a>"; postSearchResultsHtml += "</div>"; }); $('.SP-resultsWrapper').html(postSearchResultsHtml);//ADD RETURN DATA TO ELEMENT } } function onGetSearchResultsFail(data, errorCode, errorMessage) { console.log(errorMessage); } |
Below screenshot shows the search results of POST method response object.
In my next article, I will explain different data types like SelectProperties, RefinementFilters, Properties with an example.
Hope you find it helpful. If you liked this article, then please share and comment. Your comment and suggestion will be greatly appreciated.
This article looks great. could you also talk about the authentication mechanism. i want to use these api calls from .net core application. what are the things i need to create to get access to my sharepoint site. i am more looking towards a token with app id and secret rather than user token. let me know. thank you
Hi Vishwanadha,
The web application is running on a different domain then SharePoint and then you’ll face cross-domain issues. There are a few approaches to solve this:
1.CORS (Cross-origin resource sharing)
2.JSONP (JSON with padding)
3.IFrame with PostMessage API
4. Use CSOM for Search
In order to use any manipulation in SharePoint you must obtain an access token.
Read this articles https://www.vlieshout.net/how-to-gather-data-from-sharepoint-using-rest-api-on-external-website/
https://www.techsupper.com/2019/05/access-sharepoint-online-rest-apis.html