SharePoint Online: [Rest API & SharePoint App] How to access other web context

Required App permission to be setup in order to access the web, under AppManifest.xml

Example code snippet:

SP.AppContextSite is the core part to call from App to SharePoint


var hostweburl =
        decodeURIComponent(getQueryStringParameter("SPHostUrl"));

var appweburl =
        decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

//Example: Get List Item
function getItems (listName, queryText, rowLimit) {
     var d = $.Deferred();
     var viewXml = '<View><Query>' + queryText + '</Query></View>';
     var query = {
         'query': {
            '__metadata': { 'type': 'SP.CamlQuery' },
            'ViewXml': viewXml
         }
     };
     //default limit
     var limit = 10;
     if (rowLimit)
        limit = rowLimit;
                
     var settings = {
        url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/GetByTitle('" + listName + "')/items?@target='" + hostweburl + "'&$top=" + limit,
        contentType: "application/json;odata=verbose",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {                                                
           d.resolve(data.d.results);
        },
        error: function (data) {
            d.reject(data);
        }
      };

      if (queryText) {
        settings["data"] = JSON.stringify(query);
      }

      $.ajax(settings);

      return d.promise();
}