Download the code here
Overview
When building SharePoint Framework solutions, you can easily connect to the Microsoft Graph by using the MSGraphClient. MSGraphClient is a new HTTP client introduced in SharePoint Framework v1.6.0 that simplifies connecting to the Microsoft Graph inside SharePoint Framework solutions.
The MSGraphClient is available only in projects built using SharePoint Framework v1.6.0 and later. While the MSGraphClient is explained in this article by using a client-side web part to retrieve SharePoint list items, you can also use it in SharePoint Framework Extensions.
In this article I am going to show how to retrieve SharePoint list items using MS graph API for SharePoint Framework web part. Since I found that all the post in the Internet showing example using /me or /users MS graph API and no reference for retrieve SharePoint list Items.
Existing Office 365 APIs
Microsoft Graph API – formerly known as Office 365 unified API, is the new service-oriented architecture owned by Microsoft to allow developers to access a vast amount of data from the Microsoft cloud platforms. Microsoft web API is essentially designed to collaborate with Office 365 and some others services hosted on the MS Azure cloud platform. Previous we have below list of APIs and now we have unified MS graph API for all this application and for new office 365 applications.
Service | Functionality | Base URL |
Azure AD Graph | User, Groups Application, Devices | https://graph.windows.net |
Exchange Online | Mail, Calendar, Contacts | https://outlook.office365.com/api |
SharePoint Online | List, Libraries, Search, User Profiles | https://tenant.sharepoint.com/_api |
OneDrive for Business | Files, Folders | https://tenant-my.sharepoint.com/_api |
OneNote | Notebooks,Pages | https://onenote.com/api |
Yammer | Conversations | https://yammer.com/api |
Stream | Videos, Channels | https://tenant.sharepoint.com/portals |
Microsoft Graph API
Microsoft Graph is a Restful web API that enables you to access Microsoft Cloud service resources. Microsoft Graph is a unified API endpoint for accessing data across Microsoft 365, which includes Office 365, Enterprise Mobility, and Security and Windows services. It provides a simplified developer experience, with one endpoint and a single authentication token that gives your app access to data across all these services.
Microsoft Graph exposes REST APIs and client libraries to access data on the following Microsoft 365 services:
- Office 365 services: Delve, Excel, Microsoft Bookings, Microsoft Teams, OneDrive, OneNote, Outlook/Exchange, Planner, and SharePoint
- Enterprise Mobility and Security services: Advanced Threat Analytics, Advanced Threat Protection, Azure Active Directory, Identity Manager, and In tune
- Windows 10 services: activities, devices, notifications
- Dynamics 365 Business Central

Consume Microsoft Graph
You can now implement the below methods to consume the Microsoft Graph. You have two options:
Use the AadHttpClient client object
The AadHttpClient client object is useful for consuming any REST API. You can use it to consume Microsoft Graph or any other third-party (or first-party) REST API and “AadHttpClient” is used to perform REST calls against an Azure AD Application, for example 3rd party WebAPI hosted in Azure.
this.props.context.aadHttpClientFactory
.getClient('https://graph.microsoft.com’)
.then((client: AadHttpClient) => {
// Search for the users with givenName, surname, or displayName equal to the searchFor value
return client .get( `https://graph.microsoft.com/v1.0/users?$select=displayName,mail,userPrincipalName&$filter=(givenName%20eq%20'${escape(this.state.searchFor)}')%20or%20(surname%20eq%20'${escape(this.state.searchFor)}')%20or%20(displayName%20eq%20'${escape(this.state.searchFor)}')`, AadHttpClient.configurations.v1
);
})
.then(response => {
return response.json();
})
Use the MSGraphClient client object
“MSGraphClient” is used to perform REST calls against Microsoft Graph. The Microsoft Graph JavaScript client library is a lightweight wrapper around the Microsoft Graph API. This class allows developers to start making REST calls to MSGraph without needing to initialize the MSGraph client library.
this.props.context.msGraphClientFactory
.getClient()
.then((client: MSGraphClient): void => {
// From https://github.com/microsoftgraph/msgraph-sdk-javascript sample
client
.api("users")
.version("v1.0")
.select("displayName,mail,userPrincipalName")
.filter(`(givenName eq '${escape(this.state.searchFor)}') or (surname eq '${escape(this.state.searchFor)}') or (displayName eq '${escape(this.state.searchFor)}')`)
.get((err, res) => {
if (err) { console.error(err); return; }
SharePoint Framework v1.6.0 on wards supported consuming the MS Graph APIs and custom APIs.
API Permission / API access
- To consume Microsoft Graph or any other third-party REST API, you need to explicitly declare the permission requirements from an OAuth perspective in the manifest of your solution.
- In the SharePoint Framework v.1.4.1 or later, you can do that by configuring the webApiPermissionRequests property in the package-solution.json under the config folder of the solution.
- Microsoft Graph permission names follow a simple pattern: resource.operation.constraint..Read grants permission to read the profile of the signed-in user.
- User.ReadWrite grants permission to read and modify the profile of the signed-in user and
- Mail.Send grants permission to send mail on behalf of the signed-in user.
"webApiPermissionRequests": [
{
"resource": "Microsoft Graph",
"scope": "User.ReadBasic.All"
}
]
Retrieve SharePoint List Items Using Microsoft Graph API
In this article, we will be creating a client Web part, which will be retrieving the list items from SharePoint List (Contactlist) using MS Grapgh api and will display it in the tabular form in the client Web part, as shown below.

Step 1 : Setup your SPFx development environment – follow here
Step 2: Develop SPfx webpart
Open a command prompt. Create a directory for the SPFx solution.
md spfx-graphapi-listdata
Navigate to the above created directory.
cd md spfx-graphapi-listdata
Run the Yeoman SharePoint Generator to create the solution and select react for our example
yo @microsoft/sharepoint
Yeoman generator will present you with the wizard by asking questions about the solution to be created and Yeoman generator will perform the scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.

Once the scaffolding process is completed, lock down the version of the project dependencies by running below command
npm shrinkwrap
In the command prompt type below command to open the solution in the visual studio code editor or open your own editor.
code .
Go to GraphConsumersplistWebPart.ts file and render the webpartcontext
public render(): void {
const element: React.ReactElement<IGraphConsumersplistProps> = React.createElement(
GraphConsumersplist,
{
description: this.properties.description,
context: this.context,
}
);
ReactDom.render(element, this.domElement);
}
Create a new file under components folder IListItem.ts and paste below code – interface for our sp list columns
export interface IListItem {
Title: string;
ContactNumber: string;
CompanyName: string;
Country:string;
}
Create another file under component folder IGraphConsumersplistState.ts and paste below code – interface for react state to handle multiple records
import { IListItem } from './IListItem';
export interface IGraphConsumersplistState {
lists: Array<IListItem>;
}
Open IGraphConsumersplistProps.ts file under component folder and assign the webpart context
import { WebPartContext } from '@microsoft/sp-webpart-base';
export interface IGraphConsumersplistProps {
description: string;
context: WebPartContext;
}
Open GraphConsumersplist.tsx file under component folder add below codes
Import below files
import { IGraphConsumersplistState } from './IGraphConsumersplistState';
import { IListItem } from './IListItem';
import { MSGraphClient } from "@microsoft/sp-http";
import {
autobind,
PrimaryButton,
TextField,
Label,
DetailsList,
DetailsListLayoutMode,
CheckboxVisibility,
SelectionMode
} from 'office-ui-fabric-react';
then Configure the columns for the DetailsList component
let _listItemColumns = [
{
key: 'ContactPerson',
name: 'Contact Person',
fieldName: 'Title',
minWidth: 50,
maxWidth: 200,
isResizable: true
},
{
key: 'ContactNumber',
name: 'Contact Number',
fieldName: 'ContactNumber',
minWidth: 50,
maxWidth: 200,
isResizable: true
},
{
key: 'CompanyName',
name: 'Company Name',
fieldName: 'CompanyName',
minWidth: 50,
maxWidth: 200,
isResizable: true
},
{
key: 'Country',
name: 'Country',
fieldName: 'Country',
minWidth: 50,
maxWidth: 200,
isResizable: true
},
];
This array is used in the settings of the DetailsList component, as you can see in the render() method of the React component.
To render the graph api out put to Detail list column, replace below code to the render() method
public render(): React.ReactElement<IGraphConsumersplistProps> {
return (
<div className={ styles.graphConsumersplist }>
<div className={ styles.container }>
<div className={ styles.row }>
<div className={ styles.column }>
<span className={ styles.title }>List Contact List Items</span>
{
(this.state.lists != null && this.state.lists.length > 0) ?
<p className={ styles.form }>
<DetailsList
items={ this.state.lists }
columns={ _listItemColumns }
setKey='set'
checkboxVisibility={ CheckboxVisibility.hidden }
selectionMode={ SelectionMode.none }
layoutMode={ DetailsListLayoutMode.fixedColumns }
compact={ true }
/>
</p>
: null
}
</div>
</div>
</div>
</div>
);
}
Update the React component type declaration and add a constructor
constructor(props: IGraphConsumersplistProps, state: IGraphConsumersplistState) {
super(props);
// Initialize the state of the component
this.state = {
lists: []
};
}
Get List Items using Microsoft API replace the ComponentDidMount() method and all these methods support the asynchronous development model of Type Script, you can handle their result with promises.
You get an instance of the MSGraphClient type by calling the context.msGraphClientFactory.getClient()
method.
You then use the fluent API of the Microsoft Graph SDK to define the OData query that runs against the target Microsoft Graph endpoint.
The result is a JSON response that you have to decode and map to the typed result.
public componentDidMount(){
// Log the current operation
console.log("Using _searchWithGraph() method");
this.props.context.msGraphClientFactory
.getClient()
.then((client: MSGraphClient): void => {
client
.api("sites('root')/lists('Contactlist')/items?expand=fields")
.version("v1.0")
.get((err, res) => {
if (err) {
console.error(err);
return;
}
// Prepare the output array
var lists: Array<IListItem> = new Array<IListItem>();
// Map the JSON response to the output array
res.value.map((item: any) => {
lists.push( {
Title: item.fields.Title,
ContactNumber: item.fields.ContactNumber,
CompanyName: item.fields.CompanyName,
Country: item.fields.Country,
});
});
// Update the component state accordingly to the result
this.setState(
{
lists: lists,
}
);
});
});
}
Step 3: Configure the API permissions requests
To consume Microsoft Graph or any other third-party REST API, you need to explicitly declare the permission requirements from an OAuth perspective in the manifest of your solution.
Copy the declaration of the webApiPermissionRequests property in cofig\package-solution.json
"webApiPermissionRequests": [{
"resource": "Microsoft Graph",
"scope": "User.ReadBasic.All"
},
{
"resource": "Microsoft Graph",
"scope": "Sites.Read.All"
},
{
"resource": "Microsoft Graph",
"scope": "Sites.ReadWrite.All"
}
]
Notice the webApiPermissionRequests, which is an array of webApiPermissionRequest items. Each item defines the resource and the scope of the permission request. Don’t add the scope together, it will throw error while approve the API permission
Step 4: Deploy the solution and grant permissions
Run the gulp commands
gulp build
gulp bundle --ship
gulp package-solution --ship

Also verify the package-solution.json file under confirg folder
"includeClientSideAssets": true,
"isDomainIsolated": true,
Deploy the webpart as Isolated webpart to maintain the security, when grant permission via API access.
Deploy the package soluton
- Browse to the app catalog of your target tenant and upload the solution package.
- You can find the solution package under the sharepoint/solution folder of your solution.
- It is the .sppkg file. After you upload the solution package, the app catalog prompts you with a dialog box,
- Click Deploy and deploy your solution

A message in the lower part of the screen tells you that the solution package requires permissions approval. This is because of the webApiPermissionRequests property in the package-solution.json file. nder
Microsoft Graph
- User.ReadBasic.All
- Sites.Read.All
- Sites.ReadWrite.All
API Permission Management
- After deploying the web part, follow the below steps to approve API requests.
- Open SharePoint Admin Center (https://[tenant]-admin.sharepoint.com).
- From left navigation, click “Advanced” –> API access.
- Approve the pending requests, refer below screenshot FYR

And you’re now ready to go.
Step 5: Test the Solution
- Open the Share Point Site
- Add a app and install the deployed app
- Then add as web part
- See the result like below

Summary
Microsoft Graph offers a wide range of APIs to access the content and services provided by Office 365. In this article we discussed to retrieve SharePoint list items using MS Graph API.
Download the Code here