6
votes

I need to delete all the Items in a Sharepoint List using REST API.
How can I achieve this?
I can delete a single Item using: "/_api/web/lists/getByTitle('MyList')/items('ID')"

I tried to remove the ID but it did not work.

3

3 Answers

5
votes

You can try this

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

    },
    error: function (error) {
        alert(JSON.stringify(error));
    }
});
}

$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('MyList')/items",
    type: "GET",
    headers: {
        "accept": "application/json;odata=verbose",
    },
    success: function (data) {
        var items = data.d.results;
        for(var item in items){
            var url = "/_api/Web/Lists/getByTitle('MyList')/getItemById(item.ID)"
            deleteItem(url);
        }
    },
    error: function (error) {
        alert(JSON.stringify(error));
    }
});
3
votes

You have to make one delete call for each item in the list, using a URI like you showed above, passing in each ID in succession. If there are LOTS of items in the list, it would likely be cheaper and faster to delete then recreate the list itself.

0
votes

You can try this code. But you should know, that here can be exception in your list. I had problem with list after using this code. I deleted all items, but my ListCount properties set to -3. I recomend use batch request for forming and execute request. It will be more quickly and safely

window.I = 0;
deleteFunction();

function deleteListItem(listTitle, listItemId, type)
{
    try
    {
    var listItemUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + listItemId + ")";
    var itemPayload = {'__metadata': {'type': type}};

    $.ajax({       
       url: listItemUri,
       type: "POST",   
       contentType: "application/json;odata=verbose",
       headers: { 
          "Accept": "application/json;odata=verbose",
          "X-RequestDigest" : $("#__REQUESTDIGEST").val(),
          "X-HTTP-Method": "DELETE",
          "If-Match": "*"
       },success :function(){
           console.log("deleted " + window.I);
           window.I++; 
           deleteFunction();
           },
           error: function (data) {
           window.I++; 
           deleteFunction();
          }
    });
    }
    catch(e)
    {
        console.log("error" + window.I);
        window.I++;
    }
}

function deleteFunction()
{
    try
    {
        if(window.I > 1000) return;
        deleteListItem('ListName',window.I,'SP.Data.ListNameListItem');
        console.log("deleted " + window.I);
    }
    catch(e)
    {
        console.log("error" + window.I);
        window.I++;
    }
}