Showing posts with label RestApi SharePoint. Show all posts
Showing posts with label RestApi SharePoint. Show all posts

Thursday, March 18, 2021

How to read more than 5000 items from document library in SharePoint RestApi?

  1. First call a ajax function with parameters "/_api/Web/Lists/GetByTitle(ListName)/Items?$orderby=Id desc&$top=1". Now you will get the latest added "Id".
  2. Now Divide the Id returned by the ajax by 5000. (Id/5000) So that you will get a result of how many times you need to perform the ajax.
  3. Now you can perform the ajax function repeatedly be filtering every 5000 items, with filter like, $filter=Id ge 0 and Id le 5000, $filter=Id ge 5000 and Id le 10000, ........ , etc.
  4. You can have a foreach loop to perform the ajax repeatedly with a dynamic filter, $filter=Id ge (5000*LoopValue) and Id le (5000*(LoopValue+1)).

Also make sure, the ajax to have async:true, to avoid performance issue. You can store the returned data in array and perform further actions, so that you could store more than 5000 data to perform your functions.

 

 var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('DocumentList')/items?$select=customerID&$top=1000";

    var response = response || [];  // this variable is used for storing list items

    function GetListItems(){

        return $.ajax({

            url: url,  

            method: "GET",  

            headers: {  

                "Accept": "application/json; odata=verbose"  

            },

            success: function(data){

                response = response.concat(data.d.results);

                if (data.d.__next) {

                    url = data.d.__next;

                    GetListItems();

                }

                $.each(response, function(index, item) {

                    arrayCustomerID[index] = item.customerID;

                });

            },

            error: function(error){

            }

        });

    }

Wednesday, March 17, 2021

How to check whether the current user has edit permission for a particular list using JSOM in SharePoint 2013

 we first need to get the login name of user and pass it to the get_effectiveBasePermissions method.


To ensure that user has edit permission, we will check the SP.PermissionKind.editListItems enum.


SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {

    getCurrentUserPermission();

});



function getCurrentUserPermission()

{    

    var web,clientContext,currentUser,oList,perMask;


    clientContext = new SP.ClientContext.get_current();

    web = clientContext.get_web();

    currentUser = web.get_currentUser();   

    oList = web.get_lists().getByTitle('Test List');

    clientContext.load(oList,'EffectiveBasePermissions');

    clientContext.load(currentUser); 

    clientContext.load(web);           


    clientContext.executeQueryAsync(function(){

        if (oList.get_effectiveBasePermissions().has(SP.PermissionKind.editListItems)){

            console.log("user has edit permission");

        }else{

             console.log("user doesn't have edit permission");

        }   

    }, function(sender, args){

        console.log('request failed ' + args.get_message() + '\n'+ args.get_stackTrace());

    });

}

How to get permission of a SharePoint list for a user using RESTApi

 Use EffectiveBasePermissions to get permissions of the user on a list. Example:


/_api/web/lists/getbytitle('L2')/EffectiveBasePermissions

Note that this will give the permissions of the logged in user


function checkPermissions() {

    var call = jQuery.ajax({

        url: _spPageContextInfo.webAbsoluteUrl +

            "/_api/Web/effectiveBasePermissions",

        type: "GET",

        dataType: "json",

        headers: {

            Accept: "application/json;odata=verbose"

        }

    });


    call.done(function (data, textStatus, jqXHR) {

        var manageListsPerms = new SP.BasePermissions();

        manageListsPerms.initPropertiesFromJson(data.d.EffectiveBasePermissions);


        var manageLists = manageListsPerms.has(SP.PermissionKind.manageLists);


        var message = jQuery("#message");

        message.text("Manage Lists: " + manageLists);

    });

}

Wednesday, December 2, 2020

Display SharePoint list items using rest api

 <div>

<input type="button" id="btnSubmit" value="Get List Details" />

</div>

<div id="divResults"></div>


<script>

$(function () {

$("#btnSubmit").on("click", function () {

getListData();

});

});


function getListData() {

var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Projection')/items";

$.ajax({

url: fullUrl,

type: "GET",

headers: {

"accept": "application/json;odata=verbose",

"content-type": "application/json;odata=verbose",

},

success: onQuerySucceeded,

error: onQueryFailed

});

}


function onQuerySucceeded(data) {

var listItemInfo = ";

$.each(data.d.results, function (key, value) {

listItemInfo += '<b>Title:</b> ' + value.Title + ' – <b>Billable hours:</b> ' + value.BillableDays + '<br />';

});

$("#divResults").html(listItemInfo);

}

function onQueryFailed() {

alert('Error!');

}

</script>

Wednesday, February 15, 2017

How to get current user group collection through Rest api in SharePoint 2013

<script type="text/javascript">
    $(document).ready(function () { getCurrentUser(); });
    function getCurrentUser() {

        $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/CurrentUser",
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: function (data) {
                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; var InnrHtmlgrp = "<ul>";
                for (var i = 0; i < results.length; i++) {
                    lstgrp += "<li>" + results[i].Title + "</li>";
                }
                $("#bindGroup").append(lstgrp + "</ul>");
            }
        });
    }
</script>
 
      <div id="bindGroup"></div>

Thursday, September 22, 2016

Using REST API For Selecting, Filtering, Sorting And Pagination in SharePoint List

 how to work with SharePoint list items, basically performing CRUD operations, using the combination of REST API 
and jQuery Ajax. The REST URI ends with any OData query operators to specify selecting, sorting, or filtering

Selecting and sorting items:

$select :

This ' /_api/web/lists/getbytitle('test')/items' url returns all items with all possible fields or list columns. 
But what if list has more than 20-30 columns?
 It’s not good practice to get all fields. 


Syntax for this is $select=Field1, Field2, Field3 
/_api/web/lists/getbytitle('test')/items?$select=ID,Title,Employee,company

'$orderby' :


The first two specify sorting in ascending order and the third one descending order.
 It's simple, you can use '$orderby' parameter and provide the field name. 
REST service will return sorted list items in response.

Syntax: for this is $orderby=(Column Internal Name order)

Ascending Order:
/_api/web/lists/getbytitle('emp')/items?$select=ID,Title,Employee,company&$orderby= Employee asc 
Descending Order:


/_api/web/lists/getbytitle('emp')/items?$select=ID,Title,Employee,company&$orderby= Employee desc  

Filtering items:

You can filter your list to contain only items which match a simple logical expression using the $filterparameter.

Syntax: for this is $filter=(Column Internal Name operator value).
See below examples,

Filter by Title

/_api/web/lists/getbytitle('emp')/items?$filter=Employee eq ‘parth'

Filter by ID:

/_api/web/lists/getbytitle('emp')/items?$filter=ID eq 2

Filter by Date

/_api/web/lists/getbytitle('emp')/items?$filter=Start_x0020_Date le datetime'2016-03-26T09:59:32Z'

Multiple Filters

/_api/web/lists/getbytitle('emp')/items?$filter=( Modified le datetime'2016-03-26T09:59:32Z') and (ID eq 2)

Title name starts with the letter P

/_api/web/lists/getbytitle('emp')/items?$filter=startswith(Title,‘P’)

Return all items from the 'emp'list modified in May

/_api/web/lists/getbytitle('emp')/items? $filter=month(Modified) eq 5

Wednesday, September 21, 2016

what is difference between Name and Account - /_vti_bin/listdata.svc/UserInformationList,



Result:

<content type="application/xml">
  <m:properties>
    <d:Id m:type="Edm.Int32">1</d:Id>
    <d:ContentTypeID>0x010A00F8C6531A37316E499095FDC0720C4D90</d:ContentTypeID>
    <d:ContentType>Person</d:ContentType>
    <d:Name>peakfinders\administrator</d:Name>
    <d:Modified m:type="Edm.DateTime">2015-04-30T16:50:53</d:Modified>
    <d:Created m:type="Edm.DateTime">2015-04-30T16:50:53</d:Created>
    <d:CreatedById m:type="Edm.Int32">1073741823</d:CreatedById>
    <d:ModifiedById m:type="Edm.Int32">1073741823</d:ModifiedById>
    <d:Owshiddenversion m:type="Edm.Int32">1</d:Owshiddenversion>
    <d:Version>1.0</d:Version>
    <d:Path>/_catalogs/users</d:Path>
    <d:Account>i:0#.w|peakfinders\administrator</d:Account>
    <d:EMail m:null="true" />
    <d:MobileNumber m:null="true" />
    <d:AboutMe m:null="true" />
    <d:SIPAddress m:null="true" />
    <d:IsSiteAdmin m:type="Edm.Boolean">true</d:IsSiteAdmin>
    <d:Deleted m:type="Edm.Boolean">false</d:Deleted>
    <d:Hidden m:type="Edm.Boolean">false</d:Hidden>
    <d:Picture m:null="true" />
    <d:Department m:null="true" />
    <d:JobTitle m:null="true" />
  </m:properties>
</content>


Tuesday, January 19, 2016

How to Copy List item to Another list using sharepoint designer 2013 workflow?

We can use the the REST services to move the items one to another list.
  • Add Dictionary is a new variable 
  • create a dictionary add Build Dictionary action
  • Accept and Content-Type
  •  set the values for both of them to application/json; odata=verbos
  • add key __metadata 
New item created from workflow 
call the web service
_api/web/lists/getbytitle('examples')/items and the HTTP method is POST. 
Set the request to your parameters dictionary. 
To set the header of your request go to :
Right click option

Call HTTP service -> properties -> RequestHeaders and set it to your header dictionary.
 

Tuesday, January 5, 2016

How to delete list item using Restapi in Sharepoint 2013

SharePoint 2013,/_api/web/lists,


function deleteListItem(url, listname, id, success, failure) {

    // getting our item to delete, then executing a delete once it's been returned
    getListItem(url, listname, id, function (data) {
        $.ajax({
            url: data.d.__metadata.uri,
            type: "POST",
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-Http-Method": "DELETE",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "If-Match": data.d.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    });

};

Friday, January 1, 2016

Add list items restapi

function CreateListItemWithDetails(listName, webUrl, newItemTitle, success, failure) {
    var itemType = GetItemTypeForListName(listName);
    var item = {
        "__metadata": { "type": itemType },
        "Title": newItemTitle
    };

    $.ajax({
        url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            failure(data);
        }
    });
}

// Get List Item Type metadata
function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}

How to Update list items restapi SharePoint

function updateListItem(url, listname, id, metadata, success, failure) {

    // Prepping our update
    var item = $.extend({
        "__metadata": { "type": getListItemType(listname) }
    }, metadata);

    getListItem(url, listname, id, function (data) {
        $.ajax({
            url: data.d.__metadata.uri,
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": data.d.__metadata.etag
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });

    }, function (data) {
        failure(data);
    });

}

Get Single list items restapi SharePoint


getListItem("http://peakfinders",1,complete, failure);

function getListItem(url, listname, id, complete, failure) {
// Getting our list items
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// Returning the results
complete(data);
},
error: function (data) {
failure(data);
}
});
}
}

Tuesday, December 22, 2015

REST API OData Filter on Boolean not Working




/_api/web/lists/getbytitle('Zone%20Manager')/items?$filter=ZMgrStatus eq 1

Friday, December 18, 2015

How to access a custom field of a list using REST

<script type="text/javascript">
SP.SOD.executeFunc('sp.js','SP.ClientContext',update);
var returnedItems;
function update(){

var context=new SP.ClientContext();
var list=context.get_web().get_lists().getByTitle('Documents');

var caml = new SP.CamlQuery();
caml.set_viewXml("<View><Query></Query></View>");
returnedItems=list.getItems(caml);
context.load(returnedItems);
context.executeQueryAsync(onSucceededCallback,onFailedCallback);

}

function onSucceededCallback(sender,args){
alert();
var enumerator = returnedItems.getEnumerator();

while(enumerator.moveNext()){
var listItem=enumerator.get_current();
var myfield=listItem.get_item('MyField');

}
    }

function onFailedCallback(sender,args){
alert("Failed to connect:  "+args.get_message());
}
</script>

Saturday, December 12, 2015

RestApi In SharePoint 2013


List of REST Access Points
Site
http://peakfinders/site/_api/site

Web
http://peakfinders/site/_api/web

User Profile
http:// peakfinders/site/_api/SP.UserProfiles.PeopleManager

Search
http:// peakfinders/site/_api/search

Publishing
http:// peakfinders/site/_api/publishing
List of REST End Points
The following is a list of end points that are the most commonly used on a SharePoint list.

http://peakfinders/site/_api/web/lists
http://peakfinders/site/_api/lists/getbytitle('listname')
http://peakfinders/site/_api/web/lists(‘guid’)
http://peakfinders/site/_api/web/lists/getbytitle(‘Title’)