Extending the Reach of SPFX Solutions

Bill Ayers


the eBook considers why, as a SharePoint Developer, the Microsoft Graph is essential to you and how it’s supposed to help you and make you more productive. We also cover where these technologies are heading and look at the raw rest API used to interact with the Microsoft Graph at a fairly low level.

If you’ve been a developer for several years working on SharePoint, you might be aware that there have been several development models and different APIs and that, sometimes, it has been challenging to keep track of all of them. This is where the Microsoft Graph API comes to the rescue.

Within this eBook, we cover why, as a SharePoint Developer, the Microsoft Graph is essential to you and how it’s supposed to make you more productive. We also cover where these technologies are heading and look at the raw rest API used to interact with the Microsoft Graph at a fairly low level. To finalise we’ll talk about some of the wrapper libraries that we can use to make it a lot easier to develop against the Microsoft Graph.

We will cover the following topics:

  • What is a Graph
  • The Microsoft Graph
  • Where will it end?
  • Raw REST API
  • MSGraphClient
  • @Pnp/Graph
  • Conclusions

What is a graph


A Graph is a term in discrete mathematics which refers to relationships between items. Graph diagrams show some dots connected by lines (see picture above). The dots are sometimes called vertices or nodes (depending on which discipline of person you’re talking to). The connecting lines, sometimes called arcs, can be unidirectional or bi-directional. So, a Graph it’s just a collection of objects connected in various ways. It’s a very general data structure — much more general than a relational table, or any hierarchical relationship.

A Graph is a useful model for real-world processors and the information we’ve got in our businesses. Nodes may be people, topics or files we work with, and we may have very complex interactions with them.

A Graph is a data structure or constructs that can capture very complex information. A similar model is found in the brain. Neuroscientists have come up with a way where they can apply differential fluorescent dyes to different brain cells in an animal brain in the laboratory. In the case of simple organisms, they can trace the wiring between the cells of the brain and see how they work. This is not a new technique created by humans; it’s how human and animal brains work.


The Microsoft Graph

The Microsoft Graph is a unified REST (representational state transfer) API that wraps the many different APIs that have existed in the Microsoft 365 infrastructure for some time. These existing APIs were developed by different teams within Microsoft to give programmatic access to Office 365 services and applications like Outlook, Delve and Active Directory. The new Graph API provides a unifying and consistent way for connecting to all of these services and respective APIs.


The Microsoft Graph API first started by exposing people information from Azure AD identity services. Over time the demand for extra information about different artefacts – and the relationships between them – started to increase, so the Graph API was extended to expose artefacts like files, documents, videos, music, charts etc. The relationships between artefacts can be unidirectional or bidirectional; for instance, the relationship between a line manager and employee would be unidirectional while a relationship between colleagues (peers) would be bi-directional.

After files and people, the Microsoft Graph started to expose conversations like emails, chats and collaboration around documents. All of this is the lifeblood of a business; it is the people in it, and how they are interacting, and it was the first layer of information exposed by the Microsoft Graph API.

The next Microsoft Graph layer is called Insights (formerly known as the Office Graph). Insights can be seen as search on steroids because it augments the results provided by standard search by proactively surfacing related information that users may have not even have thought about when starting their search. For example, “people that looked for these documents have also looked for these other documents” or “another person that knows about this topic is person x”. This is compelling functionality, powered by Artificial Intelligent, that opens a vast amount of possibilities. It will be very exciting to see how this technology develops further and what we can with it.


The Microsoft Graph REST API is a wrapper API that encapsulates the legacy APIs that were developed to access the individual underlying systems. Besides giving us a unified and consistent way to access all of these systems, the Microsoft Graph API also provides a single authorisation endpoint with a single security token.


One of the potential issues you may find with the Microsoft Graph API is that some of the functionality provided by the individual underlying APIs may not have yet been implemented in the Graph API. In those cases, you may have to revert to using the specific underlying API instead.


Microsoft is heavily investing in the Graph API with more and more functionality constantly added to it.


In this eBook, we cover how to build SharePoint web parts that use the REST Microsoft Graph API to present information from all of these underlying services and systems.

Using the Graph API

Microsoft provides a unified REST endpoint for all graph API calls at https://graph.micropsoft.com. A request to the API is made using simple HTTP verbs like GET, POST, PATCH, PUT and DELETE and takes the following format:


  • {version} – is the version of the API we are using (e.g. /v1.0 or /beta)
  • {resource} – is the resource we are trying to access (e.g. /users, /groups, /sites, /devices …)
  • {id} – the id of the individual resource you are trying to access (e.g. /bill to access a user named Bill)
  • {property} – property of the resource you are trying to access (e.g. /department)

The Graph can be traversed via navigations which are simply properties connecting different objects. For example, if you want to access all the events associated with Bill, you would use /users/bill/events as the resource (you would need to have the right permissions to do it).

Query parameters are used to do things like filter, format, order and paging results (amongst others), just like you would do with SQL, and are critical to format and reduce the amount of data you are transferring “over the wire”. These queries are part of an open standard called OData that dictate how they are constructed.


There are several ways to call the Graph API from a client. For instance, you can use jQuery or the native JavaScript XMLHttpRequest object. I like to avoid dependencies on jQuery if I can so I use the XMLHttpRequest object, but that is simply a personal choice.

When calling the API, we need to ensure that the HTTP request headers specify the format we want the response to come back in. This is done via an “Accept” header which allows us to control the format and amount of data that is returned to us. In the example below, we are using the value “application/json;odata=verbose” to specify that we want the result formatted as JSON. The different possible values for this header are part of the HTTP protocol and fall outside of the scope of this book.

We also need to provide an authorisation header so that the service we are trying to use can determine if we have the correct permissions to access the requested resource. When using a SharePoint page to call the Graph API (e.g. via a WebPart), this header is already filled by the browser (this happens when you authenticate to SharePoint) but, if we want to access the API programmatically, we would need to provide the value for the header ourselves.


Exploring the Graph API

Microsoft provides excellent online support and documentation for the Graph API on their site: https://developer.microsoft.com/en-us/graph. There you can find to find a link to Graph Explorer (https://developer.microsoft.com/en-us/graph/graph-explorer) which is the best way to quickly start to explore what the Graph API can do and how it works.


From the Graph Explorer homepage, you can make queries against all the Microsoft services that support Graph.

By default, when you open the homepage, you can run a query that returns information about the current user (me). If you are not logged in, Graph returns information about a fictitious user but, if you sign in with your Microsoft account, Graph returns your own information.

On the left-hand side of the screen, you can access a bunch of sample queries which will allow you to become familiar with the different message formats and headers returned by the API. For instance, when you run the sample query called “my photo”, you can see the following preview of the response body and headers returned by the API:


We can also extend the list of sample queries by following the “show more samples” link and choosing the category you are interested in:


By selecting insights, for example, you get a list of the recent files you accessed:


All of the information is returned in JSON (JavaScript Object Notation) format. In the example above the response, body contains a JSON array with the details of the files.

You can also modify the type of request you make by using the dropdown next to the request URL ( these are the standard request methods part of the HTTP specification):

  • GET – when you want to retrieve information about a resource
  • POST – when you want to submit information (e.g. create a new resource)
  • PUT – when you want to update information (e.g. fully update a new resource)
  • PATCH – when you want to partially modify information (e.g. partially modify a resource)
  • DELETE – when you want to delete information (e.g. delete a resource).

You need to be very careful if you sign in with your own Microsoft Account because you could be running the queries against your live production tenant and can cause a lot of damage (if your permissions allow you).

It is recommended to set up a Development Office 365 tenant that can be used to develop and test your applications before deploying them to a production environment. You can easily do this online by joining the Office 365 developer program at https://developer.microsoft.com/en-us/office/dev-program.

This gives you a free Office 365 tenant that can be used for at least 1 year. At the end of the year, if you keep using the Tenant, Microsoft will keep renewing it for free.


You can also use the Development Tenant to explore future changes in the API that are still in development by selecting a beta endpoint (which is not recommended when using a live production tenant).


The Graph explorer also give you access to the documentation on individual queries; You simply need to click on the document icon next to the query you are interested in


If you haven’t already done so, join the Developer Program, you also get some emails and information sent periodically.


The Authorization story behind the Graph continues to improve as well. If you’re writing requests at a low level and having to provide your own security token, then you should learn about the Active Directory Authentication Library (ADAL) or the Microsoft Authentication Library (MSAL). These are authentication and authorisation libraries that will provide a security token that you will need to use to call the Microsoft Graph.

At the moment we’re on a journey between the Version 1 and Version 2 endpoints.  If you use some of the rapid libraries, I’m going to show you later you don’t need to worry too much about which one to use.


Generally, when you are building a web part using the SharePoint Framework, you have a user’s context (the user looking at the page where the web part is deployed), so you probably will want to use the Delegated Permissions of that user to interact with the Graph API. To do this you need to register an application and give it certain user privileges (that’s a deep dive topic that we are not going to cover here). When a user is using the web part, the overall permissions are the interception of the delegated application permissions and the user permissions. Because of this, when using delegated permissions, there’s nothing that will allow users to do something that they couldn’t otherwise have done in some other way.

Sometimes you may want to build a demon service (a service that is running automatically in the background without user interaction) that is using the Graph API (e.g. to connect to an underlying system like SharePoint). In these circumstances, you would have to use Application Permissions because you are running a process that does not have a user context.


The examples I will use for the remainder of this book will be using Delegated Permissions and the SharePoint Framework


The Microsoft Graph permissions are structured into the following way:

You can find the permissions that you need to access a specific resource by looking at the Graph API documentation.

In the following example, you can see that we require “Group.Read.All, Group.ReadWrite.All” delegated and application permissions to be able to get a channel message. You would need to ensure that you have those permissions correctly configured when you create the application.


Microsoft Graph SDKs

We can avoid a lot of the complexity of working with the Microsoft Graph ( e.g. setting up the security access tokens) by using wrapper SDKs. Microsoft released SDKs that support a variety of languages and platforms. You can choose the ones that suit you best from the Microsoft Graph web page (https://developer.microsoft.com/en-us/graph).

These SDKs will give strong typing (depending on the programming language you are using) and help (like Intellisense) which can make your life a lot easier.


Microsoft Normally generates these SDKs by using a tool called VIPR (https://github.com/microsoft/vipr). VIPR takes the Graph metadata and generates an API for a specific language (e.g. JavaScript). Sometimes the generated API needs to be manually fine-tuned before it can be released.


You can see the list of SDKs generated by the Microsoft Graph Team by going to https://github.com/microsoftgraph and searching for the SDK in the language you are interested in, these SDKs are usually kept reasonably up to date:


Microsoft Graph and the SharePoint Framework

In this section, I’m going to show you two examples of how to connect to the Microsoft Graph API from a SharePoint web part. In the first example, we are going to be using the MSGRaphClient library, developed by Microsoft and in the second example, we are going to be using the PnP.js library, developed by the Practices and Patterns community.

MSGraphClient library

When it comes to building solutions with SharePoint Framework, we are quite lucky because we have MSGraphClient; a new HTTP client introduced in the SharePoint Framework v1.6.0. The MSGraphClient greatly simplifies the way we call the Graph API.

In the following example, I’m going to show you how to use the MSGraphClient from a SharePoint Framework solution. We are creating a simple SharePoint WebPart that gets the name of the current user (using the MS Graph) and displays it on the screen.

We are going to start with a standard SharePoint web part project generated by Yoman (for more information on Yoman please check https://docs.microsoft.com/en-us/sharepoint/dev/spfx/toolchain/scaffolding-projects-using-yeoman-sharepoint-generator) and open the project directory Visual Studio Code:


To import the MSGraphClient library, add the following lines 12 and 13 to the generated MsGraphWebPart.ts file:


I’ve imported the types library (line 13) because I wanted to have strong typing for the objects that the library returns (we will see this later).

I then added the lines 38 to 42:


Which are doing the following:

  • First I’m getting an instance of the client by calling: this.context.msGraphClientFactory.getClient() 
  • This returns an object of type MSGraphClient (which we called client).
  • We then use the client object to get the “me” resource from the Graph API (line 39). This returns an object of type User that gets assigned to the return variable res.

We then get the displayName property of the User object and update the contents of the web part by adding an HTML H1 header element with the value of the displayName (line 40).

Because we imported the MS Graph type definitions (line 13), we can change line 39 and qualify the return object (res) with the type MSGraph.User. This will give us Intellisense so that we can easily see all the properties of the user object while we type our code (this can save you a lot of mistakes):


To see this web part in action you need to run it in a tenant SharePoint Workbench instead of your local development Workbench.  This is because you will not be able to get information about the “me” resource in your local Workbench.

To run this web part in your tenant SharePoint Workbench you need to go to  “[your sharepoint tenant url]/_layouts/15/workbench.aspx and add the web part to the page (in this example the web part is called MSGraph):


After a small delay, the web part text is updated to display your name which is the display name returned by the MS Graph.



There is also a library, created by the Patterns and Practices community, that makes using the Graph API even easier. This library is part of the Pnp.js project and can be found in GitHub (https://github.com/pnp/pnpjs) under the @pnp/graph npm package:


You can get examples of how to use this library from GitHub https://github.com/SharePoint/sp-dev-fx-webparts. For this example, I’m going to use the “react-functional-component-with-data-fetch” sample that you can find under the samples folder (https://github.com/SharePoint/sp-dev-fx-webparts/tree/master/samples/react-functional-component-with-data-fetch).


This example gets a list of Microsoft Teams, that the current user is a member of, and displays it in a SharePoint web part. It also shows the channels inside of each Team.

This example was mainly created to show how to use React Functional Components, but It also uses the Graph Library. That’s why I’m going to be using it as an example here.

If you download the example to your local development environment and open the directory with Visual Studio Code you get the following:


As you can see, in the TeamsTrackerWebPart.ts file, we are importing the @pnp/graph package in line 7.  Then, in line 18, during the call to the web part onInit method, we are calling the graph setup method and passing in the current SharePoint context. That’s all we need to do to initialise this library; very simple and effective.

In the TeamsTracker.tsx file, you can see that, in line 17, we now have a fully strongly typed library. We can access me as an object property and have full IntelliSense support (see below).


Previously, with the MSGraphClient library, we had to supply a string with the value of “me”( client.api(“/me”)). In this example, with the PnP library, everything is strongly typed. When we type “graph.me” we get access to all the properties and methods of the User Object:


As you can see, with the PnP library you get a lot of help which make it a lot easier to write code and avoid mistakes.

In line 17, we are getting the Teams that the current user is a member of, and then we render them using React (see lines 27 to 31 below). In this case we created a React control called Team to render each team.


Each one of these Team controls then also makes a call to the Graph to get the list of channels in the Team;


If we now run this project in the Tenant SharePoint Workbench by adding the TeamsTracker web part to the page;


We can see that, because this is running in the context of a SharePoint tenant, we have a list of Microsoft Teams that I’m a member of:


If we edit the web part we can also turn on the display of the channels for each Team:


You can see, this example is making use of the Graph API to get the information from Microsoft Teams, but you can use a similar approach to get information from any other Office 365 system supported by the Microsoft Graph.


We talked about a few different ways to access the Microsoft Graph. We only scratched the surface here. Which one you use is really up to your preference and by the services and functionality, you require. In some situations, you may be forced to use the Legacy APIs because they are more mature and some of the functionality may not yet be available in the Graph.

The PnPJS library includes wrappers for all of the SharePoint REST APIs. You may find that this is the easier one to use when you want to connect to SharePoint.

The next step from the PnPJS library will be the Microsoft REST API or the Microsoft Graph language-specific wrappers. Because Microsoft maintains these libraries, you may find that some of the new functionality reaches these before reaching the PnPJS library.


0000-00-00 00:00:00

Leave a Reply

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

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}