Home > database >  Create list item SharePoint online Rest API 403 - Forbidden
Create list item SharePoint online Rest API 403 - Forbidden

Time:11-25

I am trying to create a new list item in a SharePoint list on SPO.

I am getting forbidden 403 error.

var listURL = webURL   "/_api/web/lists/GetByTitle('Departments')/items"; 
                 $.ajax({  
             url: listURL,
             type: "POST",  
             headers: {  
                 "accept": "application/json;odata=verbose",  
                 "content-Type": "application/json;odata=verbose"  
             },  
             data: JSON.stringify({  
                                 '__metadata': { 'type': 'SP.Data.'   pListName   'ListItem' },
                                 'Title': 'Test1'}),
                                 
            
             success: function(data) {  
                 console.log(data.d.results);  
                 alert("Item added")
             },  
             error: function(error) {  
                 alert(JSON.stringify(error));  
             }  
            }); 

CodePudding user response:

SharePoint does not allow anonymous requests (your request appears to be anonymous). You need to be authenticated (logged in).

CodePudding user response:

You need to provide _spPageContextInfo or AccessToken to get authentication

$.ajax
    ({
        url: _spPageContextInfo.webAbsoluteUrl   "/_api/web/lists/getByTitle('New List1')/items",
        type: "POST",
        headers:
    {
        "Accept": "application/json;odata=verbose",
        "Content-Type": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
        data: JSON.stringify
    ({
        __metadata:
        {
            type: "SP.Data.New_x0020_List1ListItem"
        },
        Title: "New Title"
    }),
        success: function (data, status, xhr) {
            console.log("Success");
        },
        error: function (xhr, status, error) {
            console.log("Failed");
        }
    });
  • Related