In Focus

Get All The SharePoint Site Collection Usage Details Using Graph API

In this article, we will see the steps to check all the SharePoint site collection usage details using Graph API. The process is quite simple; just follow along.

In this article, I will explain the steps to check all the SharePoint site collection usage details and the process of getting the same using Graph API. In the previous article, we have already seen how to get all organization users using Graph API.

I need to get the file counts from the site collection and the storage information used against the storage allocated for that particular site collection. So, I have used the Graph API to get those details.

Let's see this sample output from Graph API site usage in the beta version. 

Get All The SharePoint Site Collection Usage Details Using Graph API 

What is Microsoft Graph API?

  • It is Microsoft's developer platform used to connect multiple services.
  • It provides the Rest API and client library access to the data from Azure, SharePoint, OneDrive, Outlook/Exchange, Microsoft Teams, OneNote, Planner, and Excel.
  • Using oAuth 2.0 token, we can authenticate Microsoft Graph API.

From Microsoft documentation

“Microsoft Graph is the gateway to data and intelligence in Microsoft 365. Microsoft Graph provides a unified programmability model that you can use to take advantage of the tremendous amount of data in Office 365, Enterprise Mobility + Security, and Windows 10.

You can use the Microsoft Graph API to build apps for organizations and consumers that interact with the data of millions of users. With Microsoft Graph, you can connect to a wealth of resources, relationships, and intelligence, all through a single endpoint: https://graph.microsoft.com”

Reference URL - https://developer.microsoft.com/en-us/graph/docs/concepts/overview

Here is the Microsoft Documentation URL,

https://developer.microsoft.com/en-us/graph/docs/concepts/overview

Steps to retrieve the SharePoint site usage details using node.js

Follow the below-listed steps and code.

End Point URL -  https://graph.microsoft.com/v1.0/reports/getSharePointSiteUsageDetail(period='D30')

Graph Token URL - https://login.microsoftonline.com/{tenantID}/oauth2/v2.0/token

Graph Token body - client_id=" + configValues.clientId + "&scope=" + configValues.scope + "&client_secret=" + configValues.clientSecretId + "&grant_type=client_credentials

Step 1

Register the app in Azure AD using that client ID, Tenant ID, and secret key.

Go through the below URL to register the app in Azure.

Make sure to check that your registered Azure app has permission to read the directory data.

Step 2

In your node.js solution, just create the config file and provide the below values. We have created the config file to avoid the hard-coded things. Provide your tenantId, clientId, and secret key (don't use the below mentioned one, it is just a sample and won't work).
  1. {  
  2.     "scope""https%3A%2F%2Fgraph.microsoft.com%2F.default",  
  3.     "tenantId""7aa111ae-1ab6-4256-af4c-a0c1cdb4575d",  
  4.     "clientId""bff7fae8-c253-37e5-9b6a-e096bed54f11",  
  5.     "clientSecretId""XgfrmWfX0K/N7SRouCdAskTKrz0cnKN2rS12IkJ9SJk="  
  6. }  

Step 3

Refer to that config file in your JS file, as shown below.
  1. var request = require('sync-request');  
  2. var fs = require('fs');  
  3. var configValues = JSON.parse(fs.readFileSync('sharepointusage.json'));   

Step 4

Then, frame the Graph Token URL and Graph Token body to get the auth token.
  1. var graphAccessUrl = "https://login.microsoftonline.com/" + configValues.tenantId + "/oauth2/v2.0/token";  
  2. var graphTokenBody = "client_id=" + configValues.clientId + "&scope=" + configValues.scope + "&client_secret=" + configValues.clientSecretId + "&grant_type=client_credentials"   

Step 5

Get the Authorized token using the below method.
  1. var contentType = "application/x-www-form-urlencoded; charset=utf-8";  
  2. var graphTokenError = "Failed to get graph token";  
  3. var graphToken = "";  
  4. //Call the get token method  
  5. getToken(graphAccessUrl, contentType, graphTokenBody, graphTokenError);  
  6. //This method is using to get the token from the graph token url and body  
  7. functiongetToken(url, type, content, errorMessage, callback) {  
  8.     var options = {  
  9.         'headers': {  
  10.             'Content-Type': type  
  11.         },  
  12.         'body': content  
  13.     };  
  14.     //Posting access parameters to the server  
  15.     var tokenResponse = httpPost(url, options);  
  16.     if (tokenResponse.statusCode === 200) {  
  17.         error = errorMessage;  
  18.         if (errorMessage === graphTokenError) {  
  19.             var token = JSON.parse(tokenResponse.body.toString('utf-8'));  
  20.             graphToken = token.access_token;  
  21.         }  
  22.         if (callback) {  
  23.             returncallback();  
  24.         }  
  25.     } else {  
  26.         log(errorMessage);  
  27.     }  
  28. }  

Step 6

Once you receive the token, make an HTTP call using the Endpoint and get the results.

Step 7 :

 SharePoint Usage Report Graph API v1.0 provides the results in CSV format. We can get all the results in a single API call.
 
You have to process the csv data to format the results. 
  1. var reqUrl = "https://graph.microsoft.com/v1.0/reports/getSharePointSiteUsageDetail(period='D30')";  
  2.   
  3. function getsharePointUsageReportData(reqUrl) {  
  4.     try {  
  5.         console.log("Inside get user last logon data method!!!");  
  6.         var sharePointUsageRes = httpGet(encodeURI(reqUrl), GRAPH_TOKEN);  
  7.         if (sharePointUsageRes.statusCode == 200) {  
  8.             failIndex = 0;  
  9.             var parsedJson = convertCSVToJSON(sharePointUsageRes.body.toString('utf-8'));  
  10.             //add use case value to json valued array  
  11.             var parsJson = JSON.parse(parsedJson);  
  12.             if (parsJson) {  
  13.                 siteCollectionCount = siteCollectionCount + parsJson.length;  
  14.                 for (var i = 0; i < parsJson.length; i++) {  
  15.                     var currItem = parsJson[i];  
  16.                     if (currItem) {  
  17.                         //process your data here  
  18.                     }  
  19.                 }  
  20.             }  
  21.             console.log("Site Collection count : " + siteCollectionCount);  
  22.         } else {  
  23.          console.log("API received the failed response, Please check again");
  24.             }  
  25.         }  
  26.     } catch (ex) {  
  27.         console.log(ex);  
  28.     }  
  29. }  
  30. //The below method is using to convert the csv values to json values  
  31. function convertCSVToJSON(csv) {  
  32.     /// <summary>This function is used to convert CSV to JSON</summary>   
  33.     /// <param name="csv" type="String">CSV string</param>  
  34.     /// <returns type="Array">Return as JSON Array</returns>  
  35.     try {  
  36.         var lines = csv.split("\n");  
  37.         var result = [];  
  38.         var headers = lines[0].split(",");  
  39.         for (var i = 1; i < lines.length; i++) {  
  40.             var obj = {};  
  41.             if (lines[i]) {  
  42.                 var currentline = lines[i].split(",");  
  43.                 for (var j = 0; j < headers.length; j++) {  
  44.                     obj[headers[j]] = currentline[j];  
  45.                 }  
  46.                 result.push(obj);  
  47.             }  
  48.         }  
  49.         return JSON.stringify(result);  
  50.     } catch (ex) {  
  51.         console.log(ex + " in csvToJSON method...");  
  52.     }  
  53. }  

Step 8

Then, bind the results based on your requirement. You will receive the below object when you call the SharePoint usage API.

Get All The SharePoint Site Collection Usage Details Using Graph API 

Steps to Check the SharePoint site collection usage from the admin portal

Once you get the results, you can verify the results from O365 and also, follow the below listed steps to verify the output.

Step 1

Log into Microsoft 365 Admin Center. Learn more here.

https://admin.microsoft.com/AdminPortal 

Step 2

Provide a valid username and password to log into your account.

Step 3

From the Microsoft 365 Admin Center main menu, click the Reports option and then click the Usage option.
 
Get All The SharePoint Site Collection Usage Details Using Graph API 

Step 4

On the Usage pane, click "Select a report drop-down list", expand the SharePoint option, and then click SiteUsage option.
 
Get All The SharePoint Site Collection Usage Details Using Graph API 

Step 5

Click on the Export option. You will get the last 30 days report for SharePoint site collection with relevant data.
Get All The SharePoint Site Collection Usage Details Using Graph API 

Using the same endpoint, you can get the reports for 7 days, 30 days, 90 days, and 180 days.

https://graph.microsoft.com/v1.0/reports/getSharePointSiteUsageDetail(period='D30')

Reference Link

https://docs.microsoft.com/en-us/graph/api/reportroot-getsharepointsiteusagedetail?view=graph-rest-1.0

Summary

In this article, we have explored how to get the SharePoint site collection details from office 365 Admin portal using Graph API. I hope this article is useful to you. Please share your feedback in the comments section.