How To Use MS Graph In SharePoint Framework (SPFx) App

MSGraphClient, is a new HTTP client specifically designed in SPFx to access Graph.

Microsoft Graph is a developer platform. It connects multiple services and allows developers to integrate their services with Microsoft products.

Microsoft Graph has many granular permissions to control the access of the apps to make use of the resources. While installing the app, a request will be sent to the administrator to grant permissions. Once the permission is granted by the administrator, access for the user to use resources is permitted.

Let’s directly jump into the implementation section. Please follow the below steps to get it done.

Step 1

Build your SharePoint Framework client-side web part and integrate it with Angular 4.

Step 2

MSGraphClient, is a new HTTP client specifically designed in SPFx to access Graph API. It was introduced in SharePoint Framework v1.4.1 that simplifies connecting to the Microsoft Graph inside SharePoint Framework. It is available only in projects built using SharePoint Framework v1.4.1 and later.

Note
MSGraphClient is in preview mode only.

import {MSGraphClient} from '@microsoft/sp-client-preview';

Use the above code snippet in your main Webpart.ts file to use MSGraphClient in your SharePoint solution.

Step 3

Microsoft TypeScript definitions need to be added, which enables the developers to make decisions automatically on Microsoft objects including users, groups and messages.

Install the Microsoft Graph TypeScript types in your SharePoint solution by using the below package.

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

Step 4

Once the package is downloaded, load it in the main Webpart.ts file like below.

import * as MicrosoftGraph from '@microsoft/microsoft-graph-types';

Step 5

The next step is to mention the required permissions in package-solution.json file

webApiPermissionRequests is an array of web API’s permission request items. Every item in webApiPermissionRequests defines the resource and the scope of the permission request.

Resource
It defines the resource for which the user wants to configure the permission request. The resource value to access Microsoft Graph is Microsoft Graph.

Scope
It defines the name of the permission that a user wants to access in the resource. The permission name and ID were briefly explained in official Graph API documentation.

Please find the sample code snippet below.

  1. {  
  2.     "$schema""https://dev.office.com/json-schemas/spfx-build/package-solution.schema.json",  
  3.     "solution": {  
  4.         "name""graph-messages-demo-client-side-solution",  
  5.         "id""821d32c8-3b5e-475c-aa1f-2030532c6226",  
  6.         "version""0.0.0.5",  
  7.         "includeClientSideAssets"true,  
  8.         "skipFeatureDeployment"true,  
  9.         "webApiPermissionRequests": [{  
  10.             "resource""Microsoft Graph",  
  11.             "scope""User.ReadBasic.All"  
  12.         }, {  
  13.             "resource""Microsoft Graph",  
  14.             "scope""Contacts.Read"  
  15.         }, {  
  16.             "resource""Microsoft Graph",  
  17.             "scope""Mail.Read"  
  18.         }, {  
  19.             "resource""Microsoft Graph",  
  20.             "scope""Contacts.Read"  
  21.         }]  
  22.     },  
  23.     "paths": {  
  24.         "zippedPackage""solution/graph-messages-demo.sppkg"  
  25.     }  
  26. }  
Step 6

Go to the Node.js command prompt and make sure you are pointing the Project directory and run the below command to verify that the solution builds correctly.

gulp build

Step 7

Run the below command to bundle the solution, we are using –ship to make sure that all our node_modules dependencies were included in bundle file.

gulp bundle --ship

While building solutions on the SharePoint Framework, we are working with a large number of source files that may have references to other classes, libraries, and resources. Bundling helps the developers to generate a single file as a bundle for the entire Web Part. It automatically excludes referenced resources that aren’t used.

Step 8

Use the following command to package the solution.

gulp package-solution --ship

This task will create the solution package under the project directory in a folder called sharepoint/solution for deploying the webpart to the site. The package-solution.json that presents in the config folder has the basic information about the webpart.

We are using the –ship command to get the package in release mode.

Step 9

Go to your App Catalog in your SharePoint and push the .sspkg file generated from Step 8.

Once you upload the file in appcatalog, you will be prompted with a popup like below.

appcatalog

 

During the installation of your app, you can find the highlighted content in the Deploy window, which alerts you to approve the pending permissions for Microsoft Graph.

Step 10

After the installation process, go to the SharePoint Admin Center and select the “Try the preview” option in your SharePoint admin center.

Try Preview

 

Step 11

In new modern SharePoint Admin preview page, we do a new menu called API Management to manage app permissions in your tenant.

In the step-3, we requested 4 permissions in package-solution.json, you can find those permissions requests appear in the API management screen below. An administrator should approve requested permission scopes in the resource to grant access to the apps using those resources.

API Management

 

Now, we are all set to use the Microsoft Graph in SPFx webparts. Below, I have mentioned some of the code samples for real-time scenarios which will help you to start with MS graph in SPFx.

Import the desired component code and HTML code in your webpart which given in the following examples.

Get user details in your organization:

The below component and Html code is used to get all the users' basic information from your organization. The response is also attached for the process.

Component code

  1. public users() {  
  2.     Const users: MSGraphClient = this.context.serviceScope.consume(MSGraphClient.serviceKey);  
  3.     users.api("/users").select("displayName,mail,userPrincipalName,mobilePhone,givenName,surname").get((error, response: any, rawResponse ? : any) => {  
  4.         console.log("Response :", response);  
  5.         this.user = response.value;  
  6.     });  
  7. }  

HTML code

  1. <div class="container">  
  2. <div class="row">  
  3. <div class="col-sm-6" *ngFor="let items of user">  
  4. <b> <br>displayName: {{items.displayName}}  
  5. <br>mail: {{items.mail}}  
  6. <br>givenName: {{items.givenName}}  
  7. <br>surname: {{items.surname}}  
  8. <br>userPrincipalName: {{items.userPrincipalName}}</b>  
  9. </div>  
  10. </div>  
  11. </div>  
 
Response: 

Response

 

Get all messages from your outlook mail

The below component and HTML code are used to get all the messages from your Outlook mail. The response is also attached for the process.

Component code

  1. public messages() {  
  2.     const messages: MSGraphClient = this.context.serviceScope.consume(MSGraphClient.serviceKey);  
  3.     messages.api("/me/messages").get((error, response: any, rawResponse ? : any) => {  
  4.         console.log("Response :", response);  
  5.         this.message = response.value;  
  6.         console.log("messages :"this.message);  
  7.     });  
  8. }  

HTML code

  1. <div class="container">  
  2. <div class="row">  
  3. <div class="col-sm-12" *ngFor="let items of message">  
  4. <b>  
  5. <br>subject: {{items.subject}}  
  6. <br>bodyPreview: {{items.bodyPreview}}  
  7. <br>importance: {{items.importance}}  
  8. <br>isRead: {{items.isRead}}  
  9. <br>receivedDateTime: {{items.receivedDateTime}}  
  10. </b>  
  11. </div>  
  12. </div>   
Response:
     Response-1
 

 

Please refer the Graph Explorer to get to know all the available API methods in Microsoft Graph. So, far we have discussed how to integrate Microsoft Graph in SPFx webparts and some samples for that as well.