How to Use Microsoft Graph API in SPFx Web Parts

When working with SharePoint Framework (SPFx) solutions, we may need to extend beyond the SharePoint REST APIs and access other Microsoft 365 services, such as OneDrive, Outlook, Teams, and Azure AD user data. In those cases, we can use the Microsoft Graph API.

In this article, I will explain how to use the Microsoft Graph API in SPFx web parts. Also, we will cover:

  • What is Microsoft Graph, and its importance
  • Microsoft Graph Permissions for SPFx
  • How to Use Microsoft Graph API in SPFx Web Parts
  • Microsoft Graph API Calls in SPFx
  • Deploy Solutions to the App catalog and Grant Admin Consent

By the end of this post, you’ll have an idea of what the Microsoft Graph API is and how to use it in an SPFx web part.

What is Microsoft Graph?

Microsoft Graph is the central gateway to Microsoft 365. With just one endpoint (https://graph.microsoft.com), we can connect to emails, files, users, groups, Teams messages, calendars, and much more. If you’ve ever used Microsoft 365 apps like Outlook, Teams, OneDrive, or SharePoint, you know that each of these apps holds its own data, like emails, files, chats, sites, and so on.

Now, if our SPFx webpart needs to bring data together from more than one of these services, for example:

  • Get the user’s profile from Azure Active Directory.
  • Fetch files from OneDrive.
  • Display Upcoming events from Outlook Calendar.
  • Get and update the SharePoint site, list, etc.

For doing all these things, we must utilize a separate API for each product, which can be confusing and time-consuming. In this case, we can utilize Microsoft Graph, which provides a single API to access all of this data across Microsoft 365.

Before we learn how to use Microsoft Graph in SPFx solutions, let’s first look at the permissions Microsoft Graph provides.

Microsoft Graph Permissions for SPFx

In our SPFx solution, whenever we fetch or update data from Microsoft 365 applications using Microsoft Graph APIs, we first need to declare the appropriate permissions, such as User.Read, Mail.Read, Sites.Read.All, etc, in the app’s configuration.

This is important because SPFx does not automatically get access to Microsoft Graph; we must explicitly request the permissions our solution needs. Take Reference from the Official Website.

Below are the common graph api permissions:

PermissionUsage
User.ReadRead user profile
Sites.Read.AllRead data from all SharePoint sites
Sites.ReadWrite.AllRead and write data in all SharePoint sites
Files.Read.AllRead files in all site collections
Files.ReadWrite.AllRead and write files in all site collections
Group.Read.AllRead all groups in the directory (basic group properties and membership)
Group.ReadWrite.AllRead and write all groups (create, update, delete groups)
Team.ReadBasic.AllRead basic information about all Microsoft Teams, including their names, descriptions, and channels.
TeamsActivity.ReadRead the signed-in user’s teamwork activity feed.
Team.CreateAllows the app to create teams on behalf of the signed-in user.

How to Use Microsoft Graph API in SPFx Solutions

To use the Microsoft Graph in an SPFx solution, we first need to decide on the required graph scopes and then configure the API permission requests. In this section, we’ll see how to retrieve the current user’s information using the Microsoft Graph API in an SPFx web part. To do this, follow the steps below:

  1. The following is the permission required to read the current user information in the SPFx solution.
User.Read
  1. To configure this permission in the solution, open the package-solution.json file located in the config folder of the SPFx web part solution. Then, add the webApiPermissionRequests property as shown below.
how to use microsoft graph api in spfx web parts
{
  "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
  "solution": {
    "name": "ms-graph-get-user-info-client-side-solution",
    "id": "38576b68-2952-430e-a77e-e5ee27f9cafa",
    "version": "1.0.0.0",
    "includeClientSideAssets": true,
    "skipFeatureDeployment": true,
    "isDomainIsolated": false,
    "developer": {
      "name": "",
      "websiteUrl": "",
      "privacyUrl": "",
      "termsOfUseUrl": "",
      "mpnId": "Undefined-1.21.1"
    },
    "metadata": {
      "shortDescription": {
        "default": "MSGraph_GetUserInfo description"
      },
      "longDescription": {
        "default": "MSGraph_GetUserInfo description"
      },
      "screenshotPaths": [],
      "videoUrl": "",
      "categories": []
    },
    "features": [
      {
        "title": "ms-graph-get-user-info Feature",
        "description": "The feature that activates elements of the ms-graph-get-user-info solution.",
        "id": "9f9c3725-e52b-4be6-b452-0c2f9901a3cc",
        "version": "1.0.0.0"
      }
    ],
     "webApiPermissionRequests": [
          {
            "resource": "Microsoft Graph",
            "scope": "User.Read"
          }]
          },
  "paths": {
    "zippedPackage": "solution/ms-graph-get-user-info.sppkg"
  }
}

Here:

  • webApiPermissionRequests is an array of items where we can add the permissions required for this solution.
  • Each item has two properties: resource and scope.
    • resource = Indicates the name or Objectid of the resource. For Microsoft Graph, the name is Microsoft Graph.
    • scope = Name of the permission or unique ID of the permission.

How to Use MSGraphClientV3 to make API calls

MSGraphClientV3 is a special class in SPFx that allows calling Microsoft Graph APIs, which are derived from the @microsoft/sp-http library. This is an SPFx package that contains HTTP clients such as Graph. SharePoint REST, Azure AD.

Note: I created the SPFx webpart solution using the React framework. Continue with the steps below to view the usage of the MSGraphClientV3 in our SPFx web part.

  1. Now, we need to import Microsoft Graph and get a client in our SPFx solution. Open the .ts file, add the import statement, and update the render() method as shown below.
import { MSGraphClientV3 } from '@microsoft/sp-http';

  public render(): void {
    this.context.msGraphClientFactory.getClient('3').then((client:MSGraphClientV3)=>{
    const element: React.ReactElement<IGetUserInfoProps> = React.createElement(
      GetUserInfo,
      {
        description: this.properties.description,
        isDarkTheme: this._isDarkTheme,
        environmentMessage: this._environmentMessage,
        hasTeamsContext: !!this.context.sdks.microsoftTeams,
        userDisplayName: this.context.pageContext.user.displayName,
       graphClient: client
      }
    );

    ReactDom.render(element, this.domElement);
  })}

Here:

  • @microsoft/sp-http = The SPFx package that contains HTTP clients such as Graph. SharePoint REST, Azure AD.
  • this.context.msGraphClientFactory.getClient(‘3’).then((client:MSGraphClientV3)=>{..}
    • this.context = Provides access to the SPFx web parts environment.
    • msGraphClientFactory = This creates the Microsoft Graph clients for us.
    • getClient(‘3’)= It requests the graph client for version 3 (MSGraphClientV3).
    • client: MSGraphClientV3 = Here, the Graph client is returned as client, which we can use to make API calls.
    • .then() = It will handle the client after it is created.
  • graphClient: client =We assigned the newly created client to the graphClient property.
  1. Update the Props.ts file as below:
import { MSGraphClientV3 } from '@microsoft/sp-http';
export interface IGetUserInfoProps {
  description: string;
  isDarkTheme: boolean;
  environmentMessage: string;
  hasTeamsContext: boolean;
  userDisplayName: string;
  graphClient: MSGraphClientV3;
}
  • Here, we imported the MSGraphClientV3 and assigned that to the prop graphClient.

We can then use the graphClient prop in the .tsx file instead of creating it multiple times.

  1. Now, open the .tsx file and update it with the code below:
import * as React from 'react';
import styles from './GetUserInfo.module.scss';
import type { IGetUserInfoProps } from './IGetUserInfoProps';

interface IGetUserInfoState {
  userName: string;
  userEmail: string;
  photoUrl: string;
}
export default class GetUserInfo extends React.Component<IGetUserInfoProps, IGetUserInfoState> {
  constructor(props: IGetUserInfoProps) {
    super(props);
    this.state ={
      userName: "",
      userEmail: "",
      photoUrl: ""
    }
  }
  public componentDidMount(): void {
      this.getCurrentUserInfo();
      this.getUserPhoto();
    }
  private getCurrentUserInfo(): void {
  this.props.graphClient.api('/me').get().then(user => {
      this.setState({
        userName: user.displayName,
        userEmail: user.mail
      });
    })
    .catch(err => {
      console.error("Error fetching user info", err);
    });
}
private getUserPhoto(): void {
  this.props.graphClient.api('/me/photo/$value').get().then((response: any) => {
      // Convert response to blob
      const blob = new Blob([response], { type: "image/jpeg" });
      const url = URL.createObjectURL(blob);
      this.setState({ photoUrl: url });
    })
    .catch(err => {
      console.warn("No profile photo found", err);
    });
}
  public render(): React.ReactElement<IGetUserInfoProps> {
    return (
      <section className={`${styles.getUserInfo} `}>
         <h2>User Info</h2>
          {this.state.photoUrl && (
            <img src={this.state.photoUrl} alt="User Photo" width="80" style={{ borderRadius: '50%' }} />
          )}
          <p>Name: {this.state.userName}</p>
          <p>Email: {this.state.userEmail}</p>        
      </section>
    );
  }
}

Here:

  • IGetUserInfoState = An interface that creates the below states, all of which are string data types:
    • userName
    • userEmail
    • photoUrl
  • Within the constructor, we initialized those states with empty values.
  • getCurrentUserInfo() = This function returns the current user’s display name and mail address using the api “this.props.graphClient.api(‘/me’).get().”
    • this.props.graphClient = The MS Graph client, which we created in the .ts file.
    • .api(‘/me’) = It informs the client which Graph API endpoint to call.[/me means the signed-in user].
    • .get() = Makes a get request to the endpoint
  • getUserPhoto() = this function returns the current user image using the below api “this.props.graphClient.api(‘/me/photo/$value’).” Then updating the photo url state.
  • componentDidMount() = This is a lifecycle method that will be called when the web part is loaded. In this method, we call the two methods that retrieve the current user’s name, email, and photo.
  • In the render method, we are calling the updated states, which will display the current user info:
    • this.state.photoUrl
    • this.state.userName
    • this.state.userEmail
  1. Save the changes and then run the command below in the terminal pane or command prompt where you opened the solution to test this webpart locally.
gulp serve

After running this command, you will see the web part, which displays the current logged-in user’s image and name, as shown below.

ms graph api to fetch current user info in spfx webpart

This way, we can use the Microsoft Graph in our SPFx solution. In the section below, I have explained some of the common MS Graph API calls in SPFx.

Microsoft Graph API Calls in SPFx

The Microsoft Graph API endpoint or URL is the address in our SPFx code that calls to retrieve data from Microsoft 365 apps, such as SharePoint, OneDrive, Outlook, etc. The url always starts as below:

https://graph.microsoft.com/{version}/{resource}

Here:

  • https://graph.microsoft.com = Base url always the same. We only need to write the URL part after the base URL, because MSGraphClientV3 knows the base URL.
  • {version}= v1.0 or beta, which is a preview API.
  • {resource}= Which we are asking for, such as /me, /sites, /users.

In the table below, I have listed some commonly used APIs, along with their complete API URLs, functionality in the backend, and descriptions. You can take reference from this official website

SPFx Graph CallFull API URLDescription
client.api(‘/me’).get()https://graph.microsoft.com/v1.0/meGets the signed-in user’s profile information
client.api(‘/me/drive/root/children’).get()https://graph.microsoft.com/v1.0/me/drive/root/childrenLists files and folders in the signed-in user’s OneDrive root
client.api(‘/me/messages’).get()https://graph.microsoft.com/v1.0/me/messagesRetrieves the user’s Outlook emails
client.api(‘/sites/{site-id}/lists’).get()https://graph.microsoft.com/v1.0/sites/{site-id}/listsGets all lists in a SharePoint site
client.api(‘/sites/{site-id}/lists/{list-id}/items?expand=fields’).get()https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items?expand=fieldsRetrieves list items from a SharePoint list with field values
client.api(‘/users’).get()https://graph.microsoft.com/v1.0/usersRetrieves all users in the tenant
client.api(‘/groups’).get()https://graph.microsoft.com/v1.0/groupsRetrieves all Microsoft 365 groups
client.api(‘/teams’).get()https://graph.microsoft.com/v1.0/teamsRetrieves all Teams in the tenant

Deploy Solution to App Catalog & Grant Admin Consent

When we add Microsoft Graph permissions in an SPFx solution to retrieve Microsoft 365 data, those permissions must first be approved by an administrator. Without this approval, the web part will not be able to access the requested data.

Once the solution is deployed to the tenant App Catalog, SharePoint automatically detects the Microsoft Graph permissions requested in the package.

Follow the steps below to achieve this:

  1. Run the commands below to make a package for the SPFx solution. After running these commands, the .sppkg file will be created. Upload that file into the tenant app catalog.
gulp clean 
gulp build 
gulp bundle --ship 
gulp package-solution --ship
  1. In the tenant app catalog, you can see the API access in the left nav, and click on it.
grant microsoft graph api permissions
  1. This will open the SharePoint Admin Center, where the permission requests appear in the API access section. The tenant admin can review and grant permission over here.
  2. Under the Pending requests -> Select the permission request -> Top Approve and Reject buttons will appear -> Click on Approve -> On the Right side, a pane will open, read the info, and click on Approve.
spfx requested ms graph api permissions list

Only after the admin approval, the SPFx web part will be able to access and display Microsoft Graph data. That’s it; as a tenant admin, we can now grant the requested Microsoft Graph permissions this way.

I hope you found this article helpful! In this article, I explained what Microsoft Graph is, why it is important, and how to use it in SPFx solutions, including configuring permissions, making API calls, and granting admin consent. Follow this article if you are new to using the Microsoft Graph API in the SPFx solutions.

Also, you may like:

>

Build a High-Performance Project Management Site in SharePoint Online

User registration Power Apps canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App

Power Platform Tutorial FREE PDF Download

FREE Power Platform Tutorial PDF

Download 135 Pages FREE PDF on Microsoft Power Platform Tutorial. Learn Now…