Monday, August 04, 2014

REST API SharePoint hosted App - Part 1

This post intended for the beginners who wanted to start and learn the REST API in SharePoint app model using JavaScript Object Model (JSOM).

Advantages of using REST API in SharePoint app.

  • You do not require to add any assemblies to your project.
  • Its purely based on SharePoint related supporting java script files.
  • REST API can be used in non Microsoft technologies such as Android and iOS on building the mobile application which needs to be access the SharePoint resources.
  • Supports the cross - domain library call with few lines of code while comparing server side object model.

What is cross domain library ?

Nowadays all browsers enforcing the multiple security policies,restricting the access to different domain call is core features is one of them.

Just think of mash ups application (gathering information from different sources and aggregating and showing in the page or web parts) . It could be dash board in SharePoint.
But in SharePoint app models, all apps running out side of the SharePoint contexts that is baseline for all SharePoint apps. It could be remote web,Windows Azure or Client side.

When you publish or deploy the apps, SharePoint will generate the unique domain for each of your apps with GUID identifiers.
Example

https://codethinker-c83df5dbb5c7ed.sharepoint.com/sites/appsdemo/


app domain : codethinker-c83df5dbb5c7ed
SharePoint domain : SharePoint.com
site collection : appsdemo.


[*Note:- in below example, I am trying to connect the list named friends from the app domain which is located in the SharePoint domain]


So your SharePoint needs to authorize your  apps even though browser restricts the "Cross domain call",SharePoint manage the proxy call using the file  RequestExecute.js file in the  15 hive folder.
You have to pass the app domain URL and hosting web URL parameters to the javascript class SP.RequestExecutor to overcome the cross domain call restrictions in your browsers.

Connecting your SharePoint App through REST API request.

Requirements.

  1. First log on your Office 365 site and create the new site collection based on "Developer Site" template.In later series,I cover the topic "Why you need the developer site to publish the SharePoint apps ?

Open your visual studio New Project ->Select the Apps project template under Office /SharePoint category and choose the "Apps for SharePoint"




In your project explorer open the App.js file and copy the below code snippets.

var appUrl;
var hostWebUrl;
// Reading the query string from the URL
function getQueryStringParameter(param) {
    var params = document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == param) {
            return singleParam[1];
        }
    }
}

$(document).ready(function () {
    appUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

    hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    //cross domain library
        $.getScript(hostWebUrl + "/_layouts/15/SP.RequestExecutor.js",connectREST);
});


function connectREST()
{
 var url = appUrl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Friends')/items?@target='" + hostWebUrl + "'";
var executor = new SP.RequestExecutor(appUrl);
executor.executeAsync({
url: url,
method: "GET",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
$("#message").html("App connected");
},
error: function (data) {
$("#message").html("To know more about this exception ,hit F12 and analyse the network transmission");
        }
    });
}

When you are working with ajax method in jQuery,there could be chances in constructing incorrect syntax that could lead to result different html status codes such as BAD request (400),Partial Information (203),Accepted (201),No Response (204) and etc.

To overcome these problem its always better to remind the Http Response header key/value.
Accept
application/json; odata=verbose

Accept-Language
en-US
Cache-Control
no-cache
Connection
Keep-Alive
Content-Type
application/json;odata=verbose
Cookie
WSS_FullScreenMode=false
Host
win-g3u94jerf1t

X-RequestDigest
X-RequestDigest value (scrambled)
Request
POST /_api/web/lists/getbytitle('Friends')/items HTTP/1.1

Source download link http://1drv.ms/1odDgtA

When you run this project,you will get the "Access denied error" in script log.
Because the currently logged in user have permission on the site collection,but
your doesn't have permission to access the list "Friends" in the host web.

I covered this topic in the next part : http://intelliview.blogspot.in/2014/08/rest-api-sharepoint-app-permission-part.html