Posts Tagged ‘REST’

SP 2013: Searching in SharePoint 2013 using the REST new API’s

December 26th, 2012 by Tobias Zimmergren

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

Search has always been a great way to create custom solutions that aggregate and finds information in SharePoint. With SharePoint 2013, the search capabilities are heavily invested in and we see a lot of new ways to perform our searches. In this post I’ll show a simple example of how you can utilize the REST Search API’s in SharePoint 2013 to perform a search.

REST Search in SharePoint 2013

So in order to get started, we’ll need to have an ASPX Page containing some simple markup and a javascript file where we’ll put our functions to be executed. The approach mentioned in this post is also compatible with SharePoint Apps, should you decide to develop an App that relys on Search. In my example I’ve created a custom Page which loads my jQuery and JavaScript files, and I’m deploying those files using a Module to the SiteAssets library.

Preview of the simple solution

image

Creating a Search Application using REST Search Api’s

Let’s examine how you can construct your search queries using REST formatting and by simply changing the URL to take in the proper query strings.

Formatting the Url

By formatting the Url properly you can retrieve search results pretty easily using REST.

Query with querytext

If you simply want to return all results with no limits or filters from a search, shoot out this formatted url:

http://tozit.dev/_api/search/query?querytext=’Awesome’

will yield the following result:

image_thumb[1]

Essentially we’re getting a bunch of XML returned from the query which we then have to parse and handle somehow. We can then use the result of this query in our application in whatever fashion we want. Let’s see what a very simple application could look like, utilizing the SharePoint 2013 rest search api’s.

ASP.NET Markup Snippet

As we can see in the following code snippet, we’re simply loading a few jQuery and JavaScript files that we require and we define a Search Box and a Button for controlling our little Search application.

<!-- Load jQuery 1.8.3 -->
<script type="text/javascript" src="/SiteAssets/ScriptArtifacts/jquery-1.8.3.min.js"></script>

<!-- Load our custom Rest Search script file -->
<script type="text/javascript" src="/SiteAssets/ScriptArtifacts/RestSearch.js"></script>

<!-- Add a Text Box to use as a search box -->
<input type="text" value="Awesome" id="searchBox" />

<!-- Add a button that will execute the search -->
<input type="button" value="Search" onclick="executeSearch()" />

<div id="searchResults"></div>

JavaScript logic (RestSearch.js)

I’ve added a file to the project called RestSearch.js, which is a custom javascript file containing the following code which will perform an ajax request to SharePoint using the Search API’s:

// in reality we should put this inside our own namespace, but this is just a sample.
var context;
var web;
var user;

// Called from the ASPX Page
function executeSearch()
{
    var query = $("#searchBox").val();

    SPSearchResults =
    {
        element: '',
        url: '',

        init: function(element) 
        {
            SPSearchResults.element = element;
            SPSearchResults.url = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + query + "'";
        },

        load: function() 
        {
            $.ajax(
                {
                    url: SPSearchResults.url,
                    method: "GET",
                    headers:
                    {
                            "accept": "application/json;odata=verbose",
                    },
                    success: SPSearchResults.onSuccess,
                    error: SPSearchResults.onError
                }
            );
        },

        onSuccess: function (data)
        {
            var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;

            var html = "<div class='results'>";
            for (var i = 0; i < results.length; i++)
            {
                var d = new Date(results[i].Cells.results[8].Value);
                var currentDate = d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();

                html += "<div class='result-row' style='padding-bottom:5px; border-bottom: 1px solid #c0c0c0;'>";
                var clickableLink = "<a href='" + results[i].Cells.results[6].Value + "'>" + results[i].Cells.results[3].Value + "</a><br/><span>Type: " + results[i].Cells.results[17].Value  + "</span><br/><span>Modified: " + currentDate + "</span>";
                html += clickableLink;
                html += "</div>";
            }

            html += "</div>";
            $("#searchResults").html(html);
        },

        onError: function (err) {
            $("#searchResults").html("<h3>An error occured</h3><br/>" + JSON.stringify(err));
        }
    };

    // Call our Init-function
    SPSearchResults.init($('#searchResults'));

    // Call our Load-function which will post the actual query
    SPSearchResults.load();
}

The aforementioned script shows some simple javascript that will call the Search REST API (the "_api/…" part of the query) and then return the results in our html markup. Simple as that.

Summary

By utilizing the REST Search API we can very quickly and easily create an application that searches in SharePoint 2013.

This can be implemened in SharePoint Apps, Sandboxed Solutions or Farm Solutions. Whatever is your preference and requirements, the Search API’s should be easy enough to play around with.

Enjoy.

Introduction

As most if not all of you already know, SharePoint 2013 and Office 2013 has been released to preview/beta and is available for download from Microsoft’s download centers. In this article I will briefly introduce some exciting changes that has been made to the SharePoint 2013 Business Connectivity Services framework. I’ve written a bunch of articles on BCS for SharePoint 2010, and now it’s time to continue that track and introduce the new features available in SharePoint 2013.

Please note that this article is written for SharePoint 2013 Preview, and for the final version of SharePoint some details may have changed

  1. SharePoint 2013: Business Connectivity Services – Introduction
  2. SharePoint 2013: Business Connectivity Services – Consuming OData in BCS Using an App External Content Type
  3. SharePoint 2013: Business Connectivity Services – Talking to your external lists using REST
  4. SharePoint 2013: Business Connectivity Services – Client Object Model
  5. SharePoint 2013: Business Connectivity Services – Events and Alerts

SharePoint 2013 – BCS with REST

In this article we’ll be taking a further look on the new Business Connectivity Services changes and additions in SharePoint 2013. I want to take a quick look and introduce how REST (Representational State Transfer) can be used and also how the Client Object Model can be utilized to communicate with your External Lists and BCS Entities.

So without further delays, let’s dig into the fantastic world of BCS and CSA (Client Side Awesomeness).

Important: The project type in this project, as mentioned in the post where we started building our sample, is a SharePoint-hosted app.

Business Connectivity Services and REST

Utilizing REST in BCS in your SharePoint 2013 environments isn’t really that big of a deal. It’s pretty straight forward. The first thing you should do is take a look at the following link which references the MSDN article about getting started with REST in SharePoint 2013.

MSDN Reference: http://tz.nu/QXfooY

So now that we know that REST is all about, we’re going to look at some code that will utilize REST to retrieve some data. In this sample I’ll continue to build on the solution I created in the previous article.

Final result will look like this

When our first snippet of code will be done, it’ll look something like this where our (in this case) App (page) is loaded:

image

So what the code will do is to pull out the images and links for the videos in the Telerik.Tv OData data source that we created in the previous article, and we’ll be doing this using the REST API’s.

In one big snippet, here’s what the REST call looks like in my App.js:

var context;
var web;
var user;

function sharePointReady()
{
    var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/lists/getbytitle('Video')/items";
    jqxhr = $.getJSON(requestUri, null, onSuccessfullJSONCall);
    jqxhr.error(onErrorInJSONCall);
}

function onSuccessfullJSONCall(data) {

    var outputHtml = "";
    var results = data.d.results;
    var counter = 0;
    for (var i = 0; i < results.length; i++) {
        outputHtml += "<img src='" + results[i].ImageUrl + "' class='brick-image' />";
        counter++;

        if (counter >= 4) {
            outputHtml += "<br/>";
            counter = 0;
        }
    }

    $("#message").html(outputHtml);
}

function onErrorInJSONCall(err) {
    $("#message").text("Unawesome Error: " + JSON.stringify(err));
}

As you can see in the aforementioned code snippet, the calls to the REST API’s are pretty straight forward and I’m only making a quick call to fetch the data asynchronously using the $.getJSON() method.

Lets break it down in sections..

Script part 1: sharePointReady() method call

Since our project type (a SharePoint-hosted App) contains a stub for the Default.aspx page and the App.js files – a method called sharePointReady is defined in the App.js file and in the Default.aspx you have the following block which initiates the call to this method upon loading all other required awesome things:

    <!-- The following script runs when the DOM is ready. The inline code uses a SharePoint feature to ensure -->
    <!-- The SharePoint script file sp.js is loaded and will then execute the sharePointReady() function in App.js -->
    <script type="text/javascript">
        $(document).ready(function () {
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () { sharePointReady(); });
        });
    </script>

(Optionally, you can put this code-block in the actual App.js file as well if you’d like – it’s up to you)

When SharePoint is done loading all the required stuff that it needs to function (sp.js), this method is executed. In this sample, I’m making a simple JSON call to the REST API using the syntax http://url/_api/lists/getbytitle(‘ListTitle’)/items which will get all list items in the list named Video:

function sharePointReady()
{
    var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/lists/getbytitle('Video')/items";
    jqxhr = $.getJSON(requestUri, null, onSuccessfullJSONCall);
    jqxhr.error(onErrorInJSONCall);
}

Script part 2: On successful JSON callback, the following block is executed

We’re executing the onSuccessfullJSONCall() when our previous call is successful, and it’ll basically just parse the JSON result and push the items out in a simple HTML structure:

function onSuccessfullJSONCall(data) {

    var outputHtml = "";
    var results = data.d.results;
    var counter = 0;
    for (var i = 0; i < results.length; i++) {
        outputHtml += "<img src='" + results[i].ImageUrl + "' class='brick-image' />";
        counter++;

        if (counter >= 4) {
            outputHtml += "<br/>";
            counter = 0;
        }
    }

    $("#message").html(outputHtml);
}

Script part 3: In case of unawesomeness (failure)

In case the request failed, we’ll be handling that somehow in this method. In this case we’ll just be printing out the error message very quickly to the user:

function onErrorInJSONCall(err) {
    $("#message").text("Unawesome Error: " + JSON.stringify(err));
}

Summary

In this article we took a very quick look at how to get that first REST call working with SharePoint 2013 against our External List called “video”. With the returned result in JSON, we’re parsing it out and simply rendering the result in a more reader-friendly manner as pictures in a simple HTML grid.

So that’ll be it for the REST calls for now. It should get you started and set-up for creating a very simple application that utilizes REST for retrieving data from SharePoint.

More details on working with the REST API’s in SharePoint 2013 will follow later, including how to perform cross-domain queries.

Enjoy.