SharePoint Framework (SPFX) connecting Microsoft Graph Client

Why do I need to connect to Microsoft Graph?

Microsoft Graph is a set of REST API and client libraries used to connect to all Microsoft 365 services like SharePoint, Teams, Outlook, Calendar, OneDrive, Azure active directory, Dynamics etc.,

In this article we can see how to get user details from Azure active directory using Graph client.

You can find the available list of Microsoft Graph APIs here.

Step 1: Create SPFX webpart

Step 2: Add Graph API code

Open the created SPFX webpart in Visual studio Code “code .”

Open the webpart ts file mine is “SpfxgraphclientWebPart.ts”.

Import the Graph library just above the interface

Add this piece of code into the render method, which is nothing but the code connecting the “MSGraphClient” “/me” api. As the name “/me” stands it will get my details. The result will be in JSON format.

To display the received JSON result in our webpart, add the below code inside the “this.domElement.innerHTML”

After adding the required code the ts file render method will look like this.

Step 3: Set Graph API permissions

For our webpart to connect with Graph API’s it needs permissions as per the action they do. For now, we need just read access. So, open the “yourwebpartprojectfolder/config/package-solution.json” file and add the below code in it.

After adding our “package-solution.json” file will look like this.

Step 4: Deploy webpart to SharePoint

As we cannot test our webpart in local workbench we need to deploy it to our SharePoint online site. So, package the webpart and deploy it to SharePoint Catalog site using below commands.

Get the webpart solution package file “spfxgraphclient.sppkg” from “yourwebpartfolder\sharepoint\solution”

Go to your SharePoint Catalog site “https://cogsharepoint.sharepoint.com/sites/appcatalog/AppCatalog/Forms/AllItems.aspx” and upload in “Apps for SharePoint”. Then click deploy.

Step 5: Approve Graph permissions

As we have set the webapi permissions in “package-solution.json” when our webpart is deployed it goes for a Tenant administrator approval.

Note: You should be the Tenant administrator

As a Tenant administrator:

Step 6: Test the webpart

Now we are ready to test our webpart. Run gulp serve. Go to your SharePoint online site workbench. Mine is https://cogsharepoint.sharepoint.com/_layouts/15/workbench.aspx

Amazing to see our webpart shows my “DisplayName”, “Email” and “Phone Number”.

F12 in chrome to see console log.

We could see the user details like ‘Display Name’, ‘Surname’,’BusinessPhones’ etc., from Azure Active directory through graph client.

Excited to build more webparts using Graph client 😊

Thanks for reading this blog.