Shekar Reddy
Shekar Reddy

Reputation: 756

403 forbidden and 400 bad request errors while adding and deleting items to SharePoint list using REST

I'm new to SharePoint development. I'm Trying to develop simple SharePoint App using SharePoint online. I have a List named 'Products' in my site collection. In my app I wrote the following code to add and delete items to that list

 function addProduct(product) {
 var executor;
 executor = new SP.RequestExecutor(appwebUrl);
 var url = appwebUrl +"/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Products')/items/?@target='" + hostwebUrl+"'";
 executor.executeAsync({
    url: url,
    method: "POST",
    body: JSON.stringify({__metadata: { type: 'SP.Data.ProductsListItem' },
        Title: product.ProductName(),
        ProductId: product.ProductId(),
        ProductName: product.ProductName(),
        Price:product.Price()
    }),
    headers: {
        "Accept": "application/json; odata=verbose",
        "content-type": "application/json;odata=verbose",
        },
    success: successProductAddHandler,
    error: errorProductAddHandler
});
}


function successProductAddHandler(data) {alert('added successfully') }
function errorProductAddHandler(data, errorCode, errorMessage) { alert('cannot perform action') }


function deleteProduct(product) {
var executor;
executor = new SP.RequestExecutor(appwebUrl);
var url=appwebUrl+"/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Products')/items('" + product.ID() + "')/?@target='" + hostwebUrl + "'";
executor.executeAsync({
    url: url,
    method: "POST",
    headers: {

        "IF-MATCH": "*",
        "X-HTTP-Method": "DELETE"
    },
    success: successProductAddHandler,
    error: errorProductAddHandler
});`

Im getting 403 error code when I call addProduct, and 400 error code when I call deleteProduct. I'm able to get the list items and display.

I tried adding X-RequestDigest": $("#__REQUESTDIGEST").val() but it did not work

If I include "Accept": "application/json; odata=verbose" in a request header for deleteProduct(), and when I call deleteProduct, two requests are going to server

  1. /sites/productsdev/productsapp/_api/contextinfo (getting digest value)
  2. /sites/ProductsDev/ProductsApp/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Products')/items(itemid)/?@target='mysitecollectionurl' (using the digest value returned by the above call for X-RequestDigest)

Upvotes: 0

Views: 5274

Answers (1)

Azam Khan
Azam Khan

Reputation: 141

Whenever you are doing any POST operation in SharePoint 2013 using REST API you have to pass below snippet in header

"X-RequestDigest": $("#__REQUESTDIGEST").val()

eg

headers: { "Accept": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val() }

Upvotes: 3

Related Questions