I am facing issues with updating a simple list item using SharePoint REST API. I have gone through all the blogs to get a solution but the result is same. When ever i execute the update list item function using REST API it returns me the body of the particular list item row i am trying to update but it is not updating the listem. Could someone please help me out. Thanks in advance
function (listTitle, TabId, success, failure) {
var itemType = GetItemTypeForListName(listTitle);
var query = appweburl + "_api/SP.AppContextSite(#target)/web/lists/getbytitle('" + listTitle + "')/items(5)?&#target='" + hostweburl + "'";
var meta_data = {"__metadata": { "type": itemType }};
meta_data['DeletedStatus'] = 'Inactive'
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: query,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(meta_data),
//body: meta_data,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"IF-MATCH": "*"
//"content-length": meta_data.length,
},
success: function (data) {
//alert("success: " + JSON.stringify(data));
//deferred.resolve(JSON.parse(data.body));
console.log(JSON.stringify(data));
alert(JSON.stringify(data));
},
error: function (err) {
//alert("error: " + JSON.stringify(err));
console.log(JSON.stringify(err));
}
});
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
Otherwise just replace below code in your function
executor.executeAsync({
url : query,
method : "POST",
body: JSON.stringify(meta_data),
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type" : "application/json;odata=verbose",
"X-HTTP-Method": "MERGE",
"IF-MATCH": "*"
},
success: function (data) {
console.log(JSON.stringify(data));
},
error: function (err) {
console.log(JSON.stringify(err));
} });
It will also insert the digest for you, so you do not need add
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
Related
I've tried using axios and fetch to get data from an API endpoint, but turns out to have only returned an empty array. It works fine in Postman. What have I missed?
Using Axios
axios({
method: "get",
url: "/api/purchase/receivegoods/index?action=detail-grn",
params: {
goods_receive_id: 71,
},
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then((response) => {
console.log(("response", response));
})
.catch((error) => {
console.log("error message: ", error.message);
});
Using Fetch
fetch(
"https://devactive.com/api/purchase/receivegoods/index?action=detail-grn",
{
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
params: {
goods_receive_id: 71,
},
}
)
.then((response) => response.json())
.then((result) => {
console.log("Success:", result);
})
.catch((error) => {
console.error("Error:", error);
});
EDIT:
The request is in JSON format. It looks like this (this is an example of an existing id:
{
"goods_receive_id" : 71
}
check for possible proxy configuration, postman uses system proxy by default.
You are not passing the data as the body when using Axios or Fetch. You are hitting the endpoint though. Try something like this:
data = {
"goods_receive_id" : 71
}
axios({
method: "get",
url: "/api/purchase/receivegoods/index?action=detail-grn",
data: JSON.stringify(data), // <- You add the data to the body here
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then((response) => {
console.log(("response", response));
})
.catch((error) => {
console.log("error message: ", error.message);
});
or
data = {
"goods_receive_id" : 71
}
fetch(
"https://devactive.com/api/purchase/receivegoods/index?action=detail-grn",
{
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
data: JSON.stringify(data), // <- You add the data to the body here
}
)
.then((response) => response.json())
.then((result) => {
console.log("Success:", result);
})
.catch((error) => {
console.error("Error:", error);
});
I want to fetch an API
The call look like this;
const instance = axios.create({
method: 'GET',
uri: 'https://api.compound.finance/api/v2/account',
timeout: timeout,
params: {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
},
},
headers: {
"Content-Type": "application/json",
},
});
The API spec https://compound.finance/docs/api
{
"addresses": [] // returns all accounts if empty or not included
"block_number": 0 // returns latest if given 0
"max_health": { "value": "10.0" }
"min_borrow_value_in_eth": { "value": "0.002" }
"page_number": 1
"page_size": 10
}
However the output URI contains some character to replace { } arround max_health value
The uri end up looking like this;
/api/v2/account?block_number=0&page_number=1&page_size=250&max_health=%7B%22value%22:%221%22%7D'
I have tried qs but it's not working as I expect.
I have tryed this to ;
let params = {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
}
}
await instance.get('https://api.compound.finance/api/v2/account',JSON.stringify(params)).then( (response) => {...})
It gave me this error ;
TypeError: Cannot use 'in' operator to search for 'validateStatus' in
{"block_number":"0","page_number":"1","page_size":"250","max_health":{"value":"1"}}
Any help would be appreciated.
The fix;
Use paramSerializer
const instance = axios.create({
method: 'GET',
uri: 'https://api.compound.finance/api/v2/account',
timeout: timeout,
params: {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
},
},
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
headers: {
"Content-Type": "application/json",
},
});
Heading ##On execution of fetchCode function checkDuplicacy function doesn't execute
Heading ##function fetchCode(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('FeedbackList')/items?$select=EmployeeCode";
$.ajax({
url : requestUri,
type : "GET",
async : "false",
headers : {
"accept" : "application/json; odata=verbose"
},
success : checkDuplicacy,
error : onError
})
}
Alert the error if you not familiar with developer tool debug(insert script into script editor webpart directly).
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('car model')/items",
type: 'GET',
async: false,
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
}
})
.done(function (data, textStatus, jqXHR) {
var count = data.d.results.length;
alert(count);
})
.fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
})
.always(function () {
alert("complete");
});
</script>
i would like to delete item from list in SharePoint 2016. I use SharePoint REST API, but I cannot successfully delete item. This is error message (http code 400):
A node of type 'EndOfInput' was read from the JSON reader when trying to read the start of an entry.A 'StartObject' node was expected.
Here is my code:
$.ajax({
url: 'https://myshp.com/test/_api/web/lists(guid'e23e21c7-ab29-445e-87b8-2b20b721f79d')/items?$filter=ID eq '5'',
type: 'POST',
contentType: 'application/json;odata=verbose',
headers: {
"ACCEPT": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method-Override": "DELETE"
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
What is incorrect? Thanks
Please use below code: It works fine for me :
$.ajax({
url: "https://myshp.com/test/_api/web/lists(guid'e23e21c7-ab29-445e-87b8-2b20b721f79d')/items(5)",
type: 'POST',
contentType: 'application/json;odata=verbose',
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method": "DELETE"
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
})
The below code successfully adds items in the list, but I want to add item in the folder which is present in the list using REST API, list name is "Designation" and folder name is "Folder1". What changes should I make to insert item in folder?
$.ajax({
url:"https://brillio446.sharepoint.com/teams/Social2016/work/_api/web/lists/getByTitle('Designation')/items",
method:"POST",
dataType:"json",
data: JSON.stringify({
'__metadata': {'type': 'SP.Data.DesignationListItem' },
'Title': 'D1',
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
},
success: function(data){
alert("Item added successfully!");
},
error: function(err){
alert("Error while adding item: " + JSON.stringify(err));
}
});
I also find that folder path should be there so I tried this code...
But I got error that 'Path' does no exist in SP.Data.DesigantionListItem
data: JSON.stringify({
'__metadata': {'type': 'SP.Data.DesignationListItem' },
'Title': 'D1',
'Path': '/ServerRelativeUrl of folder',
}),
This is an old question, but search led me here, so adding answer for others.
As Vadim mentioned, /_api/web/lists/getbytitle('ListTitle')/items method does not support adding items to folder.
Instead, you should use /_api/web/lists/GetByTitle('ListTitle')/AddValidateUpdateItemUsingPath method.
Just make sure, you use string values instead of numbers or dates or similar, because it works same as you enter form - parse, validate and save values.
MSDN Reference: Create list item in a folder
Example:
$.ajax({
url:"https://brillio446.sharepoint.com/teams/Social2016/work/_api/web/lists/getByTitle('Designation')/AddValidateUpdateItemUsingPath",
method:"POST",
dataType:"json",
data: JSON.stringify({{
"listItemCreateInfo": {
"FolderPath": { "DecodedUrl": "/ServerRelativeUrl of folder" },
"UnderlyingObjectType": 0
},
"formValues": [
{
"FieldName": "Title",
"FieldValue": "D1"
}
],
"bNewDocumentUpdate": false
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
},
success: function(data){
alert("Item added successfully!");
},
error: function(err){
alert("Error while adding item: " + JSON.stringify(err));
}
});
It seems it is not supported to specify folder url while creating list item but you could consider the following approach:
create a ListItem resource
get associated File resource and move it into folder
Example
function executeJson(options)
{
var headers = options.headers || {};
var method = options.method || "GET";
headers["Accept"] = "application/json;odata=verbose";
if(options.method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: options.url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if("payload" in options) {
ajaxOptions.data = JSON.stringify(options.payload);
}
return $.ajax(ajaxOptions);
}
function createListItem(listTitle,properties,folderUrl){
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
return executeJson({
"url" :url,
"method": 'POST',
"payload": properties})
.then(function(result){
var url = result.d.__metadata.uri + "?$select=FileDirRef,FileRef";
return executeJson({url : url});
})
.then(function(result){
var fileUrl = result.d.FileRef;
var fileDirRef = result.d.FileDirRef;
var moveFileUrl = fileUrl.replace(fileDirRef,folderUrl);
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfilebyserverrelativeurl('" + fileUrl + "')/moveto(newurl='" + moveFileUrl + "',flags=1)";
console.log(url);
return executeJson({
"url" :url,
"method": 'POST',
});
});
}
Usage
var listTitle = "Requests"; //list title
var targetFolderUrl = "/Lists/Requests/Archive"; //folder server relative url
var itemProperties = {
'__metadata': { "type": "SP.Data.RequestsListItem" },
"Title": 'Request 123'
};
createListItem(listTitle,itemProperties,targetFolderUrl)
.done(function(item)
{
console.log('List item has been created');
})
.fail(function(error){
console.log(JSON.stringify(error));
});
Gist