SharePoint Framework - Consume Microsoft Graph API Using MSGraphClient

Overview

In the article Develop First Client-Side Web Part, we developed a basic SharePoint client web part which can run independently without any interaction with SharePoint.

In this article, we will explore how to consume the Microsoft Graph in SharePoint Framework client-side web parts.

Brief information about Microsoft Graph

MS Graph is a rich and fast-growing set of REST APIs provided by Microsoft to access the content and services provided by Office 365. For example, using Microsoft Graph, we can access the mailbox, calendar, and One Drive for Business (OD4B) of a user. We can also access the Site Collection, sites, and lists in SharePoint Online. Also, we can access Office 365 Groups, Teams etc. using MS Graph.

SharePoint Framework - Consume Microsoft Graph API using MSGraphClient 

Read more about MS Graph here.

Create SPFx Solution

Open the command prompt. Create a directory for SPFx solution.
  1. md spfx-consume-msgraph  
Navigate to the above-created directory.
  1. cd spfx-consume-msgraph  
Run Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint  
Yeoman Generator will present you with the wizard by asking questions about the solution to be created.

SharePoint Framework - Consume Microsoft Graph API using MSGraphClient

Solution Name

Hit Enter to have the default name (spfx-consume-msgraph in this case) or type in any other name for your solution. 
Selected choice - Hit Enter
 
Target for component

Here, we can select the target environment where we are planning to deploy the client webpart, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice - SharePoint Online only (latest)
 
Place of files

We may choose to use the same folder or create a subfolder for our solution.
Selected choice - Same folder
 
Deployment option

Selecting Y will allow the app to be deployed instantly to all sites and will be accessible everywhere.
Selected choice - N (install on each site explicitly)
 
Type of client-side component to create

We can choose to create client side webpart or an extension. Choose the webpart option.
Selected choice - WebPart
 
Web part name

Hit Enter to select the default name or type in any other name.
Selected choice - ConsumeMSGraph
 
Web part description

Hit Enter to select the default description or type in any other value.
Selected choice - Consume MS Graph with SPFx
 
Framework to use

Select any JavaScript framework to develop the component. Available choices are (No JavaScript Framework, React, and Knockout)
Selected choice - React
 
Yeoman generator will perform the scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.

Once the scaffolding process is completed, lock down the version of project dependencies by running the below command.
  1. npm shrinkwrap  
In the command prompt, type the below command to open the solution in code editor of your choice.
  1. code .   
Access MS Graph

Microsoft Graph can be accessed by either native graph client (MSGraphClient) or low-level type used to access Azure AD secured REST API (AadHttpClient)

In the ConsumeMsGraph.tsx file, under “\src\webparts\consumeMsGraph\components\” folder, add the below import statement
  1. import { MSGraphClient } from '@microsoft/sp-client-preview';   
Typings for MS Graph

Microsoft Graph TypeScript Types enable IntelliSense on Microsoft Graph objects including users, messages, and groups.

On the command prompt, run the below command to include typings.
  1. npm install @microsoft/microsoft-graph-types --save-dev  
This command will install the types and save in package.json as a development dependency.
 
In the ConsumeMsGraph.tsx file, under “\src\webparts\consumeMsGraph\components\” folder, add the following import statement.
  1. import * as MicrosoftGraph from '@microsoft/microsoft-graph-types';   
Permissions

In order to consume MS Graph or any third party REST APIs, we need to explicitly specify the permissions in the manifest of the solution.

In the package-solution.json file, under “config” folder, configure webApiPermissionRequests property to specify User.ReadBasic.All permission.
  1. {  
  2.   "$schema""https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",  
  3.   "solution": {  
  4.     "name""spfx-consume-msgraph-client-side-solution",  
  5.     "id""f95e77e7-842b-4ac9-b3f7-f5c421efdb0d",  
  6.     "version""1.0.0.0",  
  7.     "includeClientSideAssets"true,  
  8.     "webApiPermissionRequests": [  
  9.       {  
  10.         "resource""Microsoft Graph",  
  11.         "scope""User.ReadBasic.All"  
  12.       }  
  13.     ]  
  14.   },  
  15.   "paths": {  
  16.     "zippedPackage""solution/spfx-consume-msgraph.sppkg"  
  17.   }  
  18. }  
The webApiPermissionRequests is an array of webApiPermissionRequest items where each item is defined as below.
  • resource - name or the ObjectId (in Azure AD). E.g. Microsoft Graph
  • scope - name or unique ID of the permission
Please refer to the permission API documentation at - https://developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference

Configure Props

Define the context property in IConsumeMsGraphProps.ts under “\src\webparts\consumeMsGraph\components\”.
  1. import { WebPartContext } from '@microsoft/sp-webpart-base';  
  2.   
  3. export interface IConsumeMsGraphProps {  
  4.   description: string;  
  5.   context: WebPartContext;  
  6. }  
Configure State

We will define the state for our React component. To define the interface to represent user, add file IUserItem.ts under “\src\webparts\consumeMsGraph\components\”.
  1. export interface IUserItem {  
  2.     displayName: string;  
  3.     mail: string;  
  4.     userPrincipalName: string;  
  5. }  
Add the file named IConsumeMsGraphState.ts under “\src\webparts\consumeMsGraph\components\”.
  1. import { IUserItem } from './IUserItem';  
  2.   
  3. export interface IConsumeMsGraphState {  
  4.     users: Array<IUserItem>;  
  5. }  
Get User Details

Implement the below method to get the user details from your tenant.
  1. private getUserDetails(): void {  
  2.   
  3.     const graphClient: MSGraphClient = this.props.context.serviceScope.consume(  
  4.       MSGraphClient.serviceKey  
  5.     );  
  6.   
  7.     graphClient  
  8.       .api("users")  
  9.       .version("v1.0")  
  10.       .select("displayName,mail,userPrincipalName")  
  11.       .get((err, res) => {    
  12.   
  13.         if (err) {  
  14.           console.error(err);  
  15.           return;  
  16.         }  
  17.   
  18.         // Prepare the output array  
  19.         var users: Array<IUserItem> = new Array<IUserItem>();  
  20.   
  21.         // Map the JSON response to the output array  
  22.         res.value.map((item: any) => {  
  23.           users.push( {   
  24.             displayName: item.displayName,  
  25.             mail: item.mail,  
  26.             userPrincipalName: item.userPrincipalName,  
  27.           });  
  28.         });  
  29.   
  30.         // Update the component state accordingly to the result  
  31.         this.setState(  
  32.           {  
  33.             users: users,  
  34.           }  
  35.         );  
  36.       });  
  37.   }  
Enable Targeted Release on your Tenant

The MS Graph operation is part of an experimental feature and is only available in the targeted release (first release) tenants,
  1. Open Office 365 Admin Center.
  2. Click Settings > Organization profile.
  3. Click Edit against “Release preferences”.
  4. Select the preference.
SharePoint Framework - Consume Microsoft Graph API using MSGraphClient
 
Please refer to the article here to setup your tenant for the targeted release.

Test the WebPart
  1. On the command prompt, type “gulp serve”.
  2. Open SharePoint site.
  3. Navigate to /_layouts/15/workbench.aspx.
  4. Add the webpart to the page.
SharePoint Framework - Consume Microsoft Graph API using MSGraphClient
 
API Management

In the Production environment, after deploying the web part, follow the below steps to approve API requests.
  1. Open SharePoint Admin Center (https://[tenant]-admin.sharepoint.com).

  2. Click “Try the preview”.

    SharePoint Framework - Consume Microsoft Graph API using MSGraphClient

  3. From left navigation, click “API Management”.

  4. Approve the pending requests.

    SharePoint Framework - Consume Microsoft Graph API using MSGraphClient 
Summary

Microsoft Graph offers a wide range of REST APIs to access the content and services provided by Office 365. The MS Graph operation is a part of an experimental feature and is only available in the targeted release (first release) tenants only.