Consume Microsoft Graph API Using PNP Graph From SPFx-Webpart

In this article i have explained how to consume Microsoft graph API using @pnp/graph from your SPFx-Webpart

So now am going to fetch all the users from office 365 directory using PNP Graph

I have already created a SPFx project “with “No JavaScript Framework”

After successful project creation let me install required libraries via NPM

npm install @pnp/graph

Once the NPM package has been installed. let me import the library into my “DisplayUsersWebpart.ts” file

import { graph } from '@pnp/graph'
import '@pnp/graph/Users' 

So i have imported the Users module from PNP Graph library. If you want to import Groups For example you can use “import @pnp/graph/Groups”

You are going to import the module based on your need to reduce the size of the package when packaging

Create “OnInit” method to initialize the Graph Configuration for current context to SPFx library

public onInit(): Promise<void> {
    graph.setup({
      spfxContext: this.context
    })
    return Promise.resolve()
  }

Let me create a method to fetch all the users and rendered into the DOM

protected FetchUsers(): void {    
    graph.users.get().then(users => {
      var getHTMLElement = document.getElementById("load")
      getHTMLElement.innerText = "Users From Office 365"
      users.map(value  =>{
        var html  = `<li>${escape(value.displayName)} </li>`
       getHTMLElement.innerHTML += html
      })
    }).catch(error => {
      console.log(JSON.stringify(error))
    })
  }

Render() method look like below

 public render(): void {
    this.domElement.innerHTML = `
      <p id="load">Loading Users</p>`;       
      this.FetchUsers();
  }

After all done. under config folder open “package-solution.json” then add “webApiPermissionRequests” permission scope to read all the users using microsoft graph

 "webApiPermissionRequests": [{
      "resource": "Microsoft Graph",
      "scope": "User.Read.All"
    }]

Full Code:

import { Version } from '@microsoft/sp-core-library';
import {
  BaseClientSideWebPart,
  IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';

import { graph } from '@pnp/graph';
import "@pnp/graph/users";


import * as strings from 'DisplayUsersWebPartStrings';

export interface IDisplayUsersWebPartProps {
  description: string;
}

export default class DisplayUsersWebPart extends BaseClientSideWebPart<IDisplayUsersWebPartProps> {

  public onInit(): Promise<void> {
    graph.setup({
      spfxContext: this.context
    })
    return Promise.resolve()
  }

  
  public render(): void {
    this.domElement.innerHTML = `
      <p id="load">Loading Users</p>`;       
      this.FetchUsers();
  }

  protected FetchUsers(): void {    
    graph.users.get().then(users => {
      var getHTMLElement = document.getElementById("load")
      getHTMLElement.innerText = "Users From Office 365"
      users.map(value  =>{
        var html  = `<li>${escape(value.displayName)} </li>`
       getHTMLElement.innerHTML += html
      })
    }).catch(error => {
      console.log(JSON.stringify(error))
    })
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

Package the solution then prepare for deployment.

Run the below command from your visual studio code terminal to get the SPFx package “gulp package-solution”

Open App Catalog site to deploy the package to available on SharePoint site collection

Note: Deployment to app catalog requires Site collection administrator privileges for the user who deploy the package

Once you deployed the app. navigate to SharePoint admin center to approve the API permission to access the graph API

Note: For approve the API Permission your need global administrator role on your tenant

Navigate to site collection edit page and add a webpart finally it look like below

Author Profile

Vinodh
Vinodh is a Microsoft MVP for SharePoint (Office Apps and Services) having 5+ years of experience in Microsoft Technologies.

His interest and expertise includes SharePoint Online Development, PowerApps Development, Flows for SharePoint and PowerApps. Single Page Apps/Add ins for SharePoint using React, Angular. SharePoint Farm Management, 2, 3 and upto 6 tier SharePoint Farm Installation and Configuration.

Awards :
Microsoft Most Valuable Professional for SharePoint and Office 365 awarded for the year 2016, 2017 and 2018.
C# Corner Most Valuable Professional for SharePoint and Office 365 awarded for the year 2016, 2017 and 2018.
Technology Expertise :
SharePoint Online, SharePoint 2013, SharePoint 2016 and SharePoint 2019 Preview.
Intranets both Modern and Classic, SharePoint Frameworks Customisation, SharePoint Add-ins, SharePoint single page apps.
Angular 5 with Bootstrap single page apps.
Typescript, JQuery and Javascript.
Micrsoft Flow and Powerapps.
Utilised :
Microsoft Graph API, SharePoint REST, SharePoint PnP JS.
Out of Box :
Consume Content search web parts for internet publishing sites using custom display templates.
Having knowledge on SharePoint workflows and SharePoint Designer workflows.
List customisation using JS Link, JSON Formatting.
Having knowledge in Active directory management services.
Create and configure service applications in SharePoint (MMS, UPSA, SSA).
Configure Outgoing email settings using SMTP Services.

Add a Comment

Your email address will not be published. Required fields are marked *