C# How to Get SharePoint Online Documents Analytics Using Graph API


In this article we will see How to get SharePoint Online documents analytics using the Microsoft Graph API. To get, you will need to:
  1. Register an app in Azure AD to authenticate and authorize API requests.
  2. Grant the app the necessary permissions to read the documents and their analytics data.
  3. Use the API to get the analytics data for the documents.
Below is the example of how you can do this in C#:

using Microsoft.Identity.Client;
using Microsoft.Graph;
using System.Net.Http.Headers;

// Replace these with your own values.
const string clientId = "your-client-id";
const string clientSecret = "your-client-secret";
const string tenantId = "your-tenant-id";
const string resourceId = "https://graph.microsoft.com";
const string siteId = "your-site-id";

// Acquire an access token.
var authContext = new AuthenticationContext("https://login.microsoftonline.com/" + tenantId);
var clientCredential = new ClientCredential(clientId, clientSecret);
var result = await authContext.AcquireTokenAsync(resourceId, clientCredential);
var accessToken = result.AccessToken;

// Create a Graph client.
var graphClient = new GraphServiceClient(
    new DelegateAuthenticationProvider(
        (requestMessage) =>
        {
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
            return Task.CompletedTask;
        }));

// Get the documents in the site.
var documents = await graphClient.Sites[siteId].Drives.Root.Children.Request().GetAsync();

// Get the analytics data for each document.
foreach (var document in documents)
{
    var analytics = await graphClient.Sites[siteId].Drives[document.ParentReference.DriveId].Items[document.Id].Analytics.Request().GetAsync();
    Console.WriteLine("Reads: " + analytics.AllTime.Read.UniqueUsers);
}


This code acquires an access token using the client ID and client secret of the app, and then uses the token to authenticate requests to the Graph API. It then gets the documents in the site and prints the number of unique users who have read each document.

Happy PC (Programming / Configuring)

Comments

Popular posts from this blog

In C# CSOM How to Delete Folders Recursively, Sub-Folders, Files in SharePoint Online Document Library

How Get, Set, Delete Permission on SharePoint Online Site using Graph API

What is SharePoint online default authentication method? And which credential flow it is using to authenticate?