Click here to Skip to main content
15,885,875 members
Articles / Productivity Apps and Services / Sharepoint
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
1 Sep 2017CPOL 9.3K  
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

  1. 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>
  2. Use cross-domain library JS file (sp.requestexecutor.js) for Rest API calls:
    JavaScript
    // Load the cross-domain library JS file                                          
    $.getScript(scriptbase + "SP.RequestExecutor.js",getHostListData);
    JavaScript
       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
           }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --