Consume Microsoft Graph API Using A PnP Graph From SPFx-Webpart

Introduction 

 
In this article, I explain how to consume Microsoft graph API using @pnp/graph from your SPFx-Webpart.
 
So now, am going to fetch all the users from an Office 365 directory using PNP Graph.
 
I have already created an SPFx project “with “No JavaScript Framework”.
 
Consume Microsoft Graph API Using PnP Graph From SPFx-Webpart
 
After successful project creation, let me install the required libraries via NPM.
  1. npm install @pnp/graph  
Once the NPM package has been installed, let me import the library into my “DisplayUsersWebpart.ts” file.
  1. import { graph } from '@pnp/graph'  
  2. import '@pnp/graph/Users'   
So, I have imported the Users module from the PNP Graph library. If you want to import Groups, as an example you can use “import @pnp/graph/Groups”
 
You are going to import the module based on your needs to reduce the size of the package when packaging.
 
Create an “OnInit” method to initialize the Graph Configuration for the current context to the SPFx library.
  1. public onInit(): Promise<void> {  
  2.     graph.setup({  
  3.       spfxContext: this.context  
  4.     })  
  5.     return Promise.resolve()  
  6.   }  
Let me create a method to fetch all the users and render them into the DOM.
  1. protected FetchUsers(): void {      
  2.     graph.users.get().then(users => {  
  3.       var getHTMLElement = document.getElementById("load")  
  4.       getHTMLElement.innerText = "Users From Office 365"  
  5.       users.map(value  =>{  
  6.         var html  = `<li>${escape(value.displayName)} </li>`  
  7.        getHTMLElement.innerHTML += html  
  8.       })  
  9.     }).catch(error => {  
  10.       console.log(JSON.stringify(error))  
  11.     })  
  12.   }  
The render() method looks like below:
  1. public render(): void {  
  2.     this.domElement.innerHTML = `  
  3.       <p id="load">Loading Users</p>`;         
  4.       this.FetchUsers();  
  5.   }  
Once done, under the config folder, open the “package-solution.json”, then add the “webApiPermissionRequests” permission scope to read all the users using Microsoft graph. 
  1. "webApiPermissionRequests": [{  
  2.       "resource""Microsoft Graph",  
  3.       "scope""User.Read.All"  
  4.     }]  
Full Code
  1. import { Version } from '@microsoft/sp-core-library';  
  2. import {  
  3.   BaseClientSideWebPart,  
  4.   IPropertyPaneConfiguration,  
  5.   PropertyPaneTextField  
  6. } from '@microsoft/sp-webpart-base';  
  7. import { escape } from '@microsoft/sp-lodash-subset';  
  8.   
  9. import { graph } from '@pnp/graph';  
  10. import "@pnp/graph/users";  
  11.   
  12.   
  13. import * as strings from 'DisplayUsersWebPartStrings';  
  14.   
  15. export interface IDisplayUsersWebPartProps {  
  16.   description: string;  
  17. }  
  18.   
  19. export default class DisplayUsersWebPart extends BaseClientSideWebPart<IDisplayUsersWebPartProps> {  
  20.   
  21.   public onInit(): Promise<void> {  
  22.     graph.setup({  
  23.       spfxContext: this.context  
  24.     })  
  25.     return Promise.resolve()  
  26.   }  
  27.   
  28.     
  29.   public render(): void {  
  30.     this.domElement.innerHTML = `  
  31.       <p id="load">Loading Users</p>`;         
  32.       this.FetchUsers();  
  33.   }  
  34.   
  35.   protected FetchUsers(): void {      
  36.     graph.users.get().then(users => {  
  37.       var getHTMLElement = document.getElementById("load")  
  38.       getHTMLElement.innerText = "Users From Office 365"  
  39.       users.map(value  =>{  
  40.         var html  = `<li>${escape(value.displayName)} </li>`  
  41.        getHTMLElement.innerHTML += html  
  42.       })  
  43.     }).catch(error => {  
  44.       console.log(JSON.stringify(error))  
  45.     })  
  46.   }  
  47.   
  48.   protected get dataVersion(): Version {  
  49.     return Version.parse('1.0');  
  50.   }  
  51.   
  52.   protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {  
  53.     return {  
  54.       pages: [  
  55.         {  
  56.           header: {  
  57.             description: strings.PropertyPaneDescription  
  58.           },  
  59.           groups: [  
  60.             {  
  61.               groupName: strings.BasicGroupName,  
  62.               groupFields: [  
  63.                 PropertyPaneTextField('description', {  
  64.                   label: strings.DescriptionFieldLabel  
  65.                 })  
  66.               ]  
  67.             }  
  68.           ]  
  69.         }  
  70.       ]  
  71.     };  
  72.   }  
  73. }  
Package the solution, then prepare it for deployment.
 
Run the below command from your visual studio code terminal to get the SPFx package “gulp package-solution”
 
Open the App Catalog site to deploy the package available on the SharePoint site collection.
 
Consume Microsoft Graph API Using PnP Graph From SPFx-Webpart
 
Note
Deployment to app catalog requires Site collection administrator privileges for the user who deploy the package
 
Once you deployed the app, navigate to the SharePoint admin center to approve the API permission to access the Graph API
 
Consume Microsoft Graph API Using PnP Graph From SPFx-Webpart
 
Consume Microsoft Graph API Using PnP Graph From SPFx-Webpart
 
Note
For approving the API Permission, you need the global administrator role on your tenant.
 
Navigate to the site collection edit page and add a webpart. Finally, it looks like below:
 
Consume Microsoft Graph API Using PnP Graph From SPFx-Webpart
 
Happy Coding...!!