Friday, September 9, 2016

Custom Search Apps Using REST API in SharePoint 2013


 In this post we will see Custom Search App using SharePoint 2013 Search and REST API

To start create Custom Search app following Prerequisites.
1.      App Development Environment must be configured.
2.      SharePoint 2013 Search Service Application must be created and configured.

3.      Sample Data Sources must be created within the Scope targeted by the crawler.

4.      Full Crawl must be finished.

5.     Also Fiddler Web Proxy to be installed. We will Fiddler from

http://www.telerik.com/download/fiddler

Follow steps in the creation of Custom Search App using REST API:-


1. Open Visual Studio 2013 and create new project using template “App for SharePoint 2013".

 

App for SharePoint 2013

 

2. Design the Default.aspx Page and write the user interface for Custom Search App. Here we are using just simple HTML.


  <table>

        <tr>
        <th>Working with Search CSOM and REST API</th>
        </tr>
        <tr>
            <td><input id="btnExecuteSearchREST" type="button" value="Execute Search using REST API" class="btn" /></td>
        </tr>
    </table>

3 .After design Default.aspx to link the “Click” event of the button “btnExecuteSearchREST” with an event handler function:

   $(document).ready(function () {


           $("btnExecuteSearchREST").click(executeSearchREST);
          

       });

4.   Code details

  function executeSerchREST() {

           var queryText = jQuery('#txtSearch').val();
           var headers = {
               Accept: "application/json;odata=verbose"
           };
           var call = jQuery.ajax({
               url: _spPageContextInfo.webAbsoluteUrl
               + "/_api/Search/query?querytext='" + queryText + "'",
               type: "GET",
               data: "json",
               headers: headers
           });
           call.done(function (data, textStatus, jqXHR) {

               var message = jQuery("#message");
               message.text("Search Results for \"" + queryText + "\"");
               message.append("<br/>");

               var rows = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
               jQuery.each(row, function (index, value) {

                   var title = jQuery.grep(value.Cells.results, function (item, index) {
                       return item.Key == "Title";
                   });
                   var path = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
                   jQuery.each(row, function (index, value) {

                       var title = jQuery.grep(value.Cells.results, function (item, index) {
                           return item.Key == "Path";
                       });

                       message.append(title[0].value + ":" + path[0].value);
                       message.append("<br/>");
                   });
               });
               call.fail(failHandler);
           });
       }

1.      Store the Search text provide by the user in the variable "queryText".


2.      Define Request Headers for the Web Request, and "odata=verbose" as a part of the value for "Accept" Property, this is a new convention for Web Requests using REST API in SharePoint 2013 and it must be followed otherwise it will give following error :

 

Error

 

3.     Set "url" to the URL of the site hosting this App using "_spPageContextInfo.webAbsoluteUrl", we should have to remember object as we have to use it on every page in SharePoint where we will use the SharePoint Context. This Object provides you a lot of useful information to work.

objects

 

4.  Now Specify the Search Query using new End Point (_api/search/query/<searchTerm>) provided by SharePoint 2013.


5. Save result of response object to “rows” variable, based on data structure fetch by response object. We can identify the data structure by analyzing the response object using Fiddler Web Proxy as shown after few steps down the line.

6.      We need to go through the result set to read the Values based on the Keys returned.

7.      Finally we display the records as required.

Note: Here we can make use of some of the JavaScript Frameworks "Knockout.js" based on MVVM Pattern and has an excellent feature of dependency tracking, which allows you to write complex UI logic with much Lesser & Cleaner Code. More about  http://learn.knockoutjs.com/.

5. Now we have done coding and in order to test the Custom Search App, first verify the Data Source which contains the data related to our search term. In our case it is “Customers” List with a Column "ContactTitle" containing the Search Term "Owner"

 

Search

 

Now specify the search term in textbox provided as a part of App UI and click "Execute Search using REST API":

App UI

 

 

We should have to analyze the response object to know what exactly getting from server against our request.


If we view the response object in Fiddler, we will see a complete JSON Object containing the data in terms of Key/Value Pairs. This is very important information as this will help to navigate the result set that we are interested in. We will use this information under4 Point 5, where we will the result set from response object to local variable.

 

Search results

Results Key

 

At last if we see to the Result Panel we should be able to get the results based on the search "Owner".

Search result
                              
                              Microsoft Refrence


Thank you very much

          Fahadullah Karimi

         SharePoint Specialist



Create External list using Business Data Connectivity in SharePoint 2013 List WorkFlow Vs Reusable WokFlow Vs Site WorkFlow

1 comment:

  1. Sharepoint Tips And Tricks: Custom Search Apps Using Rest Api In Sharepoint 2013 >>>>> Download Now

    >>>>> Download Full

    Sharepoint Tips And Tricks: Custom Search Apps Using Rest Api In Sharepoint 2013 >>>>> Download LINK

    >>>>> Download Now

    Sharepoint Tips And Tricks: Custom Search Apps Using Rest Api In Sharepoint 2013 >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete