spfx rest api read image column - sharepoint-online

I am trying to read image column in spfx using rest and nojS. THe site modern. I am unable to get the exact url. There are other properties like server relative url is returned. However is it possible to get the image and then it can be bound to image control?

You can convert json data into objects(My image column name is img).
var obj = eval('(' + data.d.img + ')');
$("#img").attr("src", obj.serverRelativeUrl);
I test with js, It should be similar in SPFX, you can refer to it.
Full test code:
<img id="img">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function () {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('test3')/items(17)",
method: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function (data) {
var obj = eval('(' + data.d.img + ')');
$("#img").attr("src", obj.serverRelativeUrl);
$("#img").attr("style", "width:50px;height:50px;")
}
});
})
</script>
Test result:

Related

Updating metadata file in sharepoint online via REST API

I upload a file to sharepoint and trying to update its metadata, but I always get error 400 in last step.
As far as I understand, sharepoint only handles lists and items. A "folder" is a list and both metadata and files inside are items. And a "file" is a list and its metadata are items.
Documentation about updating metadata say about to make a POST request to:
https: // {site_url} / _api / web / lists / GetByTitle ('{list_title}') / items ({item_id})
Updating files must be done by PUT method (not MERGE allowed), but updating metadata must be done specifically by MERGE method. I have tried both, and both failed.
This is my current updating metadata request, but I'm continuing getting an error 400.
var data = {
"__metadata": {
"type":type
},
"Description":"lorem ipsum"
};
var headerToken = {
headers: {
'Authorization':'Bearer ' + token
, 'X-HTTP-Method':'MERGE'
, 'Accept':'application/json;odata=verbose'
, 'Content-Type':'application/json;odata=verbose'
, 'Content-Length':JSON.stringify(data).length
, 'If-Match': etag
, 'X-RequestDigest': digest
}
};
try {
var response = await axios.post(
'https://{site_url}/_api/web/lists/GetByTitle("'+MY_FOLDER+'")/items('+id+')'
, JSON.stringify(data)
, headerToken
);
return response;
}
type, etag and id are get from uploading file response and digest is get from a request to contextinfo endpoint. MY_FOLDER is a test library and at this moment is a constant.
You need to use single quotes in getbytitle.
"https://{site_url}/_api/web/lists/GetByTitle('"+MY_FOLDER+"')/items("+id+")"
Updated:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
UpdateFolder()
function UpdateFolder(){
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Doc')/items(30)",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose",
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
},
data: "{__metadata:{'type':'SP.Data.DocItem'},test:'test'}",
/*where Title is column name and add your desired new data*/
success: function(data) {
console.log(data);
},
error: function(error) {
alert(JSON.stringify(error));
}
});
}
})
</script>

Is there a way to add a NavigationNode in Quick Launch under a given node not as a child using Sharepoint Rest API only?

Is there a way to add a Navigation node in Quick Launch below a given node (not as a child) using SharePoint Rest API
Sample code for your reference:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(document).ready(function ($) {
$("#createQuickLaunch").click(function () { createQuickLaunch() });
});
//Create a Quicklaunch Navigation
function createQuickLaunch() {
var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/navigation/QuickLaunch";
var headers = {
"accept": "application/json;odata=verbose",
"content-Type": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
}
var call = jQuery.ajax({
url: endPointUrl,
type: "POST",
data: JSON.stringify({
"__metadata": { type: "SP.NavigationNode" },
'IsExternal': true,
'Title': "Bing",
'Url': "http://www.bing.com"
}),
headers: headers
});
call.done(successHandler);
call.fail(failureHandler);
}
function successHandler(data, textStatus, jqXHR) {
SP.UI.Notify.addNotification("Navigation created Successully", false);
}
function failureHandler(errorMessage) {
alert("Request Failed: unable to Navigation: " + JSON.stringify(errorMessage));
}
</script>
<input type="button" title="createQuickLaunch" value="createQuickLaunch" id="createQuickLaunch"/>
Reference:
Add Quick Launch Link To SharePoint 2013 Site Using REST API

Sharepoint online: Programmatically post to news feed

I want to create a webpart which can post data to a specific Sharepoint's news feed, but have been unable to locate any good documentation. The only link I found was:
https://msdn.microsoft.com/library/e9ad06a1-831d-8ed0-c76e-8b049f14216f%28Office.15%29.aspx
My question is: what method can I use to post data to a Sharepoint-site's news feed?
In the link they mention that you can post to "the URL of a site feed". Is that the same as a news feed? Anyone who has done something similar?
We can use JSOM or REST API to achieve it.
REST API:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function(){
$.ajax( {
url: weburl + "/_api/social.feed/my/Feed/Post",
type: "POST",
data: JSON.stringify({
'restCreationData':{
'__metadata':{
'type':'SP.Social.SocialRestPostCreationData'
},
'ID': null,
'creationData':{
'__metadata':{
'type':'SP.Social.SocialPostCreationData'
},
'ContentText': "the post content text",
'UpdateStatusText':false
}
}
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(){
console.log("success to post ");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("POST error:\n" + xhr.status + "\n" + thrownError);
}
});
});
</script>
JSOM:
<script type="text/javascript" src="/_layouts/15/sp.userprofiles.js"></script>
<script type="text/javascript">
SP.SOD.executeOrDelayUntilScriptLoaded(WritePost, 'SP.UserProfiles.js');
function WritePost() {
var oclientContext;
var ofeedManager;
var oresultThread;
// Initialize the current client context and the SocialFeedManager instance.
oclientContext = SP.ClientContext.get_current();
ofeedManager = new SP.Social.SocialFeedManager(oclientContext);
// Add a link to be included in the post.
var olinkDataItem = new SP.Social.SocialDataItem();
olinkDataItem.set_itemType(SP.Social.SocialDataItemType.link);
olinkDataItem.set_text('My blog url');
olinkDataItem.set_uri('http://sundarnarasiman.net');
var osocialDataItems = [ olinkDataItem ];
// Set up the post content
var opostCreationData = new SP.Social.SocialPostCreationData();
opostCreationData.set_contentText('The text for the post, which contains a {0}.');
opostCreationData.set_contentItems(osocialDataItems);
// Write the post
oresultThread = ofeedManager.createPost(null, opostCreationData);
oclientContext.executeQueryAsync(WriteSucceeded, WriteFailed);
}
function WriteSucceeded(sender, args) {
//$get("ResultMessage").innerText = 'Successfully posted the message to Posts';
}
function WriteFailed(sender, args) {
//$get("ResultMessage").innerText = 'Failure in writing message' + args.get_message();
}
</script>
Refer to:
Post/Reply a post by Social feed REST API in SharePoint 2013
How to publish a post to SharePoint Social Feed using SharePoint 2013 JSOM

Issue in making cross-domain call to Project server oData feed from SharePoint Add-In (app)

I am developing a SharePoint Hosted Add-In which will display project server projects. I am using SP.RequestExecutor to make cross domain calls. It gives me the following error “Cannot find resource for the request ProjectData.”
I have given the Reporting (Project Server) Read permission in AppManifest file. Following is my code.
$(document).ready(function () {
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', initializePage);
});
function initializePage() {
hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
var scriptbase = hostweburl + "/_layouts/15/";
$.getScript(scriptbase + "SP.RequestExecutor.js", getProjectList);
}
function getProjectList() {
var executor;
executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: appweburl + "/_api/SP.AppContextSite(#target)/ProjectData/Projects?$filter=ProjectState eq 'In Progress'&$select=ProjectId,ProjectName&#target='" +
hostweburl + "'",
method: "GET",
crossDomain: true,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var jsonObject = JSON.parse(data.body);
alert(jsonObject.d.results);
},
error: function (error) {
alert(error.body);
}
}
);
}
There is no need to use SP.AppContextSite(#target).
Try below URL -
url: appweburl + "/_api/ProjectData/Projects?$filter=ProjectState eq
'In Progress'&$select=ProjectId,ProjectName"
The permissions for your app should include Read permissions for Reporting.

SharePoint 2010 REST API JQUery Insert, Update, Delete

Can anyone explain or point me to a link with samples of doing Update, Delete using Jquery with the SharePoint 2010 Rest API?
I have the insert working and of course queries since the MSDN documentation explains and every tutorial on the net explains queries but just wondering if anyone ever inserts, updates, deletes data instead of only samples and tutorials on querying? Yes I know I can use the CSOM but I want to learn how this is done via jquery and sharepoint rest?
Also I want to use Merge for updating.
Here's the working insert code:
function insertMilestone() {
var mileStonesListUrl = "/_vti_bin/listdata.svc/Milestones";
var milestone = {};
milestone.Title = "Testing from REST";
var entry = JSON.stringify(milestone);
$.ajax({
type: "POST",
url: mileStonesListUrl,
data: entry,
contentType: "application/json; charset=utf-8",
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
getAll();
}
});
}
How to perform CRUD operations using SharePoint 2010 REST Interface
Create
In order to perform a Create operation via REST, you must perform the following actions:
Create an HTTP request using the POST verb.
Use the service URL of the list to which you want to add an entity as
the target for the POST.
Set the content type to application/json.
Serialize the JSON objects that represent your new list items as a
string, and add this value to the request body
JavaScript example:
function createListItem(webUrl,listName, itemProperties, success, failure) {
$.ajax({
url: webUrl + "/_vti_bin/listdata.svc/" + listName,
type: "POST",
processData: false,
contentType: "application/json;odata=verbose",
data: JSON.stringify(itemProperties),
headers: {
"Accept": "application/json;odata=verbose"
},
success: function (data) {
success(data.d);
},
error: function (data) {
failure(data.responseJSON.error);
}
});
}
Usage
var taskProperties = {
'TaskName': 'Order Approval',
'AssignedToId': 12
};
createListItem('https://contoso.sharepoint.com/project/','Tasks',taskProperties,function(task){
console.log('Task' + task.TaskName + ' has been created');
},
function(error){
console.log(JSON.stringify(error));
}
);
Read
In order to perform a Read operation via REST, you must perform the following actions:
Create an HTTP request using the GET verb.
Use the service URL of the list item to which you want to add an
entity as the target for the GET.
Set the content type to application/json.
JavaScript example:
function getListItemById(webUrl,listName, itemId, success, failure) {
var url = webUrl + "/_vti_bin/listdata.svc/" + listName + "(" + itemId + ")";
$.ajax({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data.d);
},
error: function (data) {
failure(data.responseJSON.error);
}
});
}
Usage
getListItemById('https://contoso.sharepoint.com/project/','Tasks',2,function(taskItem){
console.log(taskItem.TaskName);
},
function(error){
console.log(JSON.stringify(error));
}
);
Update
To update an existing entity, you must perform the following actions:
Create an HTTP request using the POST verb.
Add an X-HTTP-Method header with a value of MERGE.
Use the service URL of the list item you want to update as the target
for the POST
Add an If-Match header with a value of the entity’s original ETag.
JavaScript example:
function updateListItem(webUrl,listName,itemId,itemProperties,success, failure)
{
getListItemById(webUrl,listName,itemId,function(item){
$.ajax({
type: 'POST',
url: item.__metadata.uri,
contentType: 'application/json',
processData: false,
headers: {
"Accept": "application/json;odata=verbose",
"X-HTTP-Method": "MERGE",
"If-Match": item.__metadata.etag
},
data: Sys.Serialization.JavaScriptSerializer.serialize(itemProperties),
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
},
function(error){
failure(error);
});
}
Usage
var taskProperties = {
'TaskName': 'Approval',
'AssignedToId': 12
};
updateListItem('https://contoso.sharepoint.com/project/','Tasks',2,taskProperties,function(item){
console.log('Task has been updated');
},
function(error){
console.log(JSON.stringify(error));
}
);
Delete
To delete an entity, you must perform the following actions:
Create an HTTP request using the POST verb.
Add an X-HTTP-Method header with a value of DELETE.
Use the service URL of the list item you want to update as the target
for the POST
Add an If-Match header with a value of the entity’s original ETag.
JavaScript example:
function deleteListItem(webUrl, listName, itemId, success, failure) {
getListItemById(webUrl,listName,itemId,function(item){
$.ajax({
url: item.__metadata.uri,
type: "POST",
headers: {
"Accept": "application/json;odata=verbose",
"X-Http-Method": "DELETE",
"If-Match": item.__metadata.etag
},
success: function (data) {
success();
},
error: function (data) {
failure(data.responseJSON.error);
}
});
},
function (error) {
failure(error);
});
}
Usage
deleteListItem('https://contoso.sharepoint.com/project/','Tasks',3,function(){
console.log('Task has been deleted');
},
function(error){
console.log(JSON.stringify(error));
}
);
Please follow List Items manipulation via REST API in SharePoint 2010 article for a more details.
Here is the update and delete, it wasn't as hard as I thought it was going to be and it works.
Hopefully this will help someone out because there is so much bogus information on using the REST API and I see a zillion posts on querying but none on Insert, Update, Delete.
//update
function updateMilestone(id) {
var mileStonesUrl = "/_vti_bin/listdata.svc/Milestones";
mileStonesUrl = mileStonesUrl + "(" + id+ ")";
var beforeSendFunction;
var milestoneModifications = {};
milestoneModifications.Title = "Updated from REST";
var updatedMilestoneData = JSON.stringify(milestoneModifications);
//update exsiting milestone
beforeSendFunction = function (xhr) {
xhr.setRequestHeader("If-Match", "*");
// Using MERGE so that the entire entity doesn't need to be sent over the wire.
xhr.setRequestHeader("X-HTTP-Method", 'MERGE');
}
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
processData: false,
beforeSend: beforeSendFunction,
url: mileStonesUrl,
data: updatedMilestoneData,
dataType: "json",
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
alert("Updated");
getAll();
}
});
function deleteMilestone(id) {
var mileStonesUrl = "/_vti_bin/listdata.svc/Milestones";
mileStonesUrl = mileStonesUrl + "(" + id+ ")";
$.ajax({
type: "DELETE",
contentType: "application/json; charset=utf-8",
processData: false,
url: mileStonesUrl,
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
alert("deleted");
getAll();
}
});
}
}
I recently worked with the REST API for SP 2013, as a Example POC that can be used for any call implementation i.e. JQuery, C# etc.
Using POSTMAN
First get your digest token:
A method was found on this site : http://tech.bool.se/basic-rest-request-sharepoint-using-postman/​
[Credit where credit is due]
POST
http://<SharePoint Domain Url>/sites/<Site name>/_api/contextinfo
Header:
Accept : application/json;odata=verbose
Body:
Clear the body ​
From the payload use "FormDigestValue" value and put it into your headers with the key : X-RequestDigest when making actions that alter items in SharePoint.
Reading data:
GET
http://<SharePoint Domain Url>/sites/<Site name>/_api/web/getfolderbyserverrelativeurl('/Sites/<Site Name>/Shared Documents/My Folder')/files?$select=Name
Headers:
Accept : application/json;odata=verbose​
When it comes to create, update , delete you need the digest token or an authorization token to perform these actions, this token is highlighted at the begining to to retrieve.
​Creating Data
POST
http://<SharePoint Domain Url>/sites/<Site Name>/_api/web/folders​
Headers:
Accept : application/json;odata=verbose
X-RequestDigest : 'GUID looking toking'
Content-Type : application/json;odata=verbose
Body:
{ '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '/Sites/<Site Name>/Shared Documents/Some Folder/POC3'}​
Note:
'ServerRelativeUrl' the folder on the end POC3 is the folder that I want to create
Related resources:
http://msdn.microsoft.com/en-us/library/office/fp142380(v=office.15).aspx
Note: PostMan was used for this example and other application may need you to url encode the endpoint.
The above Request Structure can be used for all requests, the related resource highlights some of the standard methods that can be used with the REST Api

Resources