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”.
After successful project creation, let me install the required libraries via NPM.
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 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.
- public onInit(): Promise<void> {
- graph.setup({
- spfxContext: this.context
- })
- return Promise.resolve()
- }
Let me create a method to fetch all the users and render them 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))
- })
- }
The render() method looks like below:
- public render(): void {
- this.domElement.innerHTML = `
- <p id="load">Loading Users</p>`;
- this.FetchUsers();
- }
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.
- "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 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.
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
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:
Happy Coding...!!