SPFx - Connect To MS Graph With MSGraphClient

During this article, we will explore the new MSGraphClient capabilities to connect to MS Graph. We will develop a practical scenario to connect to MS Graph from SPFx web part.

Overview

 
A while back, I wrote an article on the same topic to Consume Microsoft Graph API Using MSGraphClient. It was implemented with SPFx version 1.5.1 when MSGraphClient was in preview. However, it is a new HTTP client introduced with SPFx version 1.6.0.
 
During this article, we will explore the new MSGraphClient capabilities to connect to the MS Graph. We will develop a practical scenario to connect to MS Graph from SPFx web part.
 

Develop SharePoint Framework Web Part

 
Open a command prompt. Create a directory for SPFx solution.
  1. md ms-graph-client  
Navigate to the above-created directory.
  1. cd ms-graph-client  
Run the 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.
 
 
Solution Name - Hit Enter to have default name (ms-graph-client in this case) or type in any other name for your solution.
Selected choice - Hit Enter
 
Target for the component - Here, we can select the target environment where we are planning to deploy the client web part, i.e., SharePoint Online or SharePoint On-Premises (SharePoint 2016 onwards).
Selected choice - SharePoint Online only (latest)
 
Place of files - We may choose to use the same folder or create a sub-folder for our solution.
Selected choice - Same folder
 
Deployment option - Selecting Y will allow the app to deployed instantly to all sites and will be accessible everywhere.
Selected choice - N (install on each site explicitly)
 
Permissions to access web APIs - Choose if the components in the solution require permissions to access web APIs that are unique and not shared with other components in the tenant.
Selected choice - N (solution contains unique permissions)
 
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 - ConnectWithMSGraphClient
 
Web part description - Hit Enter to select the default description or type in any other value.
Selected choice - Connect to MS Graph with MSGraphClient
 
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 a code editor of your choice.
  1. code .  

NPM Packages Dependency

 
Microsoft Graph TypeScript types
 
The typings will help in providing IntelliSense while writing the code.
 
On the command prompt, run below command to include the npm package.
  1. npm install @microsoft/microsoft-graph-types --save-dev  

Set Permission Scopes

 
To consume MS Graph or any third-party REST APIs, the permissions need to be explicitly set in the solution manifest.
 
Open “config\package-solution.json” and add below permission scope to give read permission on MS Graph for all users.
  1. {  
  2.   "$schema""https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",  
  3.   "solution": {  
  4.     "name""ms-graph-client-client-side-solution",  
  5.     "id""3d05713c-be24-48a5-84c9-02390c5340aa",  
  6.     "version""1.0.0.0",  
  7.     "includeClientSideAssets"true,  
  8.     "isDomainIsolated"false,  
  9.     "webApiPermissionRequests": [  
  10.       {  
  11.         "resource""Microsoft Graph",  
  12.         "scope""User.ReadBasic.All"  
  13.       }  
  14.     ]  
  15.   },  
  16.   "paths": {  
  17.     "zippedPackage""solution/ms-graph-client.sppkg"  
  18.   }  
  19. }  

Pass the context from web part to React Component

 
We will have to pass the SharePoint context from our web part to the React component.
 
Open React component properties at “src\webparts\connectWithMsGraphClient\components\IConnectWithMsGraphClientProps.ts”.
 
Add below properties.
  1. import { WebPartContext } from '@microsoft/sp-webpart-base';  
  2.   
  3. export interface IConnectWithMsGraphClientProps {  
  4.   description: string;  
  5.   context: WebPartContext;  
  6. }  
From our web part (src\webparts\connectWithMsGraphClient\ConnectWithMsGraphClientWebPart.ts), pass the context to React component.
  1. export default class ConnectWithMsGraphClientWebPart extends BaseClientSideWebPart<IConnectWithMsGraphClientWebPartProps> {  
  2.   
  3.   public render(): void {  
  4.     const element: React.ReactElement<IConnectWithMsGraphClientProps> = React.createElement(  
  5.       ConnectWithMsGraphClient,  
  6.       {  
  7.         description: this.properties.description,  
  8.         context: this.context  
  9.       }  
  10.     );  
  11.   
  12.     ReactDom.render(element, this.domElement);  
  13.   }  
  14.      .  
  15.      .  
  16.      .  
  17. }  

Define State

 
Add a file “src\webparts\connectWithMsGraphClient\components\IUserInfo.ts” to represent the user information.
  1. export interface IUsernfo {  
  2.     displayName: string;  
  3.     mail: string;  
  4.     userPrincipalName: string;  
  5. }  
Add a file “src\webparts\connectWithMsGraphClient\components\IConnectWithMsGraphClientState.ts “ to represent a state with array of IUsernfo.
  1. import { IUserInfo } from './IUserInfo';  
  2.   
  3. export interface IConnectWithMsGraphClientState {  
  4.     users: Array<IUserInfo>;  
  5. }  

Use MSGraphClient in the SPFx Web Part

 
We will use the MSGraphClient to connect to MS Graph.
 
Open the React component file at “src\webparts\connectWithMsGraphClient\components\ConnectWithMsGraphClient.tsx”
 
Add below imports.
  1. import { MSGraphClient } from '@microsoft/sp-http';  
  2. import * as MicrosoftGraph from '@microsoft/microsoft-graph-types';  
  3. import { autobind, PrimaryButton, DetailsList, DetailsListLayoutMode, CheckboxVisibility, SelectionMode } from 'office-ui-fabric-react';  
Configure the columns for the DetailsList component to display user details. Add below lines after import statements.
  1. // Configure the columns for the DetailsList component  
  2. let _usersListColumns = [  
  3.   {  
  4.     key: 'displayName',  
  5.     name: 'Display name',  
  6.     fieldName: 'displayName',  
  7.     minWidth: 50,  
  8.     maxWidth: 100,  
  9.     isResizable: true  
  10.   },  
  11.   {  
  12.     key: 'mail',  
  13.     name: 'Mail',  
  14.     fieldName: 'mail',  
  15.     minWidth: 50,  
  16.     maxWidth: 100,  
  17.     isResizable: true  
  18.   },  
  19.   {  
  20.     key: 'userPrincipalName',  
  21.     name: 'User Principal Name',  
  22.     fieldName: 'userPrincipalName',  
  23.     minWidth: 100,  
  24.     maxWidth: 200,  
  25.     isResizable: true  
  26.   },  
  27. ];  
Initialize the state of component in constructor.
  1. export default class ConnectWithMsGraphClient extends React.Component<IConnectWithMsGraphClientProps, IConnectWithMsGraphClientState> {  
  2.   constructor(props: IConnectWithMsGraphClientProps, state: IConnectWithMsGraphClientState) {  
  3.     super(props);  
  4.   
  5.     // Initialize the state of the component  
  6.     this.state = {  
  7.       users: []  
  8.     };  
  9.   }  
  10.   .  
  11.   .  
  12.   .  
  13. }  
Implement a generic method to get the user details using MS Graph API. 
  1. @autobind  
  2. private getUserDetails(): void {  
  3.   this.props.context.msGraphClientFactory  
  4.     .getClient()  
  5.     .then((client: MSGraphClient): void => {  
  6.       // Get user information from the Microsoft Graph  
  7.       client  
  8.         .api('users')  
  9.         .version("v1.0")  
  10.         .select("displayName,mail,userPrincipalName")  
  11.         .get((error, result: any, rawResponse?: any) => {  
  12.           // handle the response  
  13.           if (error) {  
  14.             console.log(error);  
  15.             return;  
  16.           }  
  17.   
  18.           // Prepare the output array  
  19.           var users: Array<IUserInfo> = new Array<IUserInfo>();  
  20.   
  21.           // Map the JSON response to the output array  
  22.           result.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.     });  
  38. }  
Update the render() method to place the needed controls. 
  1. public render(): React.ReactElement<IConnectWithMsGraphClientProps> {  
  2.   return (  
  3.     <div className={styles.connectWithMsGraphClient}>  
  4.       <div className={styles.container}>  
  5.         <div className={styles.row}>  
  6.           <div className={styles.column}>  
  7.             <span className={styles.title}>Microsoft Graph</span>  
  8.             <p className={styles.subTitle}>Consume MS Graph with SPFx!</p>  
  9.             <p className={styles.description}>{escape(this.props.description)}</p>  
  10.   
  11.             <p className={styles.form}>  
  12.               <PrimaryButton  
  13.                 text='Search'  
  14.                 title='Search'  
  15.                 onClick={this.getUserDetails}  
  16.               />  
  17.             </p>  
  18.             {  
  19.               (this.state.users != null && this.state.users.length > 0) ?  
  20.                 <p className={styles.form}>  
  21.                   <DetailsList  
  22.                     items={this.state.users}  
  23.                     columns={_usersListColumns}  
  24.                     setKey='set'  
  25.                     checkboxVisibility={CheckboxVisibility.hidden}  
  26.                     selectionMode={SelectionMode.none}  
  27.                     layoutMode={DetailsListLayoutMode.fixedColumns}  
  28.                     compact={true}  
  29.                   />  
  30.                 </p>  
  31.                 : null  
  32.             }  
  33.   
  34.           </div>  
  35.         </div>  
  36.       </div>  
  37.     </div>  
  38.   );  
  39. }  

Deploy the SPFx Package to SharePoint App Catalog

 
Follow below steps to deploy the SPFx package (.sppkg) to SharePoint app catalog.
 
Build minified assets
 
On the command prompt, type the below command.
  1. gulp bundle --ship  
Prepare the package
 
On the command prompt, type the below command.
  1. gulp package-solution --ship  
The .sppkg package will be available inside the “sharepoint\solution” folder.
 

Upload package to the app catalog

 
Open the SharePoint app catalog site.
 
Upload the package to the app catalog.
 
 
Click Deploy.
 

API Management

 
After deploying the web part, follow the below steps to approve API requests.
  1. Open SharePoint Admin Center (https://[tenant]-admin.sharepoint.com).
  2. From left navigation, click “API Management”.
  3. Approve the pending requests.

Test the WebPart

  1. On the command prompt, type “gulp serve”.
  2. Open SharePoint site.
  3. Navigate to /_layouts/15/workbench.aspx
  4. Locate and add the webpart (named ConnectWithMSGraphClient) to page.
The page generates an alert “To view the information on this page, you need to verify your identity”. To resolve this add below URLs to the trusted site in the browser.
  • https://graph.microsoft.com
  • https://.office365.com
  • https://.microsoftonline.com
  • https://.sharepoint.com
  • https://.outlook.com
 

Summary

 
Microsoft Graph offers a wide range of APIs to access the content and services provided by Office 365. While building SPFx solutions, MS Graph can be easily consumed using MSGraphClient.