Get All SharePoint Site Collection Usage Details Using Graph API

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.

API site

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 the 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:”

Reference URL:

Here is the Microsoft Documentation URL,

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

Follow the below-listed steps and code.

  1. End Point URL:'D30')
  2. Graph Token URL:{tenantID}/oauth2/v2.0/token
  3. 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.

How to Register An App In Azure Active Directory

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).

    "scope": "",
    "tenantId": "7aa111ae-1ab6-4256-af4c-a0c1cdb4575d",
    "clientId": "bff7fae8-c253-37e5-9b6a-e096bed54f11",
    "clientSecretId": "XgfrmWfX0K/N7SRouCdAskTKrz0cnKN2rS12IkJ9SJk="

Step 3. Refer to that config file in your JS file, as shown below.

var request = require('sync-request');
var fs = require('fs');
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.

var graphAccessUrl = "" + configValues.tenantId + "/oauth2/v2.0/token";
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.

var contentType = "application/x-www-form-urlencoded; charset=utf-8";
var graphTokenError = "Failed to get graph token";
var graphToken = "";

// Call the get token method
getToken(graphAccessUrl, contentType, graphTokenBody, graphTokenError);

// This method is used to get the token from the graph token url and body
function getToken(url, type, content, errorMessage, callback) {
    var options = {
        'headers': {
            'Content-Type': type
        'body': content

    // Posting access parameters to the server
    var tokenResponse = httpPost(url, options);

    if (tokenResponse.statusCode === 200) {
        error = errorMessage;

        if (errorMessage === graphTokenError) {
            var token = JSON.parse(tokenResponse.body.toString('utf-8'));
            graphToken = token.access_token;

        if (callback) {
            return callback();
    } else {

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.

var reqUrl = "'D30')";

function getSharePointUsageReportData(reqUrl) {
    try {
        console.log("Inside get user last logon data method!!!");
        var sharePointUsageRes = httpGet(encodeURI(reqUrl), GRAPH_TOKEN);
        if (sharePointUsageRes.statusCode == 200) {
            failIndex = 0;
            var parsedJson = convertCSVToJSON(sharePointUsageRes.body.toString('utf-8'));
            // add use case value to json valued array
            var parsJson = JSON.parse(parsedJson);
            if (parsJson) {
                siteCollectionCount = siteCollectionCount + parsJson.length;
                for (var i = 0; i < parsJson.length; i++) {
                    var currItem = parsJson[i];
                    if (currItem) {
                        // process your data here
            console.log("Site Collection count: " + siteCollectionCount);
        } else {
            console.log("API received the failed response, Please check again");
    } catch (ex) {

// The below method is using to convert the csv values to json values
function convertCSVToJSON(csv) {
    /// <summary>This function is used to convert CSV to JSON</summary>   
    /// <param name="csv" type="String">CSV string</param>
    /// <returns type="Array">Return as JSON Array</returns>
    try {
        var lines = csv.split("\n");
        var result = [];
        var headers = lines[0].split(",");
        for (var i = 1; i < lines.length; i++) {
            var obj = {};
            if (lines[i]) {
                var currentline = lines[i].split(",");
                for (var j = 0; j < headers.length; j++) {
                    obj[headers[j]] = currentline[j];
        return JSON.stringify(result);
    } catch (ex) {
        console.log(ex + " in csvToJSON method...");

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

SharePoint usage 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.

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.

Microsoft 365 Admin Center

Step 4. On the Usage pane, click "Select a report drop-down list", expand the SharePoint option, and then click the SiteUsage option.

Select a report drop-down list

Step 5. Click on the Export option. You will get the last 30 days' report for SharePoint site collection with relevant data.

Export option

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

Reference Link:


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