Integrating Graph API With Node.js App On Azure

Introduction
 
Today, in this write-up, let us learn how we can integrate SharePoint and Node.js App on Azure using Microsoft Graph API as a bridge.
 
Read permissions are enabled in the Microsoft Graph API to interact with SharePoint. In this scenario, all the site collections are retrieved via Microsoft Graph API. It's essential to form the URL and test on Graph Explorer. Once done, an app is registered on the Azure Portal. I have explained the detailed steps for that in this article. Post registration, a node.js Azure webapp will be created which, in turn, will call the app registered on Azure Portal using a token endpoint.
 
Setting up Microsoft Graph API
 
Test the query using Graph Explorer. It should result in success while using your SharePoint tenant here.
 
Integrating GraphAPI with Node.js App on Azure 
 
Registering App on Azure Portal
 
Create an App. Enter the details as shown below. We shall use SharePoint site URL in the Redirect URL text area.
 
Integrating GraphAPI with Node.js App on Azure 
 
Settting Permissions
 
Grant the Read permisssions. Don't forget to grant Admin Consent.
 
Integrating GraphAPI with Node.js App on Azure 
 
Generating Client Secret
 
Integrating GraphAPI with Node.js App on Azure 
 
Create NodeJS Web App on Azure
 
Open the Azure Cloud Shell and start executing the below commands.
 
Create Resource Group
  1. az group create --name myResourceGroup --location "South Central US"  
Create App Service Plan 
  1. az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku FREE  
Create WebApp
 
I have used nodeazuregraphapisp as <app_name>
  1. # Bash and Powershell  
  2. az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app_name>  
SetRuntime
  1. # Bash and Powershell  
  2. az webapp config appsettings set --resource-group myResourceGroup --name <app_name> --settings WEBSITE_NODE_DEFAULT_VERSION=8.11.1  
Code NodeJS in VsCode
 
Install node.js, Express, and npm.
 
Below is the code file for accessing the Graph API. Refer to the source code for complete details.
  1. <html>  
  2.       <head>  
  3.             <title>Microsoft Graph API</title>  
  4.          </head>  
  5.            
  6.          <body>  
  7.              
  8.                <a href="/home"> Home</a>  
  9.               
  10.                <a href="/GraphAPI-SharePoint"> SharePoint GraphAPI</a>  
  11.               
  12.                  
  13.             </body>  
  14.       <script type="text/css">  
  15.          p { word-breakbreak-all }  
  16.      </script>  
  17.      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
  18.        
  19.      <script type="text/javascript">  
  20.          $(document).ready(function() {  
  21.         
  22.              requestToken();  
  23.          });  
  24.        
  25.          var token;  
  26.        
  27.          
  28.          function requestToken() {  
  29.        
  30.              $.ajax({  
  31.                  "async"true,  
  32.                  "crossDomain"true,  
  33.                  "url""https://cors-anywhere.herokuapp.com/https://login.microsoftonline.com/yourtenantname.onmicrosoft.com/oauth2/v2.0/token", // Pass your tenant name     
  34.                  "method""POST",  
  35.                  "headers": {  
  36.                      "content-type""application/x-www-form-urlencoded"  
  37.                  },  
  38.                  "data": {  
  39.                      "grant_type""client_credentials",  
  40.                        
  41.                        "client_id ""2dd85589-51c5-xxx-xxx-xxxxxx"//Enter your client id  
  42.                       "client_secret""+{)}:1=f^5%z......",//Enter your client secret  
  43.                       
  44.                      "scope ""https://graph.microsoft.com/.default"  
  45.                  },  
  46.                  success: function(response) {  
  47.                      console.log(response);  
  48.                       
  49.                      token = response.access_token;  
  50.                      document.getElementById('access_token').innerHTML = token  
  51.   
  52.                      getSiteInformation();  
  53.                  },  
  54.        
  55.                      
  56.                    error: function(error) {   
  57.                      alert("token error" + JSON.stringify(error)) ;  
  58.                  console.log(JSON.stringify(error));    
  59.                 }    
  60.        
  61.              })  
  62.          }  
  63.                 
  64.      function getSiteInformation() {    
  65.          $.ajax({    
  66.              method: 'GET',    
  67.              url: "https://graph.microsoft.com/v1.0/sites?search=*",    
  68.              headers: {    
  69.                  'Authorization''Bearer ' + token,    
  70.                  'Content-Type''application/json'    
  71.              },    
  72.          }).success(function(response) {    
  73.              console.log(response);    
  74.             // alert("success");  
  75.              for(var i=0; i<response.value.length; i++){    
  76.               console.log(response.value[i].displayName);    
  77.                   
  78.               var html =   
  79.               "<tr><td>" + response.value[i].displayName+ "</td><td>" + response.value[i].webUrl+ "</td><td>" + response.value[i].createdDateTime+ "</td>";      
  80.                  $("#site_info").append(html);    
  81.      }  
  82.          }).error(function(error) {  
  83.              alert(JSON.stringify(error));  
  84.              console.log(JSON.stringify(error));   
  85.          });    
  86.      }          
  87.      </script>  
  88.      <p id="access_token"></p>  
  89.      <p id="site_info"></p>  
  90.        
  91. </html>  
Create Zip File
 
Run the below command in your VS Code Terminal.
  1. # PowerShell  
  2. Compress-Archive -Path * -DestinationPath myAppFiles.zip  
Integrating GraphAPI with Node.js App on Azure
 
Deploy Zip
 
Drag and drop the zip file at the below URL. It will automatically get unzipped and deployed.
 
https://<app_name>.scm.azurewebsites.net/ZipDeployUI 
 
Integrating GraphAPI with Node.js App on Azure
Access your Node.js App on Azure
 
https://nodeazuregraphapisp.azurewebsites.net/
 
Integrating GraphAPI with Node.js App on Azure
 
Reference
  • https://nodejs.org/en/ 
  • https://expressjs.com/ 
  • https://developer.microsoft.com/en-us/graph 
  • https://azure.microsoft.com/en-us/