logo
Published on

Consume the Microsoft Graph API using PnP in SPFx

This article provides steps to consume the Microsoft Graph API using the PnP JS library in the SharePoint Framework (SPFx).
PnP simplifies working with Microsoft Graph and SharePoint REST API by handling authentication and response parsing for you.


⚙️ Install Required Dependencies

npm install @pnp/sp @pnp/graph --save

🧩 Configure the Custom Properties

Create a new source code file in the src/webparts/<webpartname>/components folder named ISpfxPnPGraphProps.ts.

export interface ISpfxPnPGraphProps {
  description: string;
}

⚡ Client-Side Web Part Class

SpfxPnpGraphWebPart.ts

import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
  IPropertyPaneConfiguration,
  PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import * as strings from 'SpfxPnpGraphWebPartStrings';
import SpfxPnpGraph from './components/SpfxPnpGraph';
import { ISpfxPnPGraphProps } from './components/ISpfxPnPGraphProps';
 
export interface ISpfxPnPGraphWebPartProps {
  description: string;
}
 
export default class SpfxPnpGraphWebPart extends BaseClientSideWebPart<ISpfxPnPGraphWebPartProps> {
  public render(): void {
    const element: React.ReactElement<ISpfxPnPGraphProps> = React.createElement(
      SpfxPnpGraph,
      {
        description: this.properties.description,
        context: this.context
      }
    );
    ReactDom.render(element, this.domElement);
  }
 
  protected onDispose(): void {
    ReactDom.unmountComponentAtNode(this.domElement);
  }
 
  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
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

⚛️ React Component

SpfxPnpGraph.tsx

import * as React from 'react';
import styles from './SpfxPnpGraph.module.scss';
import { ISpfxPnPGraphProps } from './ISpfxPnPGraphProps';
import { graph } from "@pnp/graph/presets/all";
 
export default class SpfxPnpGraph extends React.Component<ISpfxPnPGraphProps, {}> {
  public async componentDidMount(): Promise<void> {
    await this.getUsers();
  }
 
  private async getUsers(): Promise<void> {
    try {
      const users: any[] = await graph.users.select("displayName", "mail", "userPrincipalName").get();
      console.log(users);
    } catch (error) {
      console.error("Error fetching users from Graph", error);
    }
  }
 
  public render(): React.ReactElement<ISpfxPnPGraphProps> {
    return (
      <div className={styles.spfxPnpGraph}>
        <h2>{this.props.description}</h2>
        <p>Check the browser console for Graph API user details.</p>
      </div>
    );
  }
}

🔐 Configuring API Permissions

In order to call the Microsoft Graph API, we must specify which permissions the web part requires.
Add the following block inside the config/package-solution.json:

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

Once you deploy the package to your tenant app catalog, go to API Access in the SharePoint Admin Center to approve these permissions.


🚀 Build and Deploy

gulp build
gulp bundle --ship
gulp package-solution --ship

Then upload the generated .sppkg file from the sharepoint/solution folder to your App Catalog and deploy the solution.

After deployment, open your site, add the web part, and check the browser console to see data fetched from Microsoft Graph.


📂 GitHub Source

View full SPFx project on GitHub:Consume the Microsoft Graph API using PnP in SPFx

GitHub

✅ Summary

Using PnP JS to access Microsoft Graph API makes SPFx development faster and cleaner. It handles token acquisition automatically and provides a fluent syntax for making requests.

With this setup, you can easily expand to other endpoints such as Teams, OneDrive, Planner, or Outlook APIs with minimal configuration.

Calendar IconBook a demo