Leveraging Microsoft Graph Apis As An Alternative Approach To Sharepoint Online Rest Apis

The Core Problem with SharePoint REST APIs

SharePoint Online provides a REST API for accessing SharePoint data and performing content management tasks. However, the SharePoint REST API has some key limitations when compared to the Microsoft Graph API.

Firstly, the SharePoint REST API lacks feature parity with the Microsoft Graph. Many useful services like Groups, Teams, Outlook, and Planner have rich APIs available in Microsoft Graph, but lack client libraries in SharePoint. This limits what can be built on top of SharePoint alone.

Additionally, the SharePoint REST APIs lack standardization across different API versions. Method names, parameters, and payloads vary across legacy 2013, 2016 and modern SharePoint APIs. This makes building reusable components challenging.

Finally, the permissions and authentication model for the SharePoint REST APIs is fragmented across app-only tokens, user delegated tokens, add-in licenses and sharepoint groups. Complex application registration is often required purely to call SharePoint APIs.

Introducing Microsoft Graph

The Microsoft Graph is a unified RESTful web API that can be called from any programming language to access data across Microsoft 365 cloud services. This includes core services like Azure Active Directory, Exchange, SharePoint, OneDrive, and Teams.

Rather than having separate endpoints for each service, Microsoft Graph standardizes access under a common https://graph.microsoft.com endpoint. A unified authentication provider and standardized permission scopes simplify cross-service data access.

For SharePoint and OneDrive specifically, Microsoft Graph exposes an extensive API surface. Drive resources represent SharePoint document libraries and OneDrive folders. Under drives, the DriveItem endpoint represents individual files and folders with properties like versions, permissions and metadata.

Key Benefits of Using Microsoft Graph

Simple and Consistent APIs

By representing SharePoint content as Drive and DriveItem resources, Microsoft Graph creates a simple and consistent API for Microsoft 365 file storage. Whether code is accessing OneDrive, SharePoint or Teams files, the same DriveItem methods can be used.

All Graph resources share a common OData 4 protocol for query parameters, metadata navigation and payloads. Constructing Graph queries is straightforward with $select and $expand.

Granular Permission Scopes

Microsoft Graph permission scopes target individual resources. Delegated Files.Read scope grants access to user OneDrive content without any SharePoint permissions needed. SharePoint add-ins require complex tenant and site collection permissions.

Microsoft Graph includes delegated and application-level permissions for precise privilege control. Resources expose granular CRUD methods like GET, POST and PATCH for reading, creating and updating content.

Powerful Query Capabilities

Microsoft Graph exposes filter and order expressions modeled after OData query parameters. Complex hierarchical queries are possible using $expand alongside $filter clauses. These parameterize what related entities are expanded inline.

The Graph also supports batching for optimized execution of write operations. Batch support encapsulates creates, updates and deletes in a single round trip.

Accessing SharePoint Content with Graph

Leveraging Drive and DriveItem Resources

In Microsoft Graph, SharePoint sites surface as Drive resources, Document libraries and OneDrive folders appear as Drives, and individual files or folders map to DriveItems. Any content addressable via a SharePoint or OneDrive URL can be accessed as an item.

Using this abstraction, SharePoint list rows become DriveItems within a Drive holding that list. Files, list items and folders share a common DriveItem type with a polymorphic design that can represent any content type.

Querying SharePoint Lists and Libraries

Microsoft Graph exposes SharePoint lists and document libraries via the “list” and “listItem” facets on DriveItem resources. By targeting the list facet and using $expand, list schema and items surface inline.

For example, expanding the list facet on a Drive holding a calendar list directly surfaces calendar events. No differentiation in code is needed between accessing files or lists.

Handling Versions and Folder Structures

Within SharePoint and OneDrive, Microsoft Graph tracks DriveItem versions over time using the versions navigation property. Specific historic versions can be addressed via version ID. Since trees surface as Drive containers, folder structures compose via the children attribute.

The Drive API also exposes special folders like the Photos folder along with shared Drives held within SharePoint. The full content hierarchy composes consistently regardless of the data source location.

Building Custom Solutions with Graph

Authentication and Setup

Before querying Microsoft Graph for SharePoint or OneDrive content, an access token with appropriate delegated or application permission scopes must be acquired. Tokens typically derive from an Azure Active Authentication Library (ADAL) OAuth 2.0 grant flow.

For user based delegated auth, the OAuth 2.0 authorization code grant flow handles redirecting the user through login consent workflows. For daemon applications, OAuth 2.0 client credentials grant can directly request an access token.

Best Practices for Querying Data

When querying SharePoint DriveItems via Graph, follow OData best practices for efficient data transfer. Always specify the $select parameter to limit unnecessary metadata, and $expand parameters to inline needed resource collections.

Filter results with a $filter clause when possible as opposed to client-side filtering. Paginate queries by specifying a $top value per page alongside an evolving $skip token to handle result sets in chunks.

Paging Through Large Result Sets

To page through SharePoint DriveItem or listItem query results in segments:

  1. Begin with a query including $top and $select parameters, but no $skip
  2. Extract the @odata.nextLink value from the response
  3. Reissue the query with that nextLink value as the request URL to get the next result segment
  4. Repeat passing the latest @odata.nextLink to get all pages

In this manner, Graph queries can be fully enumerated without ever holding the complete result set in local memory.

Going Beyond SharePoint with Graph

Unlocking the Power of the Microsoft Cloud

A key advantage provided by Microsoft Graph versus the SharePoint REST API surface is that Graph exposes all of Microsoft 365 services under one API endpoint. By granting access to additional resources, entire new categories of integrated solutions become possible.

For example, a SharePoint dashboard can render insights using analytics data from the Reports endpoint to track usage. A custom Teams bot can scan messages and route important items into a SharePoint list via Graph for archival.

Integrating Services like Outlook, Teams and More

Alongside SharePoint and OneDrive, Microsoft Graph grants access to Exchange, Azure AD, Intune, Planner, OneNote, Excel, and Microsoft Bookings. Any combination of services can be queried or manipulated within a single app via Graph.

Supporting services like identity, profile, schema, and licensing enable building fully cloud integrated scenarios leveraging Microsoft 365 as a complete platform. Microsoft Graph truly glues together all endpoints into one.

Example Code for Common SharePoint Graph Queries

Connecting to Graph

  // Helper method to get Graph access token  
  async function GetGraphToken() {

    const token = await authProvider.getAccessToken();  

    const headers = new Headers();
    headers.append('Authorization', `Bearer ${token}`);

    const options = {
      method: 'GET',
      headers: headers
    };

    return options;
  }

Getting Drive Item Metadata

const itemUrl = 'https://graph.microsoft.com/v1.0/drives/{drive-id}/items/{item-id}';

const options = await GetGraphToken(); 

// GET DriveItem metadata
const response = await fetch(itemUrl, options);

const driveItem = await response.json();

Expanding a SharePoint List

const listUrl = `https://graph.microsoft.com/v1.0/drives/{drive-id}/items/{list-id}`;

const expandList = `${listUrl}?$expand=list`;

const options = await GetGraphToken();

// GET List with metadata expanded 
const response = await fetch(expandList, options);

const expandedList = await response.json();

Leave a Reply

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