Retrieve Files And Items From SharePoint Using Microsoft Graph API

Introduction 

 
In this article, I have explained how to retrieve the items & files from SharePoint using Microsoft Graph API.
 

Why use Graph API?

 
Recently, I had the query from one developer who needs to show the file information from the document library, which is always possible using the SharePoint REST API. But they face problems for some users who not have access to the library. So let’s achieve the same using MS GraphAPI
 
Endpoint
 
https://graph.microsoft.com/v1.0/sites/{siteid}/lists/{listid}/items
 
Permission Scope
 
Sites.Read.All
 
In your tenant Azure portal, navigate to azure active directory “App Registration.” Open your app to provide permission for accessing the SharePoint site lists & libraries via Microsoft Graph API.
 
Retrieve Files And Items From SharePoint Using Microsoft Graph API
 
Once you've navigated to the registered application -> Click API Permissions
 
Retrieve Files And Items From SharePoint Using Microsoft Graph API
 
Now, choose Add Permission -> Select Microsoft Graph API ->Application Permission -> Under “Sites” node select “Sites.Read.All”
 
Finally, it looks like below:
 
Retrieve Files And Items From SharePoint Using Microsoft Graph API
 
Once done, let’s display file information in SharePoint Content Editor Webpart with the help of some HTML/JQuery.
 
Create the function name “requestToken()” to fetch the access token on a page load.
  1. function requestToken() {      
  2.        $.ajax({    
  3.            "async"true,    
  4.            "crossDomain"true,    
  5.            "url""https://howling-crypt-47129.herokuapp.com/https://login.microsoftonline.com/sharepointtechie.onmicrosoft.com/oauth2/v2.0/token", // Pass your tenant name instead of sharepointtechie      
  6.            "method""POST",    
  7.            "headers": {    
  8.                "content-type""application/x-www-form-urlencoded"    
  9.            },    
  10.            "data": {    
  11.                "grant_type""client_credentials",    
  12.                "client_id ""8baf0301-27df-44b1-b4fe-7911b9a918de"//Provide your app id      
  13.                "client_secret""tZ76oVPN039WlWPoAp+1aICq66vs7oUtE4lhDQYwxGY="//Provide your secret      
  14.                "scope ""https://graph.microsoft.com/.default"    
  15.            },    
  16.            success: function(response) {    
  17.                console.log(response);    
  18.                token = response.access_token;    
  19.                console.log(token);    
  20.                FetchSharepointLibraries();  
  21.           
  22.            },    
  23.            error: function(error) {    
  24.                console.log(JSON.stringify(error));    
  25.            }    
  26.        })    
  27.    }    
Required Parameters
 
Client ID, Client Secret,Scope, Grant_Type: client_credentials by default
 
After successfully retrieving the access token, let’s create another function to query the SharePoint site lists/libraries:
  1.  function FetchSharepointLibraries(){  
  2.   
  3.         var SPSiteID = "sharepointtechie.sharepoint.com,1a634409-8e14-4d07-b1a7-366eec870233,4047d743-691c-4578-9795-4c1458096e98";   // Sharepoint Site ID  
  4.         var ListID = "07f64111-6d12-47d0-9672-7124bdddce3b"// List/LibraryID  
  5.         var GraphURL = "https://graph.microsoft.com/v1.0/sites/"+ SPSiteID +"/lists/"+ ListID +"/items";  //Constructed URL  
  6.         $.ajax({    
  7.         method: 'GET',    
  8.         url: GraphURL,    
  9.         headers: {    
  10.             'Authorization''Bearer ' + token,    
  11.             'Content-Type''application/json'    
  12.         },    
  13.      success: function(response) {    
  14.         var data = response.value;    
  15.         console.log(data);    
  16.          
  17.     },error: function(error) {  
  18.        console.log(JSON.stringify(error))  
  19.    }      
  20.     })  
  21.     }  
Let’s do some fancy work to display the files.
 
Full Code
  1. <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>  
  2. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  3.   
  4. <script type="text/javascript">  
  5.     var token;  
  6.     $(document).ready(function () {  
  7.         requestToken();  
  8.     });  
  9.   
  10.     function requestToken() {  
  11.   
  12.         $.ajax({  
  13.             "async"true,  
  14.             "crossDomain"true,  
  15.             "url""https://howling-crypt-47129.herokuapp.com/https://login.microsoftonline.com/sharepointtechie.onmicrosoft.com/oauth2/v2.0/token", // Pass your tenant name instead of sharepointtechie      
  16.             "method""POST",  
  17.             "headers": {  
  18.                 "content-type""application/x-www-form-urlencoded"  
  19.             },  
  20.             "data": {  
  21.                 "grant_type""client_credentials",  
  22.                 "client_id ""8baf0301-27df-44b1-b4fe-7911b9a918de"//Provide your app id      
  23.                 "client_secret""tZ76oVPN039WlWPoAp+1aICq66vs7oUtE4lhDQYwxGY="//Provide your secret      
  24.                 "scope ""https://graph.microsoft.com/.default"  
  25.             },  
  26.             success: function (response) {  
  27.                 console.log(response);  
  28.                 token = response.access_token;  
  29.                 console.log(token);  
  30.                 FetchSharepointLibraries();  
  31.   
  32.             },  
  33.             error: function (error) {  
  34.                 console.log(JSON.stringify(error));  
  35.             }  
  36.         })  
  37.     }  
  38.   
  39.     function FetchSharepointLibraries() {  
  40.   
  41.         var SPSiteID = "sharepointtechie.sharepoint.com,1a634409-8e14-4d07-b1a7-366eec870233,4047d743-691c-4578-9795-4c1458096e98";  
  42.         var ListID = "07f64111-6d12-47d0-9672-7124bdddce3b";  
  43.         var GraphURL = "https://graph.microsoft.com/v1.0/sites/" + SPSiteID + "/lists/" + ListID + "/items";  
  44.         $.ajax({  
  45.             method: 'GET',  
  46.             url: GraphURL,  
  47.             headers: {  
  48.                 'Authorization''Bearer ' + token,  
  49.                 'Content-Type''application/json'  
  50.             },  
  51.             success: function (response) {  
  52.                 var data = response.value;  
  53.                 var html = '';  
  54.                 $.each(data, function (index, data) {  
  55.                     var fileName = data.webUrl.split("Shared%20Documents/")[1];  
  56.                     fileName = decodeURIComponent(fileName)  
  57.                     html += "<li><a href="+ data.webUrl +">"+ fileName +"</a></li><br>";  
  58.                 })  
  59.   
  60.                 $('#files').append(html)  
  61.             }, error: function (error) { }  
  62.         })  
  63.     }  
  64. </script>  
  65.   
  66. <body>  
  67.     <ul id="files"></ul>  
  68. </body>  
The final output look like below:
 
Retrieve Files And Items From SharePoint Using Microsoft Graph API
 
Happy Coding