Ads

Showing posts with label REST. Show all posts
Showing posts with label REST. Show all posts

Friday, 7 April 2017

REST with Search in SharePoint

In SharePoint 2013, There are few REST end points which are used to retrieve search results.
  • Site Coll Url.../_api/search/query
  • Site Coll Url.../_api/search/postquery
  • Site Coll Url.../_api/search/suggest
Below are few search URLs to query search results..
Set maximum number of record to return
/_api/search/query?querytext='search term'&rowlimit=100
Set index of start row
/_api/search/query?querytext='search term'&startrow=11
Specify a number of results to return
/_api/search/query?querytext='search term'&startrow=11&rowlimit=10 (but note 10 is the default)
Specifies the list of properties to sort the search results by.
/_api/search/query?querytext=’terms’&sortlist= ‘Title:ascending’
Specify particular (managed) properties to return
/_api/search/query?querytext='search term'&selectproperties='Author,Path,Title'
Use a search Result Source (i.e. a scope)
/_api/search/query?querytext='search term'&sourceid='B09A7990-05EA-4AF9-81EF-EDFAB16C4E31' (this ex. is to search the ‘People’ result source)

In above table, The last one is used to query results from any document library which GUID is passed as sourceid in search query URL. We can also replaced this ID with other GUIDs given below to get the result from specific result sources.

Result Source
ID
Documents
e7ec8cee-ded8-43c9-beb5-436b54b31e84
Items matching a content type
5dc9f503-801e-4ced-8a2c-5d1237132419
Items matching a tag
e1327b9c-2b8c-4b23-99c9-3730cb29c3f7
Items related to current user
48fec42e-4a92-48ce-8363-c2703a40e67d
Items with same keyword as this item
5c069288-1d17-454a-8ac6-9c642a065f48
Local People Results
b09a7990-05ea-4af9-81ef-edfab16c4e31
Local Reports And Data Results
203fba36-2763-4060-9931-911ac8c0583b
Local SharePoint Results
8413cd39-2156-4e00-b54d-11efd9abdb89
Local Video Results
78b793ce-7956-4669-aa3b-451fc5defebf
Pages
5e34578e-4d08-4edc-8bf3-002acf3cdbcc
Pictures
38403c8c-3975-41a8-826e-717f2d41568a
Popular
97c71db1-58ce-4891-8b64-585bc2326c12
Recently changed items
ba63bbae-fa9c-42c0-b027-9a878f16557c
Recommended Items
ec675252-14fa-4fbe-84dd-8d098ed74181
Wiki
9479bf85-e257-4318-b5a8-81a180f5faa1








Friday, 17 February 2017

REST API to get user news feeds in SharePoint 2013

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
var feedManagerEndpoint;

$(document).ready(function () {
    var appweburl;
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var param = params[i].split("=");
        if (param[0] === "SPAppWebUrl") appweburl = param[1];
    }
    feedManagerEndpoint = decodeURIComponent(appweburl)+ "/_api/social.feed";
    postToMyFeed();
});

function postToMyFeed() {
    $.ajax( {
        url: feedManagerEndpoint + "/my/Feed/Post",
        type: "POST",
        data: JSON.stringify( {  
            'restCreationData':{
                '__metadata':{  
                    'type':'SP.Social.SocialRestPostCreationData'
                },
                'ID':null,  
                'creationData':{  
                    '__metadata':{  
                        'type':'SP.Social.SocialPostCreationData'
                    },
                'ContentText':'This post was published using REST.',
                'UpdateStatusText':false
                }  
            }  
        }),
        headers: {  
            "accept": "application/json;odata=verbose",
            "content-type":"application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: getMyFeed,
        error: function (xhr, ajaxOptions, thrownError) {  
            alert("POST error:\n" + xhr.status + "\n" + thrownError);
        }
    });
}

function getMyFeed() {
    $.ajax( {
        url: feedManagerEndpoint + "/my/Feed",
        headers: {  
            "accept": "application/json;odata=verbose"
        },
        success: feedRetrieved,
        error: function (xhr, ajaxOptions, thrownError) {  
            alert("GET error:\n" + xhr.status + "\n" + thrownError);
        }
    });    
}

function feedRetrieved(data) {
    var stringData = JSON.stringify(data);
    var jsonObject = JSON.parse(stringData);  
    var feed = jsonObject.d.SocialFeed.Threads;  
    var threads = feed.results;
    var newscontent = "";
    for (var i = 0; i < threads.length; i++) {
        var thread = threads[i];
        var participants = thread.Actors;
        var owner = participants.results[thread.OwnerIndex].Name;
        newscontent += '<p>' + owner +  
            ' said "' + thread.RootPost.Text + '"</p>';
    }  
    $("#message").html(newscontent);  
}

REST API to retrieve list/libraries from sharepoint

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
$(document).ready(function () {
  //Get the URI decoded URLs.
  hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
  appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
 
  // Load the SP.RequestExecutor.js file.
  $.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js", runCrossDomainRequest);
});
 
// Build and send the HTTP request.
function runCrossDomainRequest() {
  var executor = new SP.RequestExecutor(appweburl);  
  executor.executeAsync({
      url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists?@target='" + hostweburl + "'",
      method: "GET",  
      headers: { "Accept": "application/json; odata=verbose" },  
      success: getlistfromsite,  
      error: errorHandler  
  });
}    
//retrive all lists from site    
 function getlistfromsite(data) {
        var jsonObject = JSON.parse(data.body);
        var oists = document.getElementById("lists");
        if (oists.hasChildNodes())
        {
            while (oists.childNodes.length >= 1) {
                oists.removeChild(oists.firstChild);
            }
        }
        var results = jsonObject.d.results;
        for (var i = 0; i < results.length; i++)
        {
            var listcombined = document.createElement("option");
            listcombined.value = results[i].Title;
            listcombined.innerText = results[i].Title;
            oists.appendChild(listcombined);
        }
    }
     
    //error handler
function errorHandler(){
alert('error');
}

REST API to create list in SharePoint

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function createSPList() {  
   $.ajax(  
   {  
      url: appweburl +  
      "/_api/SP.AppContextSite(@target)/web/lists?@target='" +  
      hostweburl + "/sites/apps'",  
      type: "POST",  
      data: JSON.stringify({  
      '__metadata': { 'type': 'SP.List' },  
      'AllowContentTypes': true,  
      'BaseTemplate': 100,  
      'ContentTypesEnabled': true,  
      'Description': 'My TestCustomList description',  
      'Title': 'TestCustomList'  
   }),  
   headers: {  
      "accept": "application/json;odata=verbose",  
      "content-type": "application/json;odata=verbose",  
      "X-RequestDigest": $("#__REQUESTDIGEST").val()  
   },  
   success: successHandler,  
   error: errorHandler  
   });  
}  
function successHandler() {  
   $('#message').text('Success');  
}  
function errorHandler(data, errorCode, errorMessage) {  
   $('#message').text('Error ' + errorMessage);  
}    

REST API to upload file in doc lib

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 
  1. <input id="getFile" type="file"/><br />  
  2. <input id="displayName" type="text" value="Enter a unique name" /><br />  
  3. <input id="addFileButton" type="button" value="Upload" onclick="uploadFile()"/>  
----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function uploadFile()
{
 
    // Define the folder path for this example.
    var serverRelativeUrlToFolder = '/sites/apps/shared documents';
 
    // Get test values from the file input and text input page controls.
    // The display name must be unique every time you run the example.
    var fileInput = $('#getFile');
    var newName = $('#displayName').val();
 
    // Initiate method calls using jQuery promises.
    // Get the local file as an array buffer.
    var getFile = getFileBuffer();
    getFile.done(function (arrayBuffer) {
 
        // Add the file to the SharePoint folder.
        var addFile = addFileToFolder(arrayBuffer);
        addFile.done(function (file, status, xhr) {
 
            // Get the list item that corresponds to the uploaded file.
            var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
            getItem.done(function (listItem, status, xhr) {
 
                // Change the display name and title of the list item.
                var changeItem = updateListItem(listItem.d.__metadata);
                changeItem.done(function (data, status, xhr) {
                    alert('file uploaded successfully in Library);
                });
                changeItem.fail(onError);
            });
            getItem.fail(onError);
        });
        addFile.fail(onError);
    });
    getFile.fail(onError);
 
    // Get the local file as an array buffer.
    function getFileBuffer()  
    {
        var deferred = jQuery.Deferred();
        var reader = new FileReader();
        reader.onloadend = function (e) {
            deferred.resolve(e.target.result);
        }
        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }
        reader.readAsArrayBuffer(fileInput[0].files[0]);
        return deferred.promise();
    }
 
    // Add the file to the file collection in the Shared Documents folder.
    function addFileToFolder(arrayBuffer)  
    {
 
        // Get the file name from the file input control on the page.
        var parts = fileInput[0].value.split('\\');
        var fileName = parts[parts.length - 1];
 
        // Construct the endpoint.
        var fileCollectionEndpoint = String.format(
            "{0}/_api/sp.appcontextsite(@target)/web/getfolderbyserverrelativeurl('{1}')/files" +
            "/add(overwrite=true, url='{2}')?@target='{3}'",
            appWebUrl, serverRelativeUrlToFolder, fileName, hostWebUrl);
 
        // Send the request and return the response.
        // This call returns the SharePoint file.
        return $.ajax({
            url: fileCollectionEndpoint,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-length": arrayBuffer.byteLength
            }
        });
    }
 
    // Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
    function getListItem(fileListItemUri)  
    {
 
        // Construct the endpoint.
        // The list item URI uses the host web, but the cross-domain call is sent to the
        // app web and specifies the host web as the context site.
        fileListItemUri = fileListItemUri.replace(hostWebUrl, '{0}');
        fileListItemUri = fileListItemUri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
         
        var listItemAllFieldsEndpoint = String.format(fileListItemUri + "?@target='{1}'",
            appWebUrl, hostWebUrl);
 
        // Send the request and return the response.
        return $.ajax({
            url: listItemAllFieldsEndpoint,
            type: "GET",
            headers: { "accept": "application/json;odata=verbose" }
        });
    }
 
    // Change the display name and title of the list item.
    function updateListItem(itemMetadata)
    {
 
        // Construct the endpoint.
        // Specify the host web as the context site.
        var listItemUri = itemMetadata.uri.replace('_api/Web', '_api/sp.appcontextsite(@target)/web');
        var listItemEndpoint = String.format(listItemUri + "?@target='{0}'", hostWebUrl);
 
        // Define the list item changes. Use the FileLeafRef property to change the display name.  
        // For simplicity, also use the name as the title.
        // The example gets the list item type from the item's metadata, but you can also get it from the
        // ListItemEntityTypeFullName property of the list.
        var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
            itemMetadata.type, newName, newName);
 
        // Send the request and return the promise.
        // This call does not return response content from the server.
        return $.ajax({
            url: listItemEndpoint,
            type: "POST",
            data: body,
            headers: {
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-type": "application/json;odata=verbose",
                "content-length": body.length,
                "IF-MATCH": itemMetadata.etag,
                "X-HTTP-Method": "MERGE"
            }
        });
    }
}
 
// Display error messages.  
function onError(error)  
{
    alert(error.responseText);
}   

REST API to get file versions

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function versionfile()  
{
    var executor;
 
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
 
    executor.executeAsync
    ({
 
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/GetFileByServerRelativeUrl('/sites/apps/Shared Documents/RESTFolder.docx')/versions?@target='" + hostweburl + "'",
        method: "GET",
 
 
        headers:
 {
            "accept": "application/json; odata=verbose"
        },
        success: SuccessHandlerFileVersions,
        error: ErrorHandlerFileVersions
    });
}
 
/ Success Handler
    Function SuccessHandlerFileVersions (data)  
    {
        var FV;
        var jsonObject = JSON.parse(data.body);
        var results = jsonObject.d.results;
        for (var i = 0; i < results.length; i++)  
        {
            FV += results[i].VersionLabel + '\n';
        }
        / / Display the File versions
alert(FV);
}
// Error Handler
function ErrorHandlerFileVersions(data, errorCode, errorMessage)
{
    alert("Could not get the file versions: " + errorMessage);
}   

REST API to CheckIn file in Doc Lib

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function filecheckin()  
{
    var executor;
 
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
 
    executor = new SP.RequestExecutor(appweburl);
 
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/getfilebyserverrelativeurl('/sites/apps/Shared Documents/filename1.txt')/checkin(comment='Check-in comment.',checkintype=0)?@target='" + hostweburl + "'",
        method: "POST",
 
        headers:  
        {
            "accept": "application/json; odata=verbose"
        },
        success: function(data)
        {
            alert("success:File Checked IN");
        },
        error: function(err)  
        {
            alert("error: " + JSON.stringify(err));
        }
    });
}   

REST API to Add Template File in Document Library

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function addfile()  
{
    var executor;
 
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
 
    executor.executeAsync({
 
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/getfolderbyserverrelativeurl('/sites/apps/Shared Documents')/files/addtemplatefile(urloffile='/sites/apps/Shared Documents/wikipage.aspx',templatefiletype=1)?@target='" + hostweburl + "'",
        method: "POST",
 
        headers:  
        {
            "accept": "application/json; odata=verbose"
        },
        success: function(data)
        {
            alert("success:WIKI PAGE CREATED SUCCESSFULLY ");
        },
        error: function(err)
        {
            alert("error: " + JSON.stringify(err));
        }
    });
}
   

REST API to Checkout File in Document Library

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 

----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function filecheckout()  
{
    var executor;
 
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
 
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/getfilebyserverrelativeurl('/sites/apps/Shared Documents/filename1.txt')/checkout?@target='" + hostweburl + "'",
        method: "POST",
 
        headers:  
        {
            "accept": "application/json; odata=verbose"
        },
        success: function(data)
        {
            alert("success:File Checked out ");
        },
        error: function(err)  
        {
            alert("error: " + JSON.stringify(err));
        }
    });
}   

REST API to Delete folder from document library

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 
<div>
    <p>
        <b>Create Folder</b>
        <br />
        <input type="text" value="List Name Here" id=" DeleteFolder " />
        <button id="btnclick"> Delete Folder </button>
    </p>
</div>
----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function FolderCreation()
{
    var executor;
 var getfoldername= document.getElementById("DeleteFolder").value;
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
   url: appweburl + "/_api/SP.AppContextSite(@target)/web/GetFolderByServerRelativeUrl('lib/Folder B')?@target='" + hostweburl + "'",
        method: "POST",
}        
          headers:  
            {
              "X-HTTP-Method":"DELETE"  
            },  
success: FoldersSuccessHandler,
        error: FoldersErrorHandler
    });
}  
//Populate the selectFolders control after retrieving all of the folders.
function FoldersSuccessHandler(data) {
    alert("Folder Deleted successfully in Library");
}  
function FoldersErrorHandler(data, errorCode, errorMessage) {
    alert("Could not Delete a Folder in  Library: " + errorMessage);
}
//Utilities
// Retrieve a query string value.
// For production purposes you may want to use a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve) return singleParam[1];
    }
}  

REST to create folder in doc libraries

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST API for SP document libraries before proceed.

HTML file in Default.aspx 
<div>
    <p>
        <b>Create Folder</b>
        <br />
        <input type="text" value="List Name Here" id="CreateFolder" />
        <button id="btnclick">Create Folder</button>
    </p>
</div>
----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function FolderCreation()
{
    var executor;
    var getfoldername= document.getElementById("CreateFolder").value;
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
  url: appweburl + "/_api/SP.AppContextSite(@target)/web/GetFolderByServerRelativeUrl('lib')/folders?@target='" + hostweburl + "'",
        method: "POST",
        body: "{ '__metadata':{ 'type': 'SP.Folder' }, 'ServerRelativeUrl':'Folder B' }",
}
          headers:  
           {
             "accept": "application/json; odata=verbose",
    "content-type": "application/json; odata=verbose"
            },  
success: FoldersSuccessHandler,
        error: FoldersErrorHandler
    });
}  
//Populate the selectFolders control after retrieving all of the folders.
function FoldersSuccessHandler(data) {
    alert("Folder Created successfully in Library");
}
function FoldersErrorHandler(data, errorCode, errorMessage) {
    alert("Could not Create a Folder in  Library: " + errorMessage);
}

Use REST API to play with list & Document library

Here we will use NAPA tool to write the REST scripts.

Open developer site --> Open NAPA office 365 development tool --> Add new project
If you don't have NAPA tool then search and install NAPA App in your site.

In default.aspx page write your HTML like below so that we can trigger the methods as per our need
Ex:
  1. <button id="btn_ID_Here"> Delete Folder </button>  (Here we need jQuery to fire click event) 
  2. <input id="btn_ID_Here" type="button" value="Click" onclick="ButtonClickFunction()"/>  
Now we will replace the default "app.js " file with below codes

------------------------------------------ JS code Start Here --------------------------
'use strict';
var hostweburl;
var appweburl;
 // Get the URLs for the app web the host web URL from the query string.
$(document).ready(function ()
 {
    //Get the URI decoded URLs.
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
 
    // Resources are in URLs in the form:
    // web_url/_layouts/15/resource  
 
    // Load the js file and continue to load the page with information about the folders.
    // SP.RequestExecutor.js to make cross-domain requests
    $.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js");

//Below one is optional to bind click function to normal html as in example 1 above
         $("#btn_ID_Here").click(function (event)
        {  
            ButtonClickFunction();  
            event.preventDefault();  
        }); 
});

// ------- Your Custom functions Starts Here
//Button Click Calling Function Here
function ButtonClickFunction()
{
     
}
//1. REST API to Upload file in document library
//2. REST API to Get File versions in document library
//3. REST API to CheckIn file
//4. REST API to Add template file in doc lib
//5. REST API to Checkout file
//6. REST to Delete folder from document library
//7. REST to Create folder in doc lib
//8. REST to Get all folders from root site


// ------- Your Custom functions Ends Here    

function getQueryStringParameter(paramToRetrieve) {
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve) return singleParam[1];
    }
}
------------------------------------------JS Code End Here --------------------------

Once coding done specify the permissions that your app needs as in the following:
Choose the Properties button at the bottom of the page.

    In the Properties window, choose Permissions.
    In the Content category, set Write permissions for the Tenant scope.
    In the Social category, set Read permissions for the User Profiles scope.
    Close the Properties window.

Publish the App and Click the Trust it Button.









REST to Get all folders from root site

Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

I recommend to go through REST for SP document libraries before proceed.

HTML file in Default.aspx 
<div>
        <p>
            <b>Retrive Folders</b>
            <br />
            <select style="height:500px; width:510px" multiple="multiple" id="allFolders"></select>
        </p>
</div
----------------------
JS script in app.js (Paste the below methods in app.js file) Refer here
-----------------------
function getFolders() {
    var executor;
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/folders?@target='" + hostweburl + "'",
        method: "GET",
        headers: {
            "Accept": "application/json; odata=verbose"
        },
        success: FoldersSuccessHandler,
        error: FoldersErrorHandler
    });
}  

//Populate the selectFolders control after retrieving all of the folders.
function FoldersSuccessHandler(data) {
    var jsonObject = JSON.parse(data.body);
    var allFolders = document.getElementById("allFolders");
    if (allFolders.hasChildNodes()) {
        while (allFolders.childNodes.length >= 1) {
            allFolders.removeChild(allFolders.firstChild);
        }
    }
    var results = jsonObject.d.results;
    for (var i = 0; i < results.length; i++) {
        var Option = document.createElement("option");
        Option .value = results[i].Name;
        Option .innerText = results[i].Name;
        allFolders.appendChild(Option );
    }
}
function FoldersErrorHandler(data, errorCode, errorMessage) {
    alert("Could not retrieve  Folders: " + errorMessage);
}




REST APIs to play with SharePoint Groups


Hope you have idea how to create SharePoint App.
If you are using NAPA tool then replace below codes in APP.js file.
So i am just focusing on the REST script part to do the activities

Source Code in JS file:
Here we can call different methods from html button click as per need to perform action.
------------------------------------------------------------------------------------------------------------------------
    'use strict';
     
    var hostweburl;
    var appweburl;
 
    $(document).ready(function ()
    {
        //Get the URI decoded URLs.
        hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
        appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
     
        // Load the js file and continue to load the page with information about the folders.
        // SP.RequestExecutor.js to make cross-domain requests
        $.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js",creategroup);
    });
//--------------- ----------------------
     
    //Create Group
    function creategroup()
    {
        var executor;
         // Initialize the RequestExecutor with the app web URL.
        executor = new SP.RequestExecutor(appweburl);
     
        executor.executeAsync({
      url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups?@target= '" + hostweburl + "'",  
            method: "POST",
      body: “{'__metadata':{ 'type': 'SP.Group' }, 'Title':'New Group'}”,
            headers:  
            {  
                "content-type": "application/json; odata=verbose"
            },  
            success: function(data)  
            {  
                alert("Group CREATED SUCCESSFULLY ");  
            },  
            error: function(err)  
            {  
                alert("error: " + JSON.stringify(err));  
            }      });
    }
//--------------- ----------------------     

//Retrieve Groups
function retrivegroup()
{
    var executor;
    // Initialize the RequestExecutor with the app web URL.  
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups?@target= '" + hostweburl + "'",
        method: "GET",
        headers: {
            "Accept": "application/json; odata=verbose"
        },
        success: getGroupsSuccessHandler,
        error: function(err) {
            alert("error: " + JSON.stringify(err));
        }
    });
}

function getGroupsSuccessHandler(data)
{
    var jsonObject = JSON.parse(data.body);
    var Groups = document.getElementById("RetriveGroups");
    if (Groups.hasChildNodes())
    {
        while (Groups.childNodes.length >= 1)
        {
            Groups.removeChild(Groups.firstChild);
        }
    }
    var results = jsonObject.d.results;
    for (var i = 0; i < results.length; i++)
    {
        var allgroups = document.createElement("option");
        allgroups.value = results[i].Title;
        allgroups.innerText = results[i].Title;
        Groups.appendChild(allgroups);
    }
}
//--------------- ----------------------

//Delete Users in groups
function DeleteUser()
{
    var executor;
    var userEmail = "gowthamdev@Gauti.onmicrosoft.com";
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups(6)/users/getbyemail('" + userEmail + "')?@target='" + hostweburl + "'",
        method: "POST",
        headers: {
            "X-HTTP-Method": "DELETE"
        },
        success: function(data) {
            alert("User Deleted successfully in SharePoint Group");
        },
        error: function(err) {
            alert("error: " + JSON.stringify(err));
        }
    });
}
//--------------- ----------------------

//GetUsers in group
function getuser()
{
    var executor;
    var userEmail = "gowthamdev@Gauti.onmicrosoft.com";
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups(6)/users?@target='" + hostweburl + "'",
        method: "GET",
        headers: {
            "Accept": "application/json; odata=verbose"
        },
        success: getUsersFromGroupSuccess,
        error: getUsersFromGroupError
    });
}
//Populate the selectUsers control after retrieving all of the users from group.
function getUsersFromGroupSuccess(data)
{
    var jsonObject = JSON.parse(data.body);
    var RetriveUsers = document.getElementById("RetriveUsers");
    if (RetriveUsers.hasChildNodes())
    {
        while (RetriveUsers.childNodes.length >= 1)
        {
            RetriveUsers.removeChild(RetriveUsers.firstChild);
        }
    }
    var results = jsonObject.d.results;
    for (var i = 0; i < results.length; i++)
    {
        var selectOption = document.createElement("option");
        selectOption.value = results[i].LoginName;
        selectOption.innerText = results[i].LoginName;
        RetriveUsers.appendChild(selectOption);
    }
}
function getUsersFromGroupError(data, errorCode, errorMessage)
{
    alert("Could not get users from group: " + errorMessage);
}
//--------------- ----------------------

    //Utilities
    // Retrieve a query string value.
    // For production purposes you may want to use a library to handle the query string.
    function getQueryStringParameter(paramToRetrieve)
    {
        var params = document.URL.split("?")[1].split("&");
        for (var i = 0; i < params.length; i = i + 1)
       {
            var singleParam = params[i].split("=");
            if (singleParam[0] == paramToRetrieve) return singleParam[1];
        }
    }

Refer Here: One

Use REST API & Angular JS Implement custom search for lookup & person/group

Before proceed, I recommend you to go through Learn Angular js for better understanding.

Create 2 custom lists
    Product Sales
    Phone

In Phone Custom list, I created  Title,Priority, and Demo single line text data type columns. And in second List i.e Produc Sales, I have created Product,Total_x0020_Sales,Sales_x0020_Target,SalesPerson,LPhone and SalesName.
    Here,"LPhone" is Lookup Field link with our Phone Custom list field of Title.
    "SalesName" is person/Group filed type and Show Field is FirstName.

angularGet.js (Upload it in Site Asset library of SharePoint along with angular js file)
var spApp = angular
                .module("spApp", [])
                .controller("viewItemController", function ($scope, $http) {
                    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Product%20Sales')/items?$select=Product,Total_x0020_Sales,Sales_x0020_Target,SalesPerson,SalesName/FirstName,LPhone/Title&$expand=LPhone,SalesName";
                    $http(
                    {
                        method: "GET",
                        url: url,
                        headers: { "accept": "application/json;odata=verbose" }
                    }
                    ).success(function (data, status, headers, config) {
      var dataResults=data.d.results;
      var item = data.d.results[1];  
         
                        $scope.contacts = dataResults;
       $scope.productItems = function(item)
      {
       
        if($scope.searchText==undefined)
       {
         return true;
        }
        else{
         if((item.SalesPerson.toLowerCase().indexOf($scope.searchText.toLowerCase())!=-1)||(item.Product.toLowerCase().indexOf($scope.searchText.toLowerCase())!=-1))
         {
          return true;
         }
        }
        return false;
       }
                    }).error(function (data, status, headers, config) {
                    });
                   
                })

Create.HTML file: (Upload in site asset library or write in content editor webpart)
<html>

<head>
    <script type="text/javascript" src="/SiteAssets/angular.min.js"></script>
    <script type="text/javascript" src="/SiteAssets/angularGet.js"></script>
</head>

<body>
    <h3>View Contacts</h3>
    <hr/>
    <div ng-app="spApp">
        <div ng-controller="viewItemController"> <input type="text" placeholder="Product&SalesPerson" ng-model="searchText" /> <br/><br/>
            <table>
                <tr>
                    <th>Product</th>
                    <th>Total Sales</th>
                    <th>Sales Target</th>
                    <th>Sales Peron</th>
                    <th>LookUPFieldData</th>
                    <th>Person/GroupField</th>
                </tr>
                <tr ng-repeat="contact in contacts|filter:productItems">
                    <td>{{contact.Product}}</td>
                    <td>{{contact.Total_x0020_Sales}}</td>
                    <td>{{contact.Sales_x0020_Target}}</td>
                    <td>{{contact.SalesPerson}}</td>
                    <td>{{contact.LPhone.Title}}</td>
                    <td>{{contact.SalesName.FirstName}}</td>
                </tr> <br /> </table>
        </div>
        <hr /> </body>

</html>

Now finally add this in share point page add see the result. or open that html page if uploaded in site asset library and check.


Tuesday, 14 February 2017

Get lookup column values using REST


I have source list named: Managers
I have one site column Managers which is a lookup column to Managers--> Title column
I have another list "Details" where we use lookup column "Manager"

getListItems(_spPageContextInfo.webAbsoluteUrl,'?$select=Managers/Title,Managers/Id&$expand=Managers','Details',
function(items){
if(items.length > 0)
console.log(items[0].Managers.Title);
console.log(items[0].Managers.Id);
},
function(error){
console.log(error.responseText);
});

Tuesday, 10 May 2016

REST (Representational State Transfer)


REST (Representational State Transfer)
REST service for list was first introduced in SharePoint 2010. It was under the end point/_vti_bin/listdata.svc, and it still works in SharePoint 2013
SharePoint 2013 introduces another endpoint/_api/web/lists, and which is much more powerful than in SharePoint 2010.

Main advantage of REST SP 2013 is using this we can interact remotely with SharePoint data by using any technology that supports REST web requests Open Data Protocol (OData) syntax..
For this we need to construct a RESTful HTTP request, using the Open Data Protocol (OData) standard, which corresponds to the desired client object model API. For example:
Client object model method:
List.GetByTitle(listname)
REST endpoint:
http://server/site/_api/lists/getbytitle('listname')

Note: Client.svc web service in SharePoint handles the HTTP request, and serves the appropriate response in either Atom or JSON (JavaScript Object Notation) format.

By using HTTP requests, you can use these REST endpoints to perform typical CRUD operations against SharePoint entities.

to do this to an endpoint
HTTP request

Read
GET

Create / Update
POST
For POST operations, any properties that are not required are set to their default values. If you attempt to set a read-only property as part of a POST operation, the service returns an exception.
Update / Insert
PUT / MERGE
·         For MERGE requests, setting properties is optional; any properties that you do not explicitly set retain their current property.
·         For PUT requests, if you do not specify all required properties in object updates, the REST service returns an exception. In addition, any optional properties you do not explicitly set are set to their default properties.
Delete
DELETE
For recyclable objects like lists, files & list items, this results in a Recycle operation.

Construct REST URLs to access SharePoint resources

The main entry points for the REST service represent the site collection and site of the specified context.
Before you can access a SharePoint resource using the REST service, you first have to figure out the URI endpoint that points to that resource.

However URI for these REST endpoints closely mimics the API signature of the resource in the SharePoint client object model. (In some cases, however, the endpoint URI differs from the corresponding client object model signature)
Example

Client object model method:    List.GetByTitle(listname).GetItems()
REST endpoint:                         http://server/site/_api/lists/getbytitle('listname')/items

SharePoint REST URI syntax structure (Some endpoints for SharePoint resources deviate from this syntax structure)

SharePoint REST request syntax

To construct a REST endpoint, Follow these steps

·         Start with the REST service reference:   
o    http://server/site/_api
·         Specify the appropriate entry point:     
o    http://server/site/_api/web
·         Navigate from the entry point to the specific resources you want to access:
o    This includes specifying parameters for endpoints that correspond to methods in the client OM.
o    http://server/site/_api/web/lists/getbytitle('listname')
·          

The REST service is part of the client.svc web service So REST service uses _api to which abstract away the need to explicitly reference the client.svc web service. You can also use client.svc in endpoint URI.
URLs have a 256 character limit, so using _api shortens the base URI,

http://server/site/_api/web/lists
Same as
http://server/site/_vti_bin/client.svc/web/lists

The main entry points for the REST service represent the site collection and site of the specified context. In this way, these entry points correspond to theClientContext.Site property and ClientContext.Web property in the client object models.

Access a specific site collection: http://serverName/siteNameOrSitePath/_api/site
To access a specific site : http://serverName/siteNameOrSitePath/_api/web

Entry Points for REST
Access Point
site collection
http://server/site/_api/site
Web
http://server/site/_api/web
User Profile
http:// server/site/_api/SP.UserProfiles.PeopleManager
Search
http:// server/site/_api/search
Publishing
http:// server/site/_api/publishing
all lists in a site and adding new lists
/_api/Web/Lists
Get list by title & Update
/_api/Web/Lists/GetByTitle('listname') or
/_api/Web/Lists(guid'guid id of your list')
All fields of a list and add new fields
/_api/Web/Lists/GetByTitle(' listname ')/Fields
details of a field, modifying and deleting it
/_api/Web/Lists/GetByTitle('listname')/Fields/GetByTitle('fieldname')
All items in a list and adding new items
/_api/Web/Lists/GetByTitle('listname')/Items
get, update and delete a single item.
/_api/web/lists/GetByTitle('listname')/GetItemById(itemId)
The users in the site
_api/web/siteusers
The user groups in the site
_api/web/sitegroups
The users in group 3
_api/web/sitegroups(3)/users
The root folder of the Shared Documents library
_api/web/GetFolderByServerRelativeUrl('/Shared Documents')
The file a.txt from the Plans library
_api/web/GetFolderByServerRelativeUrl('/Plans')/Files('a.txt')/$value



Now navigate to the specific resources you want to access:

Construct more specific REST endpoints by using the names of the APIs from the client object model separated by a forward slash (/). Below is the examples of client object model calls and the equivalent REST endpoint

Client Object model API
REST Endpoint
ClientContext.Web.Lists
http://server/site/_api/web/lists
ClientContext.Web.Lists[guid]
http://server/site/_api/web/lists(‘guid’)
ClientContext.Web.Lists.GetByTitle("Title")
http://server/site/_api/web/lists/getbytitle(‘Title’)

Options for Filtering and Sorting Data

Option
Purpose
$select
Specifies which fields are included in the returned data.
$filter
Specifies which members of a collection, such as the items in a list, are returned.
$expand
Specifies which projected fields from a joined list are returned.
$top
Returns only the first n items of a collection or list.
$skip
Skips the first n items of a collection or list and returns the rest.
$orderby
Specifies the field that’s used to sort the data before it’s returned.


·         return the author, title and ISBN from a list
o    _api/web/lists/getByTitle('Books')/items?$select=Author,Title,ISBN
o    If wants to return resource-intensive fields then use $select=‘*’
·         get all the books by Mark Twain
o    _api/web/lists/getByTitle('Books')/items?$filter=Author eq 'Mark Twain'
·         To sort the books by title in ascending order
o    _api/web/lists/getByTitle('Books')/items?$orderby=Title asc
·         get only the Title of the first two books by Mark Twain,
§  _api/web/lists/getByTitle('Books')/items?$select=Title&$filter=Author eq 'Mark Twain'&$top=2
·         returns items 3-10
o    _api/web/lists/getByTitle('Books')/items?$top=10&$skip=2
·         returns items 3-12
o    _api/web/lists/getByTitle('Books')/items?$skip=2&$top=10
·         gets the bottom two items
o    _api/web/lists/getByTitle('Books')/items?$orderby=ID desc&$top=2
·         If lookup field Use $expand option, Lets if the Books list has a PublishedBy field that looks up to the Name field of a Publisher list
o    _api/web/lists/getByTitle('Books')/items?$select=Title,PublishedBy/Name&$expand=PublishedBy
·          
·          



Few Examples

GET Items from List

var urlForAllItems = "/_api/Web/Lists/GetByTitle('ListName')/Items";
Then call method - getItems(urlForAllItems);
function getItems(url) {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
            console.log(data.d.results);
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}

_spPageContextInfo.webAbsoluteUrl, returns the current site url.
From data.d.results, you will find fields internal names as object’s property. From above we will get only the Id of Lookup and Person type column, but we need more info for them.
So we can use $select, $expand option of OData query string operators

var urlForAllItems = "/_api/Web/Lists/GetByTitle('SpTutorial')/Items?"+
               "$select=ID,Title,SpMultiline,SpChoice,
               SpNumber,SpCurrency,SpDateTime,SpCheckBox,SpUrl,"+
                "SpPerson/Name,SpPerson/Title,SpLookup/Title, SpLookup/ID" +
                "&$expand=SpLookup,SpPerson";

We can also use $filter to specifies which items to return.

var urlForFilteredItems = abovestring + "&$filter=Title eq 'RK' and SpLookup/ID eq 1";

Numeric String Date Time functions
Lt (less than) startsWith (if starts with some string value) day()
Le (less than or equal) substringof ( if contains any sub string) month()
Gt (greater than)
year()
Ge (greater than or equal)
hour()
Eq (equal to) Eq minute()
Ne (not equal to) Ne second()
Note: Unfortunately, date time functions do not work with new style (URL) of SharePoint 2013. But there is a hope we can do it like SharePoint 2010 style.
var filterByMonth = "/_vti_bin/listdata.svc/SpTutorial?$filter=month(SpDateTime) eq 6";

Can use $orderby to sort items: var urlForOrderBy = above url + “&$orderby=ID desc";
Can use $top to: var urlForOrderBy = above url + “/_api/Web/Lists/GetByTitle
('SpTutorial')/Items?$top=2"


Adding New item to List
var addNewItemUrl = "/_api/Web/Lists/GetByTitle('ListName')/Items";

var data = {
    __metadata: { 'type': 'SP.Data.SpTutorialListItem' },
    Title: 'Some title',
    SpMultiline: 'Put here some multiline text. You can add here some rich text also',
    SpChoice: 'Choice 3',
    SpNumber: 5,
    SpCurrency: 34,
    SpDateTime: new Date().toISOString(),
    SpCheckBox: true,
    SpUrl: {
        __metadata: { "type": "SP.FieldUrlValue" },
        Url: "http://test.com",
        Description: "Url Description"
    },
    SpPersonId: 3,
    SpLookupId: 2
};

function addNewItem(url, data) {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "POST",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose"
        },
        data: JSON.stringify(data),
        success: function (data) {
            console.log(data);
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}

Here In header, you have to specify the value of X-RequestDigest. It’s a hidden field inside the page.
But some time the “$("#__REQUESTDIGEST").val()” does not work. In that case we need to get it from /_api/contextinfo by sending HTTP POST request to URL (_api/contextinfo)
__metadata is the user comments for update & we can get it by sending GET request to /_api/Web/Lists/getbytitle('List Name')/ListItemEntityTypeFullName
Note: Properties of data are the internal names of the fields. We can get it from following URL by making a HTTP GET request.
var urlForFieldsInternalName = "/_api/Web/Lists/GetByTitle('SpTutorial')/
Fields?$select=Title,InternalName&$filter=ReadOnlyField eq false";

Below are the type of inputs for different field types
Type Value
Single line of text String
Multiple lines of text Multiple lines can be added here also rich text
Choice String but it must come from choices available in the list.
Number Integer or double
Currency Like number
Date and Time String but it must be in ISOString format
Lookup Integer and must be the ID of Lookup item
Yes/No true or false
Person or Group Integer and must be the ID of Person or Group
Hyperlink or Picture Object that has three properties only like __metadata, Url, Description

For multiple person Group type
var data = {
    __metadata: { "type": "SP.Data.TestListItem" },
    Title: "Some title",
    MultiplePersonId: { 'results': [11,22] }
}

Update List item

var updateItemUrl = "/_api/Web/Lists/GetByTitle('SpTutorial')/getItemById('Item Id')";

function updateItem(url, oldItem, newItem) {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "PATCH",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose",
            "X-Http-Method": "PATCH",
            "If-Match": oldItem.__metadata.etag
        },
        data: JSON.stringify(newItem),
        success: function (data) {
            console.log(data);
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}

In above HTTP method is PATCH and it is also specified in header ("X-Http-Method": "PATCH") and which is recommended
etag means Entity Tag which is always returned during HTTP GET items which is required while doing any update
Following are the ways to specify etag.
  1. "If-Match": oldItem.__metadata.etag (If etag value does not match, service will return an exception)
  2. "If-Match": "*" (It is considered when force update or delete is needed)
Delete List item

function deleteItem(url, oldItem) {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "DELETE",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "If-Match": oldItem.__metadata.etag
        },
        success: function (data) {
          
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });
}

Here Url is same like we use for updating list item.





)




Ads