Search code examples
javascriptrestodatasharepoint-online

Delete item from SharePoint List using JavaScript and REST


I have some JavaScript (physical file located in /SiteAssets library) that should delete an item in a SharePoint list.

We have existing JavaScript code that retrieves data from the list - it looks like this:

(notice that since the JavaScript runs on a PDP in context of the current user, we don't need a specific access token for the request)

var data = $.ajax({
    url: projSiteUrl + "/_api/lists/getbytitle('<listname>')/items,
    type: "GET",
    dataType: "json",
    async: false,
    headers: {
        Accept: "application/json;odata=verbose"  
    }       
});

So I thought that I could write similar code to delete an item from the list again. I read on https://msdn.microsoft.com/en-us/library/office/jj164022.aspx#HTTPOps that the REST endpoint of SharePoint supports the "normal" REST verbs, so I wrote this, using the DELETE HTTP verb.

var restUrl = spSiteUrl + '/_api/web/lists/GetByTitle(\'' + listTitle + '\')/items(' + itemId + ')';
jQuery.ajax({
    url: restUrl,
    type: "DELETE",
    headers: {
        Accept: "application/json;odata=verbose"  
    }       
})

But I am getting a 403 (FORBIDDEN) when requesting.

I guess the question is: Am I wrong in assuming that the DELETE verb is supported?

Thanks :-)


Solution

  • Ok, so apparently I do need the digest when doing modifications - but not for simple data retrieval.

    If I change my code to

    jQuery.ajax({
        url: restUrl,
        type: "DELETE",
        headers: {
            Accept: "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "IF-MATCH": "*"
        }       
    }).
    

    ... it works with a simple AJAX request using the REST HTTP verb DELETE :-)