Sunday 24 September 2017

Rest API Implementation Basics in SharePoint

REST API is a great new addition in SharePoint. Let's assume a scenario for the implementation.


Scenario: 

Suppose on a page/webpart you have a button which you want to show to users belonging to a particular group only. How to implement this in REST. 

$(document).ready(function(){
    HandleButtonHiding();
});

var hideDelete = true;

function  HandleButtonHiding () {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/CurrentUser",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            //Now Get all Groups to iterate
            getCurrentUserGroupColl(data.d.Id);
        },
        error: function (data) {
            failure(data);
        }
    });

}

function getCurrentUserGroupColl(UserID) {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetUserById(" + UserID + ")/Groups",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            /* get all group's title of current user. */
            var results = data.d.results;
            for (var i = 0; i < results.length; i++) {
                var grpTitle = results[i].Title;
                if (grpTitle.indexOf("Your Group Title") != -1) {
                       hideDelete = false;
                    break;
                }
            }
               if(hideDelete){
                  $('button#xyz').css("display","none");
               }
        }
    });

No comments:

Post a Comment