Created
November 20, 2019 02:42
-
-
Save onequbit/66d95460467d321155f72ab02b16366f to your computer and use it in GitHub Desktop.
SharePoint REST API code snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getItemsREST(RESTurl) | |
{ | |
var deferred = $.Deferred(); | |
// console.log(url); | |
var result = ""; | |
var ajaxCall = { | |
url: _spPageContextInfo.webAbsoluteUrl + RESTurl, | |
type: "GET", | |
headers: { | |
"accept": "application/json;odata=verbose", | |
}, | |
async: false, | |
success: function(data) { | |
if (data.d.results) result = data.d.results; | |
else result = data.d; | |
deferred.resolve(result); | |
}, | |
error: function(error) { | |
console.log("Error in REST query: " + RESTurl); | |
// console.log(error.responseJSON.error.message.value); | |
alert(error.responseJSON.error.message.value); | |
deferred.reject(err); | |
}, | |
}; | |
$.ajax(ajaxCall); | |
return deferred.promise(result); | |
//return result; | |
} | |
function getItemsRESTuri(absoluteRESTurl) | |
{ | |
// console.log(url); | |
var result = ""; | |
var ajaxCall = { | |
url: absoluteRESTurl, | |
type: "GET", | |
headers: { | |
"accept": "application/json;odata=verbose", | |
}, | |
async: false, | |
success: function(data) { | |
if (data.d.results) result = data.d.results; | |
else result = data.d; | |
}, | |
error: function(error) { | |
console.log("Error in REST query: " + RESTurl); | |
alert(error.responseJSON.error.message.value); | |
}, | |
}; | |
$.ajax(ajaxCall); | |
return result; | |
} | |
function getListInfo2(listNameToQuery) | |
{ | |
//var urlForFieldsInternalName = "/_api/Web/Lists/GetByTitle('" + listNameToQuery + "')/Fields?$select=Title,InternalName&$filter=ReadOnlyField eq false"; | |
var urlForFieldsInternalName = "/_api/Web/Lists/GetByTitle('" + listNameToQuery + "')/Fields?$select=Title,InternalName,StaticName,EntityPropertyName,FieldTypeKind,TypeAsString,SchemaXml,ReadOnlyField"; | |
var listObj = []; | |
var fieldTypes = []; | |
var listFields = getItemsREST(urlForFieldsInternalName); | |
// console.log(listNameToQuery, "ListFields: ", listFields); | |
$.each( listFields, function(index1,value1) { | |
//console.log("listinfo: ", listNameToQuery, value1); | |
var name = value1.Title; | |
var field = {}; | |
var isExceptedReadOnly = | |
(value1.EntityPropertyName== "Author") || (value1.EntityPropertyName== "Editor") || | |
(value1.EntityPropertyName== "Created") || (value1.EntityPropertyName== "Modified"); | |
if ( | |
(value1.InternalName != "MetaInfo") && ( | |
(value1.ReadOnlyField == false) || isExceptedReadOnly | |
) | |
) { | |
field["listname"] = listNameToQuery; | |
field["name"] = value1.EntityPropertyName; | |
field["staticname"] = value1.StaticName; | |
field["displayname"] = value1.Title; | |
field["type"] = value1.TypeAsString; | |
if ( (value1.TypeAsString == "Text") || | |
(value1.TypeAsString == "Note") || | |
(value1.TypeAsString == "Number") || | |
(value1.TypeAsString == "Choice") || | |
(value1.TypeAsString == "MultiChoice") ) { | |
// field["queryselect"] = value1.InternalName; | |
} | |
if ( (value1.TypeAsString == "User") || | |
(value1.TypeAsString == "UserMulti") ) { | |
field["name"] = value1.EntityPropertyName; | |
field["queryselect"] = value1.InternalName + "/Title"; | |
field["queryexpand"] = value1.InternalName; // + "/Title"; | |
// if (isExceptedReadOnly) field["name"] += "Id"; | |
} | |
if ( (value1.TypeAsString == "Lookup") || | |
(value1.TypeAsString == "LookupMulti") ) { | |
field["queryselect"] = value1.InternalName + "/Title"; | |
field["queryexpand"] = value1.InternalName; // + "/Title"; | |
} | |
// console.log(field); | |
listObj.push(field); | |
} | |
}); | |
return listObj; | |
} | |
function getDisplayNameLookups(listname) | |
{ | |
var nameLookupsObj = []; | |
var type = []; | |
var queryselect = ""; | |
var queryexpand = ""; | |
var listFields = getListInfo2(listname); | |
//console.log("field lookups:", listname, listFields); | |
$.each(listFields,function(index,item) { | |
// console.log(index,item); | |
var internalName = item.name; | |
var displayName = item.displayname; | |
var internalNameLower = item.name.toLowerCase(); | |
var displayNameLower = item.displayname.toLowerCase(); | |
if ( (item.type == "User") || | |
(item.type == "Lookup") || | |
(item.type == "UserMulti") || | |
(item.type == "LookupMulti") || | |
(item.type == "Text") || | |
(item.type == "Note") || | |
(item.type = "Number") || | |
(item.type == "Choice") || | |
(item.type == "MultiChoice") ) { | |
// console.log("lookups item: ", item); | |
if (typeof item.queryselect !== "undefined") | |
queryselect += item.queryselect + ","; | |
if (typeof item.queryexpand !== "undefined") | |
queryexpand += item.queryexpand + ","; | |
nameLookupsObj[internalName] = displayName; | |
nameLookupsObj[displayName] = internalName; | |
nameLookupsObj[internalNameLower] = displayName; | |
nameLookupsObj[displayNameLower] = internalName; | |
type[displayName] = item.type; | |
} | |
}); | |
nameLookupsObj.type = type; | |
nameLookupsObj.queryselect = queryselect.substring(0,queryselect.length-1); | |
nameLookupsObj.queryexpand = queryexpand.substring(0,queryexpand.length-1); | |
// console.log(nameLookupsObj); | |
return nameLookupsObj; | |
} | |
function getListItemById(listname, id, successmethod, failuremethod) { | |
var fieldLookups = getDisplayNameLookups(listname); | |
// console.log("fieldLookups:", fieldLookups); | |
var selectquery = "&$select=" + fieldLookups.queryselect + ",*"; | |
var expandquery = "&$expand=" + fieldLookups.queryexpand; | |
// console.log(_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")?" + selectquery + expandquery); | |
var result = ""; | |
$.ajax({ | |
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")?" + selectquery + expandquery, | |
method: "GET", | |
async: false, | |
headers: {"Accept": "application/json;odata=verbose" }, | |
success: function (data) { | |
result = successmethod(data.d); | |
for (var fieldname in result) { | |
var displayname = fieldLookups[fieldname]; | |
if ( displayname != fieldname ) { | |
result[displayname] = result[fieldname]; | |
} | |
if ( (fieldLookups.type[displayname] == "Lookup") || | |
(fieldLookups.type[displayname] == "User") ){ | |
console.log("list item fieldname: " + fieldname + ":" + fieldLookups.type[displayname], result[fieldname].Title," --> " + displayname ); | |
result[displayname] = result[fieldname].Title; | |
} | |
} | |
$.extend( result, { FieldLookups : fieldLookups } ); | |
}, | |
error: function(ಠ_ಠ) { | |
console.log(JSON.stringify(ಠ_ಠ)); | |
}, | |
}); | |
return result; | |
} | |
function getListItems(listname, filterquery, successmethod, failuremethod) { | |
var deferred = $.Deferred(); | |
var fieldLookups = getDisplayNameLookups(listname); | |
// console.log("fieldLookups:", fieldLookups); | |
var selectquery = "&$select=" + fieldLookups.queryselect + ",*"; | |
var expandquery = "&$expand=" + fieldLookups.queryexpand; | |
var filter = ""; | |
//console.log("filterquery: " + filterquery); | |
if (filterquery !== "undefined") | |
filter = (filterquery.length > 0) ? "&" + filterquery : ""; | |
// console.log("querying:" + listname + " for '" + filterquery + "' at: " + _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items?" + selectquery + expandquery + "&" + filter); | |
var resultArray = null; | |
$.ajax({ | |
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items?" + selectquery + expandquery + filter, | |
method: "GET", | |
async: false, | |
headers: {"Accept": "application/json; odata=verbose" }, | |
success: function (data) { | |
resultArray = successmethod(data.d.results); | |
//console.log("resultArray: ", resultArray); | |
for (var resultIndex in resultArray) { | |
//var result = resultArray[resultIndex]; | |
// console.log(listname," result:",result ); | |
for (var fieldname in resultArray[resultIndex]) { | |
var displayname = fieldLookups[fieldname]; | |
// console.log(listname,", (field:)" + fieldname + ", (displayname:)" + displayname); | |
// console.log("... (type):" + fieldLookups.type[displayname], result[fieldname], " --> " + displayname ); | |
if ( displayname != fieldname ) { | |
resultArray[resultIndex][displayname] = resultArray[resultIndex][fieldname]; | |
} | |
if ( (fieldLookups.type[displayname] == "Lookup") || | |
(fieldLookups.type[displayname] == "User") ){ | |
resultArray[resultIndex][displayname] = resultArray[resultIndex][fieldname].Title; | |
} | |
} | |
$.extend( resultArray[resultIndex], { FieldLookups : fieldLookups } ); | |
} | |
deferred.resolve(resultArray); | |
}, | |
error: function(ಠ_ಠ) { | |
console.log(JSON.stringify(ಠ_ಠ)); | |
}, | |
}); | |
return deferred.promise(resultArray); | |
} | |
function getListItems2(listname, filterquery) { | |
var fieldLookups = getDisplayNameLookups(listname); | |
// console.log("fieldLookups:", fieldLookups); | |
var selectquery = "&$select=" + fieldLookups.queryselect + ",*"; | |
var expandquery = "&$expand=" + fieldLookups.queryexpand; | |
var filter = ""; | |
//console.log("filterquery: " + filterquery); | |
if (filterquery !== "undefined") | |
filter = (filterquery.length > 0) ? "&" + filterquery : ""; | |
// console.log("querying:" + listname + " for '" + filterquery + "' at: " + _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items?" + selectquery + expandquery + "&" + filter); | |
var resultArray = null; | |
$.ajax({ | |
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items?" + selectquery + expandquery + filter, | |
method: "GET", | |
async: false, | |
headers: {"Accept": "application/json; odata=verbose" }, | |
success: function (data) { | |
resultArray = data.d.results; | |
//console.log("resultArray: ", resultArray); | |
for (var resultIndex in resultArray) { | |
//var result = resultArray[resultIndex]; | |
// console.log(listname," result:",result ); | |
for (var fieldname in resultArray[resultIndex]) { | |
var displayname = fieldLookups[fieldname]; | |
// console.log(listname,", (field:)" + fieldname + ", (displayname:)" + displayname); | |
// console.log("... (type):" + fieldLookups.type[displayname], result[fieldname], " --> " + displayname ); | |
if ( displayname != fieldname ) { | |
resultArray[resultIndex][displayname] = resultArray[resultIndex][fieldname]; | |
} | |
if ( (fieldLookups.type[displayname] == "Lookup") || | |
(fieldLookups.type[displayname] == "User") ){ | |
resultArray[resultIndex][displayname] = resultArray[resultIndex][fieldname].Title; | |
} | |
} | |
$.extend( resultArray[resultIndex], { FieldLookups : fieldLookups } ); | |
} | |
}, | |
error: function(ಠ_ಠ) { | |
console.log(JSON.stringify(ಠ_ಠ)); | |
}, | |
}); | |
return resultArray; | |
} | |
function getUserInfoREST(userName) | |
{ | |
var usrObj = {}; | |
var urlForUserProperties = "/_api/Web/SiteUsers()?$filter=Title eq '" + userName + "'&$top=1";// &$filter=Email ne ''"; | |
var userinfo = getItemsREST(urlForUserProperties); | |
return userinfo[0]; | |
} | |
function getMyUserInfoREST() | |
{ | |
var usrObj = {}; | |
var urlForUserProperties = "/_api/Web/SiteUsers()?$filter=Id eq " + _spPageContextInfo.userId; | |
var userinfo = getItemsREST(urlForUserProperties); | |
// console.log("getMyUserInfoREST()", userinfo); | |
return userinfo[0]; | |
} | |
function updateListItem(listname, id, dataToUpdate, successmethod, failuremethod) | |
{ | |
//console.log("dataToUpdate:", dataToUpdate); | |
var itemToUpdate = getListItemById(listname, id, function(data) { | |
//console.log("itemToUpdate obtained"); | |
console.log(data); | |
return data; | |
}, function(){} ); | |
var item = $.extend( | |
{ '__metadata': itemToUpdate.__metadata }, | |
dataToUpdate | |
); | |
console.log(item); | |
getListItemById(listname, id, function(data) { | |
var ajaxObj = | |
{ | |
async: false, | |
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('" + listname + "')/items(" + id + ")", | |
type: "POST", | |
contentType: "application/json;odata=verbose", | |
dataType:"json", | |
data: JSON.stringify(item), | |
headers: { | |
"Accept":"application/json;odata=verbose", | |
"X-RequestDigest": $("#__REQUESTDIGEST").val(), | |
"X-HTTP-Method": "MERGE", | |
"If-Match": "*", | |
}, | |
success: function(data) { | |
//console.log("inner ajax call succeeded"); | |
successmethod(data); | |
}, | |
error: function(error) { | |
console.log("inner ajax call failed"); | |
console.log(JSON.stringify(error)); | |
}, | |
} | |
$.ajax(ajaxObj); | |
}, function(sender, args) { | |
console.log("ajax call failed"); | |
console.log(sender,args); | |
failuremethod(sender, args); | |
}); | |
} | |
function createListItem(listName, itemProperties) { | |
var item = $.extend( | |
{"__metadata": { "type" : GetItemTypeForListName(listName) }}, | |
itemProperties | |
); | |
$.ajax({ | |
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items", | |
type: "POST", | |
processData: false, | |
contentType: "application/json;odata=verbose", | |
data: JSON.stringify(item), | |
headers: { | |
"Accept": "application/json;odata=verbose", | |
"X-RequestDigest": $("#__REQUESTDIGEST").val() | |
}, | |
success: function(data) { | |
console.log("inner ajax call succeeded"); | |
//console.log(data); | |
return data.d; | |
}, | |
error: function(error) { | |
console.log("inner ajax call failed"); | |
console.log(JSON.stringify(error)); | |
} | |
}); | |
} | |
function GetItemTypeForListName(name) { | |
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem"; | |
} | |
function updateListItemFields2(listName, listItemID, nameValuePairs, isDeferred) | |
{ // this function is being used in AFRForm.html | |
console.log("attempting to update list item " + listItemID + " with " + nameValuePairs.length + " item(s)"); | |
// make this deferred so it can run synchronously | |
var deferThis = null; | |
if (typeof isDeferred === 'undefined') isDeferred = false; | |
if (isDeferred) deferThis = jQuery.Deferred(); | |
// standard client context query setup... | |
var clientContext = new SP.ClientContext.get_current(); | |
// obtain a reference to the target list to query | |
var oList = clientContext.get_web().get_lists().getByTitle(listName); | |
// target the list item to be updated | |
this.oListItem = oList.getItemById(listItemID); | |
$.each(nameValuePairs, // iterate over the array of name-value pairs to be updated | |
function(index,field) { | |
$.each(field, // iterate over the individual pair to get the key and value | |
function(key,value) { | |
console.log("fieldname: " + key + ", value:" + value); | |
oListItem.set_item(key, value); // the key must be the List field internal name | |
} | |
) | |
} | |
); | |
// do the update | |
oListItem.update(); | |
clientContext.executeQueryAsync( // <-- haha, not really | |
function() { | |
console.log("List item " + listItemID + " updated"); | |
if (isDeferred) deferThis.resolve(); | |
}, | |
function(sender, args) { | |
console.log(args.get_message()); | |
if (isDeferred) deferThis.resolve(sender, args); | |
} | |
); | |
if (isDeferred) return deferThis.promise(); // we now return to your regularly asychronous programming | |
else return false; | |
} | |
function getRoleAssignmentName(RoleAssignmentObject) | |
{ | |
var uri = RoleAssignmentObject.RoleDefinitionBindings.__deferred.uri; | |
var foo = getItemsRESTuri(uri); | |
//console.log("RoleDefinition: ", foo[0]); | |
return foo[0].Name; | |
} | |
function getRoleAssignmentId(RoleAssignmentObject) | |
{ | |
var uri = RoleAssignmentObject.RoleDefinitionBindings.__deferred.uri; | |
var foo = getItemsRESTuri(uri); | |
//console.log("RoleDefinition: ", foo[0]); | |
return foo[0].Id; | |
} | |
function getRoleMemberName(RoleAssignmentObject) | |
{ | |
var uri = RoleAssignmentObject.Member.__deferred.uri; | |
var foo = getItemsRESTuri(uri); | |
//console.log("RoleAssignment: ", foo); | |
return foo.Title; | |
} | |
function getRoleMemberId(RoleAssignmentObject) | |
{ | |
var uri = RoleAssignmentObject.Member.__deferred.uri; | |
var foo = getItemsRESTuri(uri); | |
//console.log("RoleAssignment: ", foo); | |
return foo.Id; | |
} | |
/* | |
function getAllLists1() { | |
var context=SP.ClientContext.get_current(); | |
var lists = context.get_web().get_lists(); | |
//context.load(lists, 'Include(RootFolder)'); | |
context.load(lists); | |
context.executeQueryAsync( | |
function() { | |
var enumerator = lists.getEnumerator(); | |
while (enumerator.moveNext()) { | |
var list = enumerator.get_current(); | |
var ishidden = list.get_hidden(); | |
var listtitle = list.get_title(); | |
var GUID = list.get_id(); | |
//var url = rootFolder.get_serverRelativeUrl(); | |
// if (!ishidden) console.log(listtitle + ":" + GUID ); | |
if (!ishidden) { | |
$("#chooseList").append("<option value='" + GUID + "'>" + listtitle + "</option>"); | |
} | |
} | |
}, function (ಠ_ಠ) { | |
console.log(ಠ_ಠ); | |
} | |
); | |
} | |
*/ | |
/* | |
function getAllListGUIDs() { | |
var listGUIDCollection = []; | |
$().SPServices({ | |
operation: "GetListCollection", | |
async:false, | |
completefunc: | |
function( xData, Status ){ | |
$( xData.responseXML ).find("Lists > List").each(function() { | |
var $node = $(this); | |
var name = $node.attr("Title"); | |
var guid = $node.attr("ID"); | |
listGUIDCollection [name] = guid; | |
}) | |
} | |
}); | |
return listGUIDCollection ; | |
} | |
*/ | |
/* | |
function getListViewWebPartGUIDs() | |
{ | |
var listViewWebPartGUIDLookup = []; | |
var listViewWebParts = $("div[class^='ms-webpart']").children("div[haspers='false']").find("table[class*='ms-listviewtable'][summary]") | |
$.each(listViewWebParts, function(index,item) { | |
// console.log( $(item).attr("summary") + ":{" + $(item).attr("id").split("}-{")[1] ); | |
}); | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment