How to add Item in Folder present in the list using REST API in SharePoint? - rest

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

Related

How to format axios GET call with nested params

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",
},
});

Hosting a Forge Autodesk viewer on Github

I've an issue with the Forge viewer I'm developping : Im' trying to host it using Github-page, but it doesn't seem to work correctly.
The issue is on the File tree : when I load the viewer page from the Github pages, the file tree seems stuck on "Loading...". However, it correctly loads when I load the page from localhost.
The code of the File tree :
$(document).ready(function () {
prepareAppBucketTree();
$('#refreshBuckets').click(function () {
$('#appBuckets').jstree(true).refresh();
});
$('#createNewBucket').click(function () {
createNewBucket();
});
$('#createBucketModal').on('shown.bs.modal', function () {
$("#newBucketKey").focus();
})
$('#hiddenUploadField').change(function () {
var node = $('#appBuckets').jstree(true).get_selected(true)[0];
var _this = this;
if (_this.files.length == 0) return;
var file = _this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
_this.value = '';
}
});
break;
}
});
});
function createNewBucket() {
var bucketKey = $('#newBucketKey').val();
var policyKey = $('#newBucketPolicyKey').val();
console.log(bucketKey)
jQuery.post({
url: '/api/forge/oss/buckets',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'policyKey': policyKey }),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
$('#createBucketModal').modal('toggle');
},
error: function (err) {
if (err.status == 409)
alert('Bucket already exists - 409: Duplicated')
console.log(err);
}
});
}
function prepareAppBucketTree() {
$('#appBuckets').jstree({
'core': {
'themes': { "icons": true },
'data': {
"url": '/api/forge/oss/buckets',
"dataType": "json",
'multiple': false,
"data": function (node) {
return { "id": node.id };
}
}
},
'types': {
'default': {
'icon': 'glyphicon glyphicon-question-sign'
},
'#': {
'icon': 'glyphicon glyphicon-cloud'
},
'bucket': {
'icon': 'glyphicon glyphicon-folder-open'
},
'object': {
'icon': 'glyphicon glyphicon-file'
}
},
"plugins": ["types", "state", "sort", "contextmenu"],
contextmenu: { items: autodeskCustomMenu }
}).on('loaded.jstree', function () {
$('#appBuckets').jstree('open_all');
}).bind("activate_node.jstree", function (evt, data) {
if (data != null && data.node != null && data.node.type == 'object') {
// $("#MyViewerDiv").empty();
var urn = data.node.id;
getForgeToken(function (access_token) {
jQuery.ajax({
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn + '/manifest',
headers: { 'Authorization': 'Bearer ' + access_token },
success: function (res) {
if (res.status === 'success') callByUrn('urn:'+urn);
else $("#MyViewerDiv").html('The translation job still running: ' + res.progress + '. Please try again in a moment.');
},
error: function (err) {
var msgButton = 'This file is not translated yet! ' +
'<button class="btn btn-xs btn-info" onclick="translateObject()"><span class="glyphicon glyphicon-eye-open"></span> ' +
'Start translation</button>'
$("#MyViewerDiv").html(msgButton);
}
});
})
}
});
}
function autodeskCustomMenu(autodeskNode) {
var items;
switch (autodeskNode.type) {
case "bucket":
items = {
uploadFile: {
label: "Upload file",
action: function () {
uploadFile();
},
icon: 'glyphicon glyphicon-cloud-upload'
}
};
break;
case "object":
items = {
translateFile: {
label: "Translate",
action: function () {
var treeNode = $('#appBuckets').jstree(true).get_selected(true)[0];
translateObject(treeNode);
},
icon: 'glyphicon glyphicon-eye-open'
}
};
break;
}
return items;
}
function uploadFile() {
$('#hiddenUploadField').click();
}
function translateObject(node) {
$("#MyViewerDiv").empty();
if (node == null) node = $('#appBuckets').jstree(true).get_selected(true)[0];
var bucketKey = node.parents[0];
var objectKey = node.id;
jQuery.post({
url: '/api/forge/modelderivative/jobs',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'objectName': objectKey }),
success: function (res) {
$("#MyViewerDiv").html('Translation started! Please try again in a moment.');
},
});
}
Please note that Github Pages are used for serving static pages without any special server-side logic. Your Forge application requires a server to talk to as well, for example, to obtain a list of buckets for the tree view (by making a request to /api/forge/oss/buckets).
You could potentially host your application's server-side logic on something like Heroku, and then have your static HTML/CSS/JavaScript page on Github talk to that server (for example, https://my-forge-app.herokuapp.com/api/forge/oss/buckets). Just be careful about CORS.

Update list item using SharePoint REST API not working

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(),

Share custom story with staged image on Facebook using FB.ui no working

I have the following code that stage the canvas image and then create object to share it using FB.ui. Staging the image and create the object are working without problem but the share dialog not displayed. If I replaced the image parameter in create object with an image url it is working.
is there any wrong in my code:
var userAccessToken = $("#user_access_token").val();
var appAccessToken = $("#app_access_token").val();
try {
blob = dataURItoBlob(dataURL);
} catch (e) {
console.log(e);
}
var fd = new FormData();
fd.append("access_token", userAccessToken);
fd.append("file", blob);
try {
var imageURI;
$.ajax({
url: "https://graph.facebook.com/me/staging_resources",
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log("success " + data['uri']);
imageURI = data['uri'];
},
error: function (shr, status, data) {
console.log("error " + data + " Status " + shr.status);
},
complete: function () {
FB.api(
'https://graph.facebook.com/app/objects/myappnamespace:myobject',
'post',
{
access_token : appAccessToken,
object:{
app_id: myappid,
url: "myappurl",
title: "Sample Photo",
image: {
url:imageURI,
user_generated:true
},
description: ""
}
},
function(response) {
var objectId = response['id'];
FB.ui({
method: 'share_open_graph',
action_type: 'myappnamespace:myaction',
action_properties: JSON.stringify({
myobject:objectId
})
}, function(response){});
}
);
}
});
} catch (e) {
console.log(e);
}
finally I found the solution by changing user_generated parameter from true to false
now the code for creating object looks like below:
FB.api(
'https://graph.facebook.com/app/objects/myappnamespace:myobject',
'post',
{
access_token : appAccessToken,
object:{
app_id: myappid,
url: "myappurl",
title: "Sample Photo",
image: {
url:imageURI,
user_generated:false
},
description: ""
}
}

Is it possible to change the header config of an AngularJS $resource object?

Here's my code:
var userAuth;
var user = $resource('https://myservice.com/user/:id/', {id: '#_id'} ,{
login: {
method: 'POST',
params: {
id: 'login'
},
transformResponse: function(data) {
data = angular.fromJson(data);
userAuth = 'Kinvey '+data._kmd.authtoken;
return data;
}
},
current: {
method: 'GET',
params: {
id: '_me'
},
headers: {
'Authorization': userAuth
}
}
});
I want to be able to use the updated contents of the userAuth variable in the headers of the current endpoint of the resource, after it has been modified in the transformResponse of the login call. Is this even possible? If so, how?
EDIT: I am using Angular version 1.1.3 - this question is about changing the headers in the resource once they have been set, not settings them initially. Thanks
Assuming you are using the current stable release (1.0.8), although this feature is documented in the $resource page it has not been released.
AngularJS resource not setting Content-Type
EDIT:
See my comment below for the explaination of this code.
var customerHeaders = {
'Authorization' : ''
};
var user = $resource('https://myservice.com/user/:id/', {id: '#_id'} ,{
login: {
method: 'POST',
params: {
id: 'login'
},
transformResponse: function(data) {
data = angular.fromJson(data);
customHeaders.Authorization = 'Kinvey '+data._kmd.authtoken;
return data;
}
},
current: {
method: 'GET',
params: {
id: '_me'
},
headers: customHeaders
}
});