SharePoint Framework - Consume Microsoft Graph API Using AadHttpClient

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

Overview

In the article Consume Microsoft Graph API Using MSGraphClient, we explored how to consume the Microsoft Graph using MSGraphClient.
 
In this article, we will explore to consume the Microsoft Graph in SharePoint Framework client-side web parts using AadHttpClient.

Brief information about Microsoft Graph

MS Graph is a rich and fast-growing set of REST APIs provided by Microsoft to access content and services provided by Office 365. For example, using Microsoft graph we can access mailbox, calendar, and one drive for business (OD4B). As well as we can access Site collection, sites, and lists in SharePoint Online. Also, we can access Office 365 Groups, Teams using MS Graph.
 
Microsoft Graph
Create SPFx Solution

Open the command prompt. Create a directory for SPFx solution.
  1. md spfx-msgraph-aadhttpclient  
Navigate to the above-created directory.
  1. cd spfx-msgraph-aadhttpclient  
Run Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint --plusbeta  
Since AadHttpClient is in beta, use --plus beta with Yeoman generator.
 
Yeoman generator will present you with the wizard by asking questions about the solution to be created.

Yeoman generator
Solution Name

Hit enter to have a default name (spfx-msgraph-aadhttpclient 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 web part; i.e. SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice - SharePoint Online only (latest).
 
Place of files

We can 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 a client-side web part or an extension. Choose web part option.
Selected choice - WebPart
 
Web part name

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

Hit enter to select the default description or type in any other value.
Selected choice - Consume MS Graph with SPFx using AADHttpClient
 
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 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 the code editor of your choice.
  1. code .  
Access MS Graph using AadHttpClient

Microsoft Graph can be accessed by low-level type used to access Azure AD secured REST API (AadHttpClient). AadHttpClient client object can be used to consume any REST API, whereas MSGraphClient client object can only consume Microsoft Graph.

In the MsGraphAadHttpClient.tsx file under “\src\webparts\msGraphAadHttpClient\components\” folder, add the below import statement
  1. import { AadHttpClient } from '@microsoft/sp-http';  
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 the 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-msgraph-aadhttpclient-client-side-solution",  
  5.     "id""f4213803-dc4b-42d9-b6c4-96e895ec02fe",  
  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-msgraph-aadhttpclient.sppkg"  
  17.   }  
  18. }  
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
Configure Props

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

We will define the state for our React component.

To define interface to represent user, add file IUserItem.ts under “\src\webparts\ msGraphAadHttpClient\components\”
  1. export interface IUserItem {  
  2.     displayName: string;  
  3.     mail: string;  
  4.     userPrincipalName: string;  
  5. }  
Add file IMsGraphAadHttpClientState.ts under “\src\webparts\msGraphAadHttpClient\components\”
  1. import { IUserItem } from './IUserItem';  
  2.   
  3. export interface IMsGraphAadHttpClientState {  
  4.     users: Array<IUserItem>;  
  5. }  
Get User Details

Implement below method to get the user details from your tenant.
  1. private getUserDetails(): void {  
  2.     const aadClient: AadHttpClient = new AadHttpClient(  
  3.       this.props.context.serviceScope,  
  4.       "https://graph.microsoft.com"  
  5.     );  
  6.   
  7.     // Get users with givenName, surname, or displayName  
  8.     aadClient  
  9.       .get(  
  10.         `https://graph.microsoft.com/v1.0/users?$select=displayName,mail,userPrincipalName`,  
  11.         AadHttpClient.configurations.v1  
  12.       )  
  13.       .then(response => {  
  14.         return response.json();  
  15.       })  
  16.       .then(json => {  
  17.         // Prepare the output array  
  18.         var users: Array<IUserItem> = new Array<IUserItem>();  
  19.   
  20.         // Log the result in the console for testing purposes  
  21.         console.log(json);  
  22.   
  23.         // Map the JSON response to the output array  
  24.         json.value.map((item: any) => {  
  25.           users.push( {   
  26.             displayName: item.displayName,  
  27.             mail: item.mail,  
  28.             userPrincipalName: item.userPrincipalName,  
  29.           });  
  30.         });  
  31.   
  32.         // Update the component state accordingly to the result  
  33.         this.setState(  
  34.           {  
  35.             users: users,  
  36.           }  
  37.         );  
  38.       })  
  39.       .catch(error => {  
  40.         console.error(error);  
  41.       });  
  42.   }  
Enable Targeted Release on your Tenant

The MS Graph operation is part of an experimental feature and is only available in 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

    Enable Targeted Release on your Tenant 
Please refer to the article here to set up your tenant for 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 web part to the page.

     Test the WebPart
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”

    API Management

  3. From left navigation, Click “API Management”
  4. Approve pending requests

    Approve pending requests
Summary

Microsoft Graph offers a wide range of REST APIs to access content and services provided by Office 365. The MS Graph operation is part of an experimental feature and is only available in Targeted release (first release) tenants only. AadHttpClient is in preview mode, avoid using it in production.