SPFx and Microsoft Graph: Accessing User Data

Microsoft Graph is the API to access Microsoft 365 data. Here’s how to use it from SPFx web parts.

Setup Graph Client

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

// Get client from context
const client: MSGraphClient = await this.context.msGraphClientFactory.getClient();

// Make request
const me = await client
  .api('/me')
  .select('displayName,mail,jobTitle')
  .get();

Common Operations

// Get user's photo
const photo = await client.api('/me/photo/$value').get();

// List user's teams
const teams = await client.api('/me/joinedTeams').get();

// Get calendar events
const events = await client
  .api('/me/events')
  .top(10)
  .orderby('start/dateTime')
  .get();

Permissions

Request permissions in package-solution.json:

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

Admins must approve these permissions in SharePoint Admin Center.

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.