SharePoint Framework - Graph API - Get User Profile From Office 365

In this article, we will see how we can get user profile details of a logged-in user from Office 365 into SharePoint framework - SPFx web part using Graph API.

Step 1

Create a folder with the name GraphAPI-1 on your local drive.

C:\Users\ABC\Documents\SPFx\GraphAPI-1

Step 2

Open the location in the command prompt using cd command. Scaffold the SPFx solution using the Yeoman Generator.

yo @microsoft/sharepoint

Step 3

Give the webpart a name and other details as shown below:

Step 4

Install MS Graph types node package by using the command:

npm install @microsoft/microsoft-graph-types --save-dev

Step 5

Open the solution in VS Code. You can use the "Code" command in the command prompt directly to open the solution in VS Code. Go to the web part type script file UserProfileInfoWebPart.ts and import MSGraphClient and MicrosoftGraph, as below:

import { MSGraphClient } from'@microsoft/sp-http';
import*asMicrosoftGraphfrom'@microsoft/microsoft-graph-types';

Step 6

Update the render() method.

 this.context.msGraphClientFactory
.getClient()
.then((graphclient: MSGraphClient): void=> {
graphclient
.api('/me')
.get((error, user: MicrosoftGraph.User, rawResponse?: any) => {
this.domElement.innerHTML = `
<section class="${styles.userProfileInfo}${!!this.context.sdks.microsoftTeams ? styles.teams : ''}">
    <div class="${styles.welcome}">
         <p class="${styles.description}">Display Name: ${user.displayName}</p>
         <p class="${styles.description}">Given Name: ${user.givenName}</p>
         <p class="${styles.description}">Surname: ${user.surname}</p>
         <p class="${styles.description}">Email ID: ${user.mail}</p>
         <p class="${styles.description}">Mobile Phone: ${user.mobilePhone}</p> 
    </div>
</section>`;
 });
});

Step 7

Run gulp serve and check your web part in workbench. This will get your user profile details from M 365 using Graph API.