Thursday, September 27, 2018

Example of wrapper to ease usage of Graph calls in SPFx

silhouette of trees and purple lightning

Waldek Mastykarz wrote a good post about not passing the web part context all around your React components, which is good advice. And as Waldek pointed out after reviewing my code I pass the full context and not just the GraphClient. So ideally, passing just what you need is better, but I’m lazy at times :) And it gives you the reader an opportunity to improve my code :)

I tend to create static helper classes, and here’s one approach to ease calling Graph API’s throughout your solution.

The wrapper class is quite simple, and I’ve created helper methods for GET, POST, PATCH, DELETE.

To use this you would first initialize the class in your main web part code.

public async render(): Promise<void> {
   await MSGraph.Init(this.context);

and somewhere in your code if you wanted to get Group data for a group you could use something like this:

import { MSGraph } from '../services/MSGraph';


let groupId = this.props.context.pageContext.legacyPageContext.groupId;
let graphUrl = `/groups/${groupId}`;
let group = await MSGraph.Get(graphUrl);

Photo by Jeremy Thomas at Unsplash


  1. Hi Mikael, This is great, thanks.
    Although I get a strange error on this line...
    this._graphClient = await context.msGraphClientFactory.getClient();
    Type 'MSGraphClient' is not assignable to type 'MSGraphClient'. Two different types with this name exist, but they are unrelated.

    I've checked for multiple imports, reloaded node modules, etc but nothing seems to work.
    I've recently updated this to SPFX 1.6, successfully other than this, but that might be the cause

    1. Try "npm dedupe" then build. When updating use the Office 365 CLI, as it gives all steps needed for a proper upgrade. You may also nuke node_modules and reinstall before building.

  2. This is great!! Thank you so much. I used already a service to get data from Graph but this makes it so much cleaner.

  3. Hi Mikael, Thanks alot writing this wrapper which can be used in any project.
    Having issues in filtering data. Not sure what wrong I'm doing this.

    Below is the URL and its response in graph explorer. It is works in graph explorer, it would work with your code also.$select=id,displayName&$filter=startswith(displayName,T)

    "error": {
    "code": "Request_UnsupportedQuery",
    "message": "Unsupported Query.",
    "innerError": {
    "request-id": "0bed92ef-4391-4d39-82d5-8d837fa4c5d4",
    "date": "2019-06-21T08:53:06"

    1. Very hard to debug this remote. Open F12 dev tools and look at the request being sent and see if you can spot where the error is.