I am trying to create a SharePoint list view through the SharePoint REST API, with a defined set of columns to be part of the view. The endpoint i am using is below:
POSTMAN API Request:
HTTP METHOD: POST
URL: https://tenantname.sharepoint.com/sites/SPSite/_api/web/lists/getbytitle('ListName')/views Headers:
Body (JSON):
{
"__metadata":{
"type":"SP.View"
},
"Title":"TestView",
"ViewFields":["Title","Name"]
}
I get a JSON error, since this payload does not seem to be right. Need help in understanding how to create a view with specific fields through the SharePoint REST API.
Thanks, Yesh
When creating view, it's not supported to add viewFields, this needs to be done after creating list view.
So please create the view like this firstly:
var viewQuery = "<OrderBy><FieldRef Name=\"ID\" /></OrderBy>";
$.ajax
({
// _spPageContextInfo.webAbsoluteUrl - will give absolute URL of the site where you are running the code.
// You can replace this with other site URL where you want to apply the function
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('MyList')/views",
type: "POST",
data: "{'__metadata':{'type': 'SP.View'},'ViewType': 'HTML','Title':'New View Created From REST','PersonalView':false,'ViewQuery':'" + viewQuery + "'}",
headers:
{
// Accept header: Specifies the format for response data from the server.
"Accept": "application/json;odata=verbose",
//Content-Type header: Specifies the format of the data that the client is sending to the server
"Content-Type": "application/json;odata=verbose",
// X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data, status, xhr) {
alert(data.d.Id);
},
error: function (xhr, status, error) {
console.log("Failed");
}
});
Then set Viewfield for the new created List View like this:
$.ajax
({
// _spPageContextInfo.webAbsoluteUrl - will give absolute URL of the site where you are running the code.
// You can replace this with other site URL where you want to apply the function
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('MyList')/Views(guid'58cfaaa2-107c-4a94-8490-38d1df195e5b')/ViewFields/addviewfield('Created')",
type: "POST",
headers:
{
// Accept header: Specifies the format for response data from the server.
"Accept": "application/json;odata=verbose",
//Content-Type header: Specifies the format of the data that the client is sending to the server
"Content-Type": "application/json;odata=verbose",
// X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data, status, xhr) {
console.log("Success");
},
error: function (xhr, status, error) {
console.log("Failed");
}
});
So the above sample is adding "Created" field into viewFields and View Guid is alert in first rerquest, use it in second request.