gitbrent / sprestlib Goto Github PK
View Code? Open in Web Editor NEWJavaScript SharePoint REST Web Services Library
Home Page: https://gitbrent.github.io/SpRestLib/
License: MIT License
JavaScript SharePoint REST Web Services Library
Home Page: https://gitbrent.github.io/SpRestLib/
License: MIT License
Hi, how do I access a remote Sharepoint REST service?
Hi,
I'm using Angular 4 and I'm trying to use: var sprLib = require("sprestlib");
I keep getting this error:
ERROR in ./node_modules/sprestlib/dist/sprestlib.js
Module not found: Error: Can't resolve 'https' in 'C:\Users\USER\Documents\spapp\sp-app\node_modules\sprestlib\dist'
regards
Hi,
Is there any planning to implement some methods to manage (list, start & stop) list workflow instances?
Thanks,
The .rest()
method is ignoring options (not including them in REST queries) when queryCols
is not included:
CODE:
sprLib.rest({ url:'/sites/dev/_api/web/lists', queryFilter:'ID eq 99' })
RequestURL:
/sites/dev/_api/web/lists?_=1507783353329
CODE:
sprLib.rest({ url:'/sites/dev/_api/web/lists', queryCols:'ID', queryFilter:'ID eq 99' })
RequestURL:
/sites/dev/_api/web/lists?$select=ID&$top=1000&$filter=ID%20eq%2099&_=1507783353336
Hi,
Do you have any examples of access SharePoint List from within a Office Add-in. I've tried the following:
sprLib.rest({ url: '_api/contextinfo', type: 'POST' })
.then(arr => {
var strReqDig = arr[0].GetContextWebInformation.FormDigestValue;
return sprLib.list({ name: 'Tasks', requestDigest: strReqDig, baseUrl: '{url}' }).items()
.then(function (arrItems) {
showNotification("length: ", arrItems.length)
})
})
.then(obj => {
console.log('Item created!');
})
.catch(function (strErrMsg) { showNotification("Error: ",strErrMsg) });
{url} is pointing to my sharepoint site. when running, the error message i'm getting is:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Requested URL | https://localhost:44304/_api/contextinfo
Thanks
When calling sprLib.list() on a list with more than a 100 items, only the first 100 items are returned. How to set $top?
sprLib.list('list').items().then( data => { console.log(data) } )
(v1.7.0)
Here https://gitbrent.github.io/SpRestLib/docs/api-file.html#recycle-file must be example like this sprLib.file("filename").recycle(), please change delete() to recycle()
I am trying to simplify the returned values for a lookup column down to a list of Ids.
The Events list has a Supplier lookup column.
Initially I tried,
sprLib.list('Events').items({
listCols: {
EventId: { dataName: 'ID' },
SupplierIds: { dataFunc: function (objItem) { return objItem.SupplierId.results } }
}
})
But this doesn't work because SupplierId is not returned by the query. Instead it appears that this is required:
sprLib.list('Events').items({
listCols: {
EventId: { dataName: 'ID' },
SupplierId: { dataName: 'SupplierId' },
SupplierIds: { dataFunc: function (objItem) { return objItem.SupplierId.results } }
}
})
Is there a way to return SupplierIds without also returning the SupplierId object?
David
I like this library a lot, but am I able to use $expand? I have a column which is a lookup to another list - it would be great if I could use this library to expand the results - I can get $expand to work in a normal rest url but it doesn't look like $expand is a parameter option in sprLib? If it is, can you please point me to the demo page which shows how?
thanks
-Type: application/atom+xml;type=feed;charset=utf-8
Perhaps in an afront to my sanity, one of the sharepoint servers I am querying, despite requesting a JSON response, seems to be returning application/atom+xml.
I am certain when I ran the exact code about 4 weeks ago it was working, so I am assuming something may have changed in the server configuration that I wasn't aware of. It looks like the data is still being returned if I look at the raw response data, , but I am guessing SPRestLib isn't parsing it anymore..
Has anyone dealt with something similar to this?
On this link :https://github.com/gitbrent/SpRestLib#delete-item
delete function accept the item Id as int, but this is not true as the delete function want a json object {Id : ID}
Thanks
Defect Desc:
Ex:
This sprLib.list('Departments').getItems(['Id','Id'])
or:
sprLib.list('Departments').getItems({ listCols:['Id','Id'] })
.then(arr => console.log(arr[0]))
Results:
{Id: undefined}
Any plans to support batch requests https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/make-batch-requests-with-the-rest-apis?
I love this library and sometimes will need to loop through a list to make many updates and SharePoint online throttles me.
Thanks! #
SpRestLib is a great lib for sharepoint ! As a sharepoint client side developer(20% of my role) I liked the elegant & powerful APIs. It makes my work so easy and amazing output.
Especially I liked the people-picker a lot. I was trying to find a solution for almost a year and tried many libraries from GitHub but none worked for me. This one just worked after I passed the "requestDigest" to the query. And we don't need to load a lot of other sharepoint js files like what mentioned in other solutions.
however, this great feature is not even mentioned in the user manual, I think others like me might also miss this if they search in GitHub. I strongly suggest to mention the people picker in the user manual page: https://gitbrent.github.io/SpRestLib/docs/api-rest.html
Or if possible maintain this as a unique project and I believe many people will benefit from this a lot!
Again thanks a million for this great library. By the way I used "PptxGenJS" a lot. It saved me !
The user()
method takes options with names like title
, email
, etc.
If a user doesn't utilize the correct case, the user method returns the current user's properties (the API treats it as if a null value was passed). This is both an unwanted design outcome and a potentially confusing response for users.
The option names should be made case insensitive to correct the issue.
sprLib.user({ title:'Bill Gates' }).then(...) // Returns Bill's user properties
sprLib.user({ Title:'Bill Gates' }).then(...) // Returns the current users properties
My use case is about handling empty lists. It would greatly simplify some code if I didn't have to treat the empty list case as a special one.
Is it possible to have a canonical list of columns that sprLib identifies as columns shared by sprLib.list().items() and sprLib.list().cols()?
I would like to use sprLib.list().cols() to extract the schema returned by sprLib.list().items(). However, sprLib.list().cols() has one view and sprLib.list().items() another?
At the moment the list of columns returned by sprLib.list().items() is only knowable by introspection of the result which fails in the case of zero items.
Thanks
David
When I use only one option sprLib.list().items({ queryNext: { prevId: 29, maxItems: 5 } })
, it requests like this http://localhost:3000/_api/lists/getbytitle('UsersDetail')/items&p_ID=29&$top=5
.
You can see than before p_ID=29 stand &
intstead of ?
.
And I get an error Invalid argument
.
But if I add more than one option on request, like this:
sprLib.list(usersList).items({ listCols: ['ID'], queryNext: { prevId: 29, maxItems: 5 } });
, my request is good http://localhost:3000/_api/lists/getbytitle('UsersDetail')/items?%24skiptoken=Paged%3dTRUE%26p_ID%3d29&%24select=ID&p_ID=29&$top=5
and before my first GET argument stands question symbol ?
Is there any support of getting directly the members of a specific group given its name?
Hello,
When I am building my application based on sprLib, with npm and webpack, the file included in the build is sprestlib.js which does not contains the Jquery dependency.
import sprLib from 'sprestlib' is including this file instead of sprestlib.bundle.js which contains the jquery dependency.
To bypass this I modified the file sprestlib/package.json:
"main": "dist/sprestlib.js", --> "main": "dist/sprestlib.bundle.js",
Is this the expected behavior? Do I misunderstood something?
Why don't replace Jquery by a more specific library such as axios, lodash, etc...?
Thank you
I want a direct method (instead of using sprestLib.rest), to create and edit documents library folders.
Desc:
baseUrl
option is ignored by the underlying versions query.Test Case:
/sites/dev/
sprLib.list({ name:'Site Assets', baseUrl:'/sites/dev/sandbox' }).items({
listCols: {
id: {dataName: 'Id'},
file: {dataName:'FileLeafRef', getVersions:true }
}
})
.then(function(data){ return data; });
Result:
baseUrl
was ignored and the current site was queriedHi
Small detail, if the sprestlib-demo.html is added in a subfolder of sitepages and then made available through an demo.aspx in the same folder API accesses fail with 404 errors.
David
Hello,
I looked into the source code too but I did not find a way to pass the site url for "User Methods". I usually complete the application (js, css, html) locally and then when everything is fine I upload the package to sharepoint folder then users can access the .aspx pages (changed extension from html to aspx) So I always use the complete sharepoint site url.
So if you can set global var for the baseUrl for all functions or at least for the User Methods then it will be much more useful.
Currently I use the original Ajax call for all the projects
function currentLogin() {
$.ajax({
url: "xxxx/teams/apmt/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=DisplayName,Email",
async: false,
type: 'get',
headers: {
"Accept": "application/json;odata=verbose"
},
cache: false,
//dataType: 'json',
success: function(spJsonData) {
//get user name
var pageDisplayName;
var displayName = spJsonData.d.DisplayName
var isLongerDisplayName = displayName.search(/[(]/)
if (isLongerDisplayName != -1) {
var bracketStart = displayName.indexOf("(")
pageDisplayName = displayName.substring(0, bracketStart)
} else(pageDisplayName = spJsonData.d.DisplayName)
var loginMsg = "Welcome " + pageDisplayName
$("#login-name").html(loginMsg)
//get user mail id
$("#userMail").html(spJsonData.d.Email)
var picURL = "url(https://outlook.office365.com/owa/service.svc/s/GetPersonaPhoto?email=" + spJsonData.d.Email + ")"
$("#login-image").css("background-image", picURL)
},
error: function() {
$("#login-name").html("Welcome ,[...]")
}
});
}
Hi,
again this is a great library!
if I only need the "UserProfileProperties" the call will return all other "Person Properties" though the API will return only "UserProfileProperties" with function sprLib.user(options).profile('UserProfileProperties')
from the performance perspective the call returns a lot of info that we don't need, especially when the user has many peers or direct reports etc. If possible you may create a standalone function for UserProfileProperties only with below query :
Url = "https://xx.sharepoint.com/teams/3wuam/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)/UserProfileProperties?@v='i:0%23.f|membership|" + mailID + "'"
with above query we can get the UserProfileProperties much faster
just a suggestion but the existing functions are already great to go with :)
In the early versions (e.g. 1.4.0-beta) you have set default "queryLimit" to 1000 using "'$top=' + ( inObj.queryLimit ? inObj.queryLimit : APP_OPTS.maxRows );" but now this has been dropped in the last version. I understood you want to align with the default sharepoint behavior, however this is something we often forget and in most of the case we want to set the limit more than 100. So we have to give this parameter for each call , or if we forget users will only see 100 items and the issue would be reported sooner after we deploy the app.
If we still have 1000 as default value life will be much earlier for us :-) Because we don't need to take care of this (in most of the cases 1000 items can meet the needs). Maybe I am talking about my particular environment where we don't work with huge items in SP.
Do you have a plan to support User Profile api?
Hello,
I run below query but I saw it is a "POST" action and I got error:
"error":{"code":"-2130575251, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again."}}}
I tried to add the digest token but it did not work.
I used this API before but I used the "GET" Method and it worked for me.
//////////////////////////////
sprLib.user({
baseUrl: 'https://xxxx.sharepoint.com/teams/StrategyandPOA',
email: '[email protected]',
}).profile().then(function (objUser) {
console.log(objUser)
});
Hello,
I am facing the same problem as discussed on issue #5, I am using SpRestLib in a Sharepoint hosted app, into the default.aspx page, when making GET calls no problem, but when I call list('listname').create({data}),
with data as JSON object {name:"test", ...}, I get an error about page validation etc, in devtools I noted that there is no X-RequestDigest nor Payload in the post call.
How can I resolve the issue as there is no solution mentioned in the previous discussion #5 ?
Thanks in advance
It appears that SP REST Api support for adding and updating groups is relatively weak compared wtih other APIs. Is there anything that can be done witha d]
Hi,
I'm using the SpRestLib in Node and was unable to make sprLib.folder().add() work, I always got the error message "The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.".
When I do the call manually via
sprLib.rest({ type: "POST", url: vURL, requestDigest: token, metadata: false })
It does work, it seems that SharePoint expects the requestDigest for folder add operations as well.
To implement the enhancement in #38 you have made changes to sprLib.user(options).profile(). Now it seems we cannot provide any Properties from Person Properties like 'DirectReports', 'DisplayName' etc
sprLib.user(options).profile('DirectReports') -->this is not working, error: DirectReports"DirectReports
property does not exist in SP.UserProfiles.PeopleManager.UserProfileProperties"
sprLib.user(options).profile('Department')-->this is working fine, 'Department' is part of the UserProfileProperties
Uncaught TypeError: sprLib.file(...).checkout() is not a function
Was returned for the first time.
Any clue as to why this is so? I have been using this since June without issue, now today there is an issue.
sprLib.file(somefile).info() functions just fine!
#site location of code:
/sites/uat/vanilla
script.onload = function () {
sprLib.folder("SiteAssets").info().then(objSiteInfo => console.log(objSiteInfo));
}
Created: "2018-09-05T16:25:54"
FolderCount: 9
HasSubdirs: true
HasUniqueRoleAssignments: false
Hidden: false
ItemCount: 13
ListGUID: "{CB79ACA3-9E86-4C55-8DCE-88E6CD0E14ED}"
Modified: "2019-03-19T22:02:33"
Name: "SiteAssets"
ServerRelativeUrl: "/sites/UAT/SiteAssets"
TotalSize: 4812042
script.onload = function () {
sprLib.folder("/sites/uat/vanilla/SiteAssets").info().then(objSiteInfo => console.log(objSiteInfo));
}
Uncaught (in promise) (404) List does not exist.
The page you selected contains a list that does not exist. It may have been deleted by another user.
URL used: ../_api/web/Lists(guid'5519F739-A6AB-4D49-ABF1-EC6348B314AD')/rootFolder/Folders?$select=ListItemAllFields/Id&$expand=ListItemAllFields
may be related/similar to issue #27
GUID in alternate results is correct for the list requested.
Not add in default view the new created column, only inserted in edit mode:
var StartDate = {
'__metadata': {'type':'SP.FieldDateTime'},
'FieldTypeKind': 4,
'Title': 'Start Date',
'DisplayFormat': 0
};
. . .
sprLib.rest({
url: '/sites/MyDemo/_api/contextinfo',
type:'POST',
requestDigest: diggestCode,
data: JSON.stringify(StartDate)
}).then( alert( "Column has been created!"););
).catch( alert( "cant insert")
);
...
Hi,
I want upload files to a Sharepoint library, but didnt found a method to do this, do you plan to add it in the soonly?
Thanks
Good day!
When I try to create an item in a list I get the following error:
400 - {"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"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."}}}
const body = {
Name: action.userData.name,
Surname: action.userData.surname,
Alias: action.userData.alias,
Gin: action.userData.gin,
Location: action.userData.location,
Email: action.userData.email
};
return sprLib.list('NgPeople').create(body);
I guess it is related to sending 'data' or 'body' object during request.
Regards,
Zhandos
Hello,
I like this lib very much.
but it seems the following is not support right now. I wanted to always use the GUID because the list title can be changed by others.
sprLib.list({ listGUID:"the GUID", baseUrl:"the url" }).getItems...
The methods available for returning list items are paged. Can the pattern below be made more general or idiomatic?
The desired function
getRecords('Test',['ID', 'Title', 'SupplierId'])
.then(function(ret) {
console.log(ret);
});
returns
{list: 'Test', listCols: ['ID', 'Title', 'SupplierId'], data: [{},...]}
implementation
function getRecords(list, listCols) {
return new Promise(function(resolve) {
var data = [];
function innerGetRecords(dataPage) {
if (dataPage) {
data = data.concat(dataPage);
if ('__next' in dataPage[0]) {
sprLib.list(list)
.items({
listCols: listCols,
queryNext: dataPage[0].__next
})
.then(innerGetRecords)
.catch(errMsg => console.error(errMsg));
} else {
resolve({list: list,listCols: listCols,data: data})
}
} else {
sprLib.list(list)
.items({
listCols: listCols,
queryLimit: 5000 // library's upper limit
})
.then(innerGetRecords)
.catch(errMsg => console.error(errMsg));
};
}
innerGetRecords();
});
}
Hello,
Thanks for your interactif collaboration, I am want to format a Date field as I get items via sprLib.List().getItems(listCols), I user listCols Obj and set date:
{dataName:'DateFieldName',formatDate:'DATE'}
But I always get the unformatted date format
When I search in your code, there is no mention of the formatDate in getItems function.
Really enjoying the SpRestLib - fantastic and stable tool. I'm now porting code from SPOnline back to Onprem 2013 and what initially seemed to be a permission issue, appears to be a API difference between SPOnline and SP2013?
Using the demo sandbox on SPOnline
sprLib.site().groups()
works as expected. On SP2013 onprem
sprLib.site().groups()
generates an unending request to sign-in with different credentials and when the dialog is cancelled, the error message is:
ERROR
(401) Access denied. You do not have permission to perform this action or access this resource.
URL used: ../_api/web/SiteGroups?$select=Id,Title,Description,OwnerTitle,PrincipalType,AllowMembersEditMembership,Users/Id,Users/LoginName,Users/Title&$top=5000&$expand=Users/Id,Users/LoginName,Users
But if we modify the call to eliminate the $expand, directly calling the rest end point it works!
sprLib.rest({
url: '_api/web/SiteGroups?$select=Id,Title,Description,OwnerTitle,PrincipalType,AllowMembersEditMembership,Users/Id,Users/LoginName,Users/Title&$top=5000'
})
.------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.
| Users | Id | Title | PrincipalType | AllowMembersEditMembership | Description | OwnerTitle |
|---------------------------------------------------------------------------------------------------------|-----|----------------------------------------------------|---------------|----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------|
....
This appears to be an API difference between SPOnline and SP2013?
David
Using a url
value that begins with 'https' or 'http':
sprLib.rest({ url:'https://officetest.sharepoint.com/_api/web/sitegroups' })
is being sent to SP with a prepended "/"
Source: Issue #5
Desc: Add new option to .rest()
and List CRUD API's for "DigestToken" value to be passed (fall back to form element if available, thereby keeping current functionality intact)
I noticed when I only execute sprLib.user(options).profile() I saw below call is made, but we don't get any info from this call because we are trying to get info from sprLib.user(options).profile()
siteUrl/_api/Web/siteusers?$filter=Email%20eq%20%27UserMailID%27&$select=Id,Title,Email,LoginName,IsSiteAdmin,PrincipalType
Hi,
I need to have the npm package which contains the last commits
Thank you
Hello!
How is it possible to access __next property for pagination using List methods? I couldn't find any hints for paging in sprestlib documentation. API is really lightweight and very handy, it would be great to have paging options as well.
Regards,
Zhandos
Hello,
in issue# 8 (#8) we discussed to add the site url to the user methods, and It work at that time but it seems this is no long working after you introduced the "sprLib.baseUrl()"
error from console:
Warning: Check your options! Available user()
options are: id
,email
,login
,title
var siteUrl = 'https://xxx.sharepoint.com/teams/xxx'
sprLib.user({
baseUrl: siteUrl
}).info().then(function (objUser) {
console.log(objUser)
});
however this is working
sprLib.baseUrl('https://xxx.sharepoint.com/teams/xxxx');
sprLib.user().info().then(function (objUser) {
console.log(objUser)
});
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.