How to Make Rest API Calls in SharePoint Hosted App for Office 365/SharePoint Online ?





5.00/5 (2 votes)
Things to remember while using Rest API calls on SharePoint hosted App for Office 365/SharePoint Online
Introduction
While developing a Sharepoint hosted app in Office365/Sharepoint online environment for the first time, I have faced some challenges in Rest API call, I have used the same Rest query as I used previously in my Sharepoint hosted apps which I developed and deployed in onprem, but here in Office365, some unauthentication errors like 403/401 were thrown.
In this post, I have mentioned some workarounds for the issues that I faced.
Solution
- Always refer to the js source files and Ajax reference in the below order:
<script type="text/javascript" src="../Scripts/jquery-1.7.1.min.js"></script>(Any JS Reference) <script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script> <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script> <script type="text/javascript" src="/_layouts/15/sp.js"></script>
- Use cross-domain library JS file (sp.requestexecutor.js) for Rest API calls:
// Load the cross-domain library JS file $.getScript(scriptbase + "SP.RequestExecutor.js",getHostListData);
function getHostListData() { var reqestUrl = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle ('listName')/items?@target='" + hostweburl + "'"; // Initialize the RequestExecutor with the app web URL var executor = new SP.RequestExecutor(appweburl); // Issue the call against the host web. executor.executeAsync( { url: reqestUrl, method: "GET", headers: { "Accept": "application/json; odata=verbose" }, success: successHandler, error: errorHandler } ); } // Function to handle the success event. function successHandler(data) { // your code } // Function to handle the error event. function errorHandler(data, errorCode, errorMessage) { //your code }