I am trying to construct the correct URL to return the items in a SharePoint View using the REST api.
Using my browser and the following URL I can return the items in the list.
https://mysharepoint.sharepoint.com/sites/MySite/_api/web/lists/getbytitle('Announcements')/Items
And I can get the view definition using the following URL.
https://mysharepoint.sharepoint.com/sites/MySite/_api/web/lists/getbytitle('Announcements')/Views/getbytitle('Latest News')/
But I cannot figure out what I need to put at the end of that URL to actually get the items that are returned by the the View.
SP.View object does not contain any methods for manipulating list items. But SP.View object contains SP.View.viewQuery property that specifies the query that is used by the list view. That means the following approach could be used for retrieving list items for view:
perform the first request to get CAML Query for List View using SP.View.viewQuery property
perform the second request to retrieve List Items by specifying CAML Query
How to return list items for a List View using REST API using JavaScript
function getJson(url)
{
return $.ajax({
url: url,
type: "GET",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
function getListItems(webUrl,listTitle, queryText)
{
var viewXml = '<View><Query>' + queryText + '</Query></View>';
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
var queryPayload = {
'query' : {
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml' : viewXml
}
};
return $.ajax({
url: url,
method: "POST",
data: JSON.stringify(queryPayload),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose"
}
});
}
function getListItemsForView(webUrl,listTitle,viewTitle)
{
var viewQueryUrl = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
return getJson(viewQueryUrl).then(
function(data){
var viewQuery = data.d.ViewQuery;
return getListItems(webUrl,listTitle,viewQuery);
});
}
Usage
getListItemsForView(_spPageContextInfo.webAbsoluteUrl,'Announcements','Latest News')
.done(function(data)
{
var items = data.d.results;
for(var i = 0; i < items.length;i++) {
console.log(items[i].Title);
}
})
.fail(
function(error){
console.log(JSON.stringify(error));
});
Related
Hi we are trying to retrieve the link URL of page in Site Pages using REST API the problem is that we cannot find the Name FileLeafRef property value.FileLeafReaf = null.
function fn_getListItems(webUrl,listTitle, queryText)
{
var viewXml = '<View><Query>' + queryText + '</Query></View>';
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
var queryPayload = {
'query' : {
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml' : viewXml
}
};
return fn_executeJson(url,"POST",null,queryPayload);
}
function fn_getListViewItems(webUrl,listTitle,viewTitle)
{
var url = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
return fn_executeJson(url).then(
function(data){
var viewQuery = data.d.ViewQuery;
return fn_getListItems(webUrl,listTitle,viewQuery);
});
}
function fn_executeJson(url,method,headers,payload)
{
method = method || 'GET';
headers = headers || {};
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if (typeof payload != 'undefined') {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}
Thanks.
SharePoint stores the full URL of a file in a hidden column EncodedAbsUrl.
So, you can request it explicitly as:
/_api/web/lists/getbytitle('Site Pages')/items?$select=*,EncodedAbsUrl
After that, you can directly use it somewhat as below, watch out for the quotes :
var items = data.d.results;
$.each(items, function(index, value) {
//Append results to DIV
$("#lstGlobalNews").append("<tr><td class='ms-vb2'><a href="+value.EncodedAbsUrl+" target='_blank'>"+value.Title+"</a></td><td class='ms-vb2' style='text-align: right;'>"+fn_FormatDate(value.Date_x0020_Posted)+"</td></tr>");
});
To retrieve FileLeafRef property, it needs to be explicitly specified in $select query option, for example:
/_api/web/lists/getbytitle('Site Pages')/items?$select=FileLeafRef
As alternative option it could also be retrieved via File resource, for example:
/_api/web/lists/getbytitle('Site Pages')/items?$select=File/Name&$expand=File
The FileLeafRef property only get the file name. If you want to get the file url, we need use ServerRelativeUrl property of file.
The REST API using this.
/_api/web/lists/getbytitle('Site%20Pages')/items?$select=File/ServerRelativeUrl&$expand=File
How to read sharepoint list items from a specific folders using Javascript/Jquery through JSOM or REST?
Using JSOM or CSOM, you need to specify 'FileDirRef' property in CAML Query, and add 'RecursiveAll' scope:
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(
'<View Scope="RecursiveAll"> " +
"<Query>" +
"<Where>" +
"<Eq>" +
"<FieldRef Name="FileDirRef" />" +
"<Value Type=\"Text\">yourFolderPath</Value>" +
"</Eq>" +
"</Where>" +
"</Query>" +
"</View>');
function GetFolders() {
var oWeb = _spPageContextInfo.webAbsoluteUrl;
var URLC = oWeb + "/_api/web/lists/getByTitle('ListName')/items";
$.ajax({
url: URLC,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
async: false,
cache: false,
success: function (data) {
$.each(data.d.results, function (index, item) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFolderByServerRelativeUrl('ListName/ListFolder)/listitemallfields/",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
async: false,
cache: false,
success: function (data) {
}
});
})
},
error: function (data) { }
});
}
You can use REST API to read list items from a specific folders using getfolderbyserverrelativeurl.
Refer below Code :
var folderRelativeUrl = "Relative_URL_Of_Your_Folder"; //here specify relative URL of your folder (e.g. '/Shared Documents')
getItemFromFolder().then(getItemFromFolderSuccess, getItemFromFolderFailed);
function getItemFromFolder(){
return $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfolderbyserverrelativeurl('" + folderRelativeUrl + "')/files?$expand=ListItemAllFields",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
function getItemFromFolderSuccess(data){
// success handler
var response = data.d.results; // This is Response Object from Server
}
function getItemFromFolderFailed(error){
// error handler code
}
I have a SharePoint list with two columns:
users (type people, multiple values allowed)
responsible_department (type string)
I want to get the items from this list where the current user is in the ùsers` field. The field can have multiple users (multiple users allowed)!
I am currently able to get the current user:
var currentUser;
function init() {
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
this.clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded() {
console.log(currentUser.get_loginName());
}
function onQueryFailed(sender, args) {
console.log('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
No i need to query the mutli user field in my list for all items where my current user is part of the people field. I dont know how to query for this.
Can someone help me out?
I found a solution on MSDN and this works for me:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var siteURL = _spPageContextInfo.webAbsoluteUrl;
var listname = "CustomList";
var currentUserId=_spPageContextInfo.userId;
var url = siteURL + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Title,PeopleField/ID&$filter=substringof('"+currentUserId+"',PeopleField/ID)&$expand=PeopleField/ID";
$.ajax({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items = data.d.results;
for(var i = 0; i < items.length;i++) {
var item=items[i];
console.log(item.Title);
}
},
error: function (data) {
}
});
});
</script>
I am trying to post reply on a particular discussion of SharePoint online discussion board through REST API but unable to do it. I don't want to use SP.utilities as this REST API will be called from Android App.
Below is the code which I am implementing:
$.ajax({
url:"../_api/web/Lists/getbytitle(listname)/items?$filter=ParentItemID eq 40",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(itemProperties),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*"
},
success: function (data) {
alert("Successfully posted!!");
},
error: function (error) {
alert("error");
console.log(JSON.stringify(error));
}
});
Instead of creating reply inside discussion, it is creating a new discussion item.
Any help will be highly appreciated.
For creating a message item (reply) in Discussion Board the following properties needs to be specified:
FileSystemObjectType for a message items needs to be set to 0
ContentTypeId- content type Id of message item
ParentItemID - discussion item (container for messages) id
Regarding ParentItemID property
ParentItemID property could not be specified via message payload since it is a read only property, it means the following query for creating a message item fails:
Url /_api/web/lists/getbytitle('Discussions')/items
Method POST
Data {
'__metadata': { "type": "SP.Data.DiscussionsListItem" },
'Body': "Message text goes here",
'FileSystemObjectType': 0,
'ContentTypeId': '<MessageContentTypeId>',
'ParentItemID': <DiscussionItemId>
}
Solution
The following example demonstrates how to to create a message (reply) in Discussion Board via SharePoint REST API.
For creating a message under a discussion item (folder) the following
approach is used: once message item is created, it's getting moved
under a discussion item
var listTitle = "Discussions"; //Discussions Board title
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var messagePayload = {
'__metadata': { "type": "SP.Data.DiscussionsListItem" }, //set DiscussionBoard entity type name
'Body': "Message text goes here", //message Body
'FileSystemObjectType': 0, //set to 0 to make sure Message Item is created
'ContentTypeId': '0x0107008822E9328717EB48B3B665EE2266388E', //set Message content type
'ParentItemID': 123 //set Discussion item (topic) Id
};
createNewDiscussionReply(webUrl,listTitle,messagePayload)
.done(function(item)
{
console.log('Message(reply) has been sent');
})
.fail(function(error){
console.log(JSON.stringify(error));
});
where
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("data" in options) {
ajaxOptions.data = JSON.stringify(options.data);
}
return $.ajax(ajaxOptions);
}
function createListItem(webUrl,listTitle,payload){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
return executeJson({
"url" :url,
"method": 'POST',
"data": payload
});
}
function moveListItem(webUrl,listTitle,itemId,folderUrl){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")?$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 = webUrl + "/_api/web/getfilebyserverrelativeurl('" + fileUrl + "')/moveto(newurl='" + moveFileUrl + "',flags=1)";
return executeJson({
"url" :url,
"method": 'POST'
});
});
}
function getParentTopic(webUrl,listTitle,itemId){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")/Folder";
return executeJson({
"url" :url,
});
}
function createNewDiscussionReply(webUrl,listTitle, messagePayload){
var topicUrl = null;
return getParentTopic(webUrl,listTitle,messagePayload.ParentItemID)
.then(function(result){
topicUrl = result.d.ServerRelativeUrl;
return createListItem(webUrl,listTitle,messagePayload);
})
.then(function(result){
var itemId = result.d.Id;
return moveListItem(webUrl,listTitle,itemId,topicUrl);
});
}
I'm trying to use RESTful services to return all replies in a SharePoint sitefeed. Currently, I am successfully using this code to retrieve the sitefeed's posts:
function getFeed(){
var feed;
var reply;
var rCounter;
$.ajax({
url: "https://<mysite>.sharepoint.com/<sitename>/_api/social.feed/actor(item=#v)/feed?#v=%27https://<mysite>.sharepoint.com/<sitename>/newsfeed.aspx%27",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// Returning the results
myFeed = $(data);
console.log(myFeed);
for (i = 0; i < myFeed[0].d.SocialFeed.Threads.results.length; i++) {
feed = (myFeed[0].d.SocialFeed.Threads.results[i].RootPost.Text);
console.log(myFeed[0].d.SocialFeed.Threads.results[0].Actors.results[1].Name + ": " + feed);
if (myFeed[0].d.SocialFeed.Threads.results[i].Replies.results.length >0){
rCounter = myFeed[0].d.SocialFeed.Threads.results[i].Replies.results.length;
for (j = 0; j < myFeed[0].d.SocialFeed.Threads.results[i].Replies.results.length; j++) {
rCounter--;
reply = myFeed[0].d.SocialFeed.Threads.results[i].Replies.results[rCounter].Text;
console.log(reply);
}
}
console.log("* * * * * * * * *");
}
},
error: function (data) {
console.log("ERROR - SEE CODE");
}
});
}
However, this gives me the posts but with only the two latest replies. According to this MSDN post, I need to use a POST method to get all replies and pass in the thread ID. So I made a new function:
function getPost(){
$.ajax({
url: "https://<mysite>.sharepoint.com/<sitename>/_api/social.feed/post(ID=ai)/?#ai='8.211b75cd6dc84fe4bc6c3e9f46971f51.97717348cd3048768103d55751dc0e2d.211b75cd6dc84fe4bc6c3e9f46971f51.819bde2276b948a8a120964289476489.17c08f26b90a4b659ff1fcfb0ede4025.5.5.1'",
method: "POST",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// Returning the results
console.log($(data));
},
error: function (data) {
console.log("ERROR - SEE CODE");
}
});
}
When I run this new function, I get a 403 (FORBIDDEN) error. Can someone tell me what I'm doing wrong?
try passing headers like below.
function getPost(){
$.ajax({
url: "https://<mysite>.sharepoint.com/<sitename>/_api/social.feed/post(ID=ai)/?#ai='8.211b75cd6dc84fe4bc6c3e9f46971f51.97717348cd3048768103d55751dc0e2d.211b75cd6dc84fe4bc6c3e9f46971f51.819bde2276b948a8a120964289476489.17c08f26b90a4b659ff1fcfb0ede4025.5.5.1'",
method: "POST",
headers: { "Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val() },
success: function (data) {
// Returning the results
console.log($(data));
},
error: function (data) {
console.log("ERROR - SEE CODE");
}
});
}