Retrieve Files & Items from SharePoint using Microsoft Graph API.

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

Why using Graph API ?

Recently i have the query from one developer he needs to show the file information from document library it always possible using SharePoint REST API. But they facing problem for some users who not have access to library. So let’s achieve the same using Ms Graph API

Endpoint: https://graph.microsoft.com/v1.0/sites/{siteid}/lists/{listid}/items

Permission Scope: Sites.Read.All

Follow the below article for your understanding how to fetch access token using Microsoft Graph API

In your tenant azure portal navigate to azure active directory “App Registration” Open your app to provide the permission for accessing the SharePoint site lists & libraries via Microsoft Graph API.

Once Navigated to the registered application -> Click API Permissions



Now Choose Add Permission -> Select Microsoft Graph API ->Application Permission -> Under “Sites” node select “Sites.Read.All”

Finally it look like below

Once done let’s display file information in SharePoint Content Editor Webpart with the help of some HTML/JQuery.

Create function name “requestToken()” to fetch the access token on page load

 function requestToken() {    
        $.ajax({  
            "async": true,  
            "crossDomain": true,  
            "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    
            "method": "POST",  
            "headers": {  
                "content-type": "application/x-www-form-urlencoded"  
            },  
            "data": {  
                "grant_type": "client_credentials",  
                "client_id ": "8baf0301-27df-44b1-b4fe-7911b9a918de", //Provide your app id    
                "client_secret": "tZ76oVPN039WlWPoAp+1aICq66vs7oUtE4lhDQYwxGY=", //Provide your secret    
                "scope ": "https://graph.microsoft.com/.default"  
            },  
            success: function(response) {  
                console.log(response);  
                token = response.access_token;  
                console.log(token);  
                FetchSharepointLibraries();
         
            },  
            error: function(error) {  
                console.log(JSON.stringify(error));  
            }  
        })  
    }  

Required Parameters:

Client ID, Client Secret,Scope, Grant_Type: client_credentials By default

After successfully retrieved the access token let’s create another function to query the SharePoint site lists/libraries

 function FetchSharepointLibraries(){

        var SPSiteID = "sharepointtechie.sharepoint.com,1a634409-8e14-4d07-b1a7-366eec870233,4047d743-691c-4578-9795-4c1458096e98";   // Sharepoint Site ID
        var ListID = "07f64111-6d12-47d0-9672-7124bdddce3b"; // List/LibraryID
        var GraphURL = "https://graph.microsoft.com/v1.0/sites/"+ SPSiteID +"/lists/"+ ListID +"/items";  //Constructed URL
        $.ajax({  
        method: 'GET',  
        url: GraphURL,  
        headers: {  
            'Authorization': 'Bearer ' + token,  
            'Content-Type': 'application/json'  
        },  
     success: function(response) {  
        var data = response.value;  
        console.log(data);  
       
    },error: function(error) {}    
    })
    }
  

Let’s do some fancy work to display the files

Full Code:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script type="text/javascript">
    var token;
    $(document).ready(function () {
        requestToken();
    });

    function requestToken() {

        $.ajax({
            "async": true,
            "crossDomain": true,
            "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    
            "method": "POST",
            "headers": {
                "content-type": "application/x-www-form-urlencoded"
            },
            "data": {
                "grant_type": "client_credentials",
                "client_id ": "8baf0301-27df-44b1-b4fe-7911b9a918de", //Provide your app id    
                "client_secret": "tZ76oVPN039WlWPoAp+1aICq66vs7oUtE4lhDQYwxGY=", //Provide your secret    
                "scope ": "https://graph.microsoft.com/.default"
            },
            success: function (response) {
                console.log(response);
                token = response.access_token;
                console.log(token);
                FetchSharepointLibraries();

            },
            error: function (error) {
                console.log(JSON.stringify(error));
            }
        })
    }

    function FetchSharepointLibraries() {

        var SPSiteID = "sharepointtechie.sharepoint.com,1a634409-8e14-4d07-b1a7-366eec870233,4047d743-691c-4578-9795-4c1458096e98";
        var ListID = "07f64111-6d12-47d0-9672-7124bdddce3b";
        var GraphURL = "https://graph.microsoft.com/v1.0/sites/" + SPSiteID + "/lists/" + ListID + "/items";
        $.ajax({
            method: 'GET',
            url: GraphURL,
            headers: {
                'Authorization': 'Bearer ' + token,
                'Content-Type': 'application/json'
            },
            success: function (response) {
                var data = response.value;
                var html = '';
                $.each(data, function (index, data) {
                    var fileName = data.webUrl.split("Shared%20Documents/")[1];
                    fileName = decodeURIComponent(fileName)
                    html += "<li><a href="+ data.webUrl +">"+ fileName +"</a></li><br>";
                })

                $('#files').append(html)
            }, error: function (error) { }
        })
    }
</script>

<body>
    <ul id="files"></ul>
</body>

Final output look like below

keep Sharing …..

Author Profile

Vinodh
Vinodh is a Microsoft MVP for SharePoint (Office Apps and Services) having 5+ years of experience in Microsoft Technologies.

His interest and expertise includes SharePoint Online Development, PowerApps Development, Flows for SharePoint and PowerApps. Single Page Apps/Add ins for SharePoint using React, Angular. SharePoint Farm Management, 2, 3 and upto 6 tier SharePoint Farm Installation and Configuration.

Awards :
Microsoft Most Valuable Professional for SharePoint and Office 365 awarded for the year 2016, 2017 and 2018.
C# Corner Most Valuable Professional for SharePoint and Office 365 awarded for the year 2016, 2017 and 2018.
Technology Expertise :
SharePoint Online, SharePoint 2013, SharePoint 2016 and SharePoint 2019 Preview.
Intranets both Modern and Classic, SharePoint Frameworks Customisation, SharePoint Add-ins, SharePoint single page apps.
Angular 5 with Bootstrap single page apps.
Typescript, JQuery and Javascript.
Micrsoft Flow and Powerapps.
Utilised :
Microsoft Graph API, SharePoint REST, SharePoint PnP JS.
Out of Box :
Consume Content search web parts for internet publishing sites using custom display templates.
Having knowledge on SharePoint workflows and SharePoint Designer workflows.
List customisation using JS Link, JSON Formatting.
Having knowledge in Active directory management services.
Create and configure service applications in SharePoint (MMS, UPSA, SSA).
Configure Outgoing email settings using SMTP Services.

Add a Comment

Your email address will not be published. Required fields are marked *