Get HostWeb Resources using REST API

You have to keep some important scenario in your mind when your are trying to get the Information form the HostWeb via AppWeb........

Cross Domain Restriction - done by browser[due to this you can't able to get info from HostWeb]

use this two things in URL:

SP.AppContextSite(@target)

&@target='"+hostUrl+"'",

Let's see this in action:

(function () {
"use strict";

jQuery(function () {

var appUrl = GetUrlKeyValue("SPAppWebUrl");
var hostUrl = GetUrlKeyValue("SPHostUrl");

var call = jQuery.ajax({
url: appUrl + "/_api/SP.AppContextSite(@target)/Web/RootFolder/Folders?$expand=Files&@target='"+hostUrl+"'",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data, textStatus, jqXHR) {
var message = jQuery("#message");
message.text("");
jQuery.each(data.d.results, function (index, value) {
//here i don't wanna process empty folders Here value is the folder
if (value.Files.results.length > 0) {
showFiles(message, value); // value is the object representing Folders
}
});
});
call.fail(failHandler);
});

// showFiles implementation code
function showFiles(message, folder) {
message.append(folder.Name + ":"); // This will write the name of the Folder
// Below code will iterate through the file objects --> so in this Loop the value object represents a file
jQuery.each(folder.Files.results, function (index, value) {
message.append("<div style='padding-left:10px'>" + value.Name + "</div");
});
message.append("<br/>");
}

function failHandler(jqXHR, textStatus, errorThrown) {
var response = "";
try {
var parsed = JSON.parse(jqXHR.responseText);
response = parsed.error.message.value;
} catch (e) {
response = jqXHR.responseText;
}
alert("Call failed. Error: " + response);
}

})();

 

Download your file: 

GetResourcesOfHostWeb_ViaRESTAPI.js (1.84 kb)

 

May be you can see this error:

Solution for this error:

May be the User have the permission for access the resources of HostWeb but the App don't have, so for allowing the app to access the hostweb information you have to do some configuration in AppManifest.xml file.

See this in action:

Again issue:

So try this: Means give your app to Manage permission

 

Done:

See resources from the HostWeb:

Voila! Done.........

Add comment