SPFx - Data Access Options in SharePoint SPFx-Based Solutions

A technical overview for SharePoint Framework developers covering Fetch API, SPHttpClient, MSGraphClient and PnPjs.

Data access options in SharePoint SPFx-based solutions
Overview of common data access options in SharePoint Framework solutions.

Introduction

SharePoint Framework, commonly referred to as SPFx, is the primary development model for modern client-side customizations in SharePoint Online. Web parts, extensions, Adaptive Card Extensions and Microsoft Teams applications almost always need to access data from SharePoint or Microsoft 365. The selected data access technology has a direct impact on performance, maintainability, extensibility and the long-term sustainability of a solution.

SPFx development has changed significantly over time. In early SPFx projects, direct access to the SharePoint REST API was the dominant approach. Today, several established options are available. In addition to plain HTTP requests, specialized clients and libraries provide built-in support for authentication, request handling, typing and higher-level abstractions.

At the same time, Microsoft Graph has become increasingly important. Many Microsoft 365 resources are no longer exposed only through SharePoint-specific APIs. Instead, they are available through a tenant-wide API surface that spans users, groups, Teams, Outlook, Planner, OneDrive and SharePoint.

This article compares the most relevant data access options for SPFx-based solutions and explains when each approach is appropriate. The examples are based on the public demo repository:


https://github.com/maschroeder-z/data-access-option-spfx

Data Access Architecture in SPFx

An SPFx component runs entirely in the browser of the signed-in user. Requests are therefore executed in the security context of the current Microsoft 365 user. In most SPFx solutions, there is no dedicated server-side middleware between the browser and SharePoint or Microsoft Graph.

Authentication is handled by SharePoint Framework. In typical SharePoint scenarios, developers do not need to manually request OAuth tokens or construct authentication headers. Instead, SPFx provides preconfigured HTTP clients that are already aware of the current site, tenant and user context.

Depending on the target system, different APIs may be used:

  • SharePoint REST API
  • Microsoft Graph
  • External REST endpoints
  • Custom enterprise APIs
  • Azure Functions or other backend services

SharePoint REST focuses on SharePoint-specific resources such as webs, lists, list items, files and document libraries. Microsoft Graph provides access to a broader Microsoft 365 data model, including users, groups, Teams, Outlook, Planner and OneDrive. External systems are usually accessed through generic HTTP requests.

The Four Main Data Access Options

In SPFx-based development, four data access approaches are commonly used:

  • Native Fetch API
  • SPHttpClient
  • MSGraphClient
  • PnPjs

Each option represents a different level of abstraction. The native Fetch API provides the lowest level of abstraction and exposes the raw HTTP request. The SPHttpClient adds SharePoint-specific integration. The MSGraphClient focuses on Microsoft Graph. PnPjs provides the highest abstraction level with a fluent, strongly typed API for SharePoint and Microsoft Graph scenarios.

Choosing the Right Data Access Technology

The right choice depends on the requirements of the solution. There is no single best option for every scenario.

The native Fetch API is the most flexible approach. It can be used for SharePoint, Microsoft Graph, Azure Functions, third-party services or any other HTTP-based API. However, it provides no SharePoint-specific support. Headers, credentials, error handling, paging and request construction must be handled manually.

The SPHttpClient is designed specifically for SharePoint REST access. It is provided by SPFx and automatically integrates with the SharePoint authentication context. For traditional CRUD operations against SharePoint lists, document libraries or sites, it is often a simple and reliable choice.

The MSGraphClient is the appropriate option when data from Microsoft Graph is required. This includes scenarios involving users, groups, Teams, Outlook, Planner, OneDrive or tenant-wide Microsoft 365 data. It handles token management through SPFx but requires the necessary API permissions to be declared and approved.

PnPjs provides a fluent, developer-friendly abstraction over SharePoint REST and Microsoft Graph. It reduces boilerplate code and improves readability, especially in larger projects with many data access operations. Features such as batching, paging, typing and reusable query patterns make it a strong option for enterprise-grade SPFx solutions.

Comparison of Abstraction Levels

The main difference between the four approaches is how much of the underlying HTTP communication remains visible.

The Fetch API operates directly on the HTTP level. Every request header, query parameter and response conversion must be explicitly implemented. This provides maximum control but also increases the amount of repetitive code.

The SPHttpClient still exposes the SharePoint REST URL, but it adds SPFx-aware authentication and configuration. It is therefore close to the raw REST API while still reducing SharePoint-specific implementation effort.

The MSGraphClient abstracts authentication and provides a fluent interface for Microsoft Graph requests. Developers still need to understand the Graph endpoint structure, but the code is usually more readable than manually assembled REST URLs.

PnPjs hides most REST details behind a fluent object model. Instead of building URLs manually, developers work with concepts such as webs, lists, items, files, folders and users. This significantly improves maintainability in complex solutions.

Key Decision Criteria

Maintainability

The larger a project becomes, the more important readable and maintainable data access code becomes. Long REST URLs with nested OData parameters are difficult to extend and review. Fluent APIs such as PnPjs reduce this complexity and make intent more visible in the code.

Performance

In most scenarios, the selected client library has less impact on performance than the structure of the request itself. The number of HTTP calls, the amount of returned data, the use of $select, paging, batching and list indexing are usually more important than whether the request is issued through Fetch API, SPHttpClient or PnPjs.

Scope of Functionality

The SharePoint REST API still exposes many SharePoint-specific capabilities that are not fully available through Microsoft Graph. Microsoft Graph, however, is the preferred API for tenant-wide Microsoft 365 data. PnPjs provides convenient access to many SharePoint capabilities and can also be used with Microsoft Graph modules.

Future Readiness

Microsoft Graph continues to evolve as the central API for Microsoft 365. However, SharePoint REST remains highly relevant for SharePoint-specific development. Modern SPFx architectures often combine both: SharePoint REST or PnPjs for SharePoint data, Microsoft Graph for Microsoft 365 data and Fetch API for external services.

The Reference Project

The reference project demonstrates the same SharePoint list query using four different technologies. This makes the implementation differences directly visible. Each option retrieves comparable data, but the code structure, abstraction level and amount of boilerplate differ significantly.

The following sections of this article analyze each data access option in detail. The discussion covers architecture, typical use cases, advantages, disadvantages, code examples and practical recommendations for SPFx development.

Direct Data Access with the Native Fetch API

The simplest way to retrieve data within an SPFx solution is by using the browser's native Fetch API. Since it is part of every modern browser, no additional libraries or SharePoint-specific components are required. This makes it suitable not only for SharePoint but also for any REST-based service inside or outside the Microsoft 365 ecosystem.

Developers with a background in traditional web application development often start with fetch(). The API is straightforward, universally available and provides complete control over every aspect of the HTTP request. However, this low level of abstraction also means that authentication, request construction, error handling and response processing must be implemented explicitly.

Architecture

The Fetch API communicates directly with the target system over HTTP. Within an SPFx application, requests are executed in the security context of the currently authenticated user. Nevertheless, the Fetch API itself has no knowledge of SharePoint-specific concepts.

Developers are responsible for:

  • Building the REST endpoint URL
  • Defining HTTP headers
  • Selecting the appropriate HTTP method
  • Processing the server response
  • Implementing error handling
  • Managing paging
  • Applying OData query parameters
  • Optimizing request performance

The browser is responsible only for executing the HTTP request itself. Consequently, the generated request remains fully transparent, making it easy to understand exactly which REST endpoint is being called.

Typical Request Workflow

A standard Fetch API request typically consists of four steps:

  1. Construct the REST endpoint.
  2. Create the HTTP request.
  3. Execute the request using fetch().
  4. Deserialize and process the JSON response.

Since SharePoint REST returns JSON by default, the response is generally converted into a JavaScript object using response.json().

For simple list queries this workflow is easy to understand and requires only a few lines of code.

Example from the Reference Project

The following example retrieves a single list item using the native Fetch API. It is taken from the accompanying reference project.

public async GetWithFetch(): Promise<any[]> { const listUrl = `${this.absoluteURL}/_api/web/lists/getbytitle('${LIB}')/items?$select=id&$top=1`; const response = await fetch(listUrl, { method: 'GET', headers: { 'Accept': 'application/json;odata=verbose', 'Content-Type': 'application/json' }, credentials: 'include' }); const data = await response.json(); return data; }

This concise example clearly illustrates the direct nature of the Fetch API. Every aspect of the REST request remains visible within the source code, allowing developers to modify the endpoint or query parameters whenever necessary.

Building the REST Endpoint

Constructing a valid SharePoint REST URL is one of the most important aspects of working with the Fetch API.

https://tenant.sharepoint.com/sites/demo |_api |_web |_lists |_getbytitle('Documents') |_items ?$select=id &$top=1

Even small mistakes in the URL frequently result in HTTP errors or invalid responses.

More advanced scenarios often require additional OData parameters such as:

  • $filter
  • $expand
  • $orderby
  • $top
  • $skiptoken

As queries become more sophisticated, REST URLs quickly grow in length and complexity, making them increasingly difficult to maintain.

Authentication

A common misconception is that OAuth tokens must be generated manually when using the Fetch API inside SPFx. This is not the case for SharePoint endpoints.

By specifying:

credentials: "include"

the browser automatically sends the user's existing authentication cookies. SharePoint therefore executes the request in the current user's security context without requiring additional authentication logic.

The situation differs when communicating with external REST services. Those APIs often require additional authentication mechanisms such as OAuth access tokens or API keys.

Advantages

The Fetch API offers several characteristics that make it attractive in specific scenarios.

Maximum Flexibility

Since it has no dependency on SharePoint, virtually any REST-based service can be accessed.

  • Azure Functions
  • ASP.NET Web APIs
  • Third-party REST services
  • Enterprise APIs
  • Microsoft Graph (with custom authentication)

Complete Control

Every request header, query parameter and HTTP method is explicitly defined, making it possible to implement even highly specialized communication scenarios.

No Additional Dependencies

The Fetch API is built into the browser and therefore requires no additional npm packages. Bundle size remains minimal and no third-party libraries must be maintained.

Disadvantages

Boilerplate Code

Nearly every request contains repetitive code such as:

  • HTTP headers
  • Error handling
  • JSON parsing
  • Endpoint construction
  • Authentication settings

This repetitive code increases maintenance effort, especially in larger projects.

Higher Error Potential

Since REST URLs are manually assembled, typing mistakes or invalid OData parameters are more likely to occur. API changes must also be reflected manually throughout the codebase.

No SharePoint-Specific Features

Unlike SPHttpClient, the Fetch API provides no built-in support for SharePoint concepts such as request digests, batching or SharePoint-specific configuration.

Performance Considerations

It is often assumed that the Fetch API is significantly faster than SPHttpClient or PnPjs. In reality, measurable performance differences are minimal.

The overall response time is typically determined by:

  • Server-side processing
  • Network latency
  • Payload size
  • Number of HTTP requests
  • Query optimization

Optimizing the REST query itself usually has a much greater impact than choosing one client library over another.

Typical Use Cases

The Fetch API is particularly suitable for:

  • External REST services
  • Azure Functions
  • Enterprise backend APIs
  • Small SPFx projects
  • Proof-of-concept applications
  • Specialized HTTP communication scenarios

For large SharePoint applications, however, the manual implementation effort often outweighs the flexibility benefits.

Best Practices

  • Centralize REST endpoint construction.
  • Use $select to minimize payload size.
  • Implement centralized error handling.
  • Evaluate HTTP status codes explicitly.
  • Use strongly typed response models.
  • Move data access logic into reusable service classes.

Following these practices helps maintain a clean architecture even when using the browser's native HTTP client.

Summary

The Fetch API represents the most direct way to communicate with the SharePoint REST API. It offers maximum flexibility and is an excellent choice for external REST services or highly customized HTTP communication.

As projects grow, however, the disadvantages of a low abstraction level become more apparent. Boilerplate code, manually constructed REST URLs and the lack of SharePoint-specific helper functionality increase maintenance effort.

For SharePoint REST scenarios, the built-in SPHttpClient usually provides a better balance between transparency and developer productivity. It simplifies authentication, integrates seamlessly with SPFx and reduces implementation effort while still exposing the full SharePoint REST API.

SPHttpClient – The Native SharePoint Client for REST-Based Data Access

While the Fetch API provides a generic HTTP client for communicating with any REST service, SPHttpClient was specifically designed for SharePoint. It is an integral part of the SharePoint Framework and is available in every SPFx solution without requiring additional packages or dependencies.

SPHttpClient represents a balanced approach between low-level REST access and the convenience of a framework-aware client. Developers continue to work directly with the SharePoint REST API, while authentication, request configuration and SharePoint-specific behaviors are handled by SPFx.

For traditional CRUD operations against SharePoint lists, libraries and site resources, SPHttpClient is often considered the default choice because it combines full REST flexibility with seamless framework integration.

Architecture

Unlike the browser's native Fetch API, SPHttpClient introduces a lightweight abstraction layer that is aware of the SharePoint Framework runtime.

The architecture consists of three primary components:

  • SPFx Context
  • SPHttpClient
  • SharePoint REST API

The SPFx Context provides a preconfigured HTTP client that already contains information about the current tenant, site collection, web and authenticated user. Developers simply consume the existing client instead of creating their own HTTP implementation.

Internally, SPHttpClient still communicates with the SharePoint REST API using standard HTTP requests. The difference lies in the automatic handling of SharePoint-specific infrastructure concerns.

Automatic Authentication

One of the major advantages of SPHttpClient is its built-in authentication support.

Instead of manually configuring credentials or security headers, SPFx manages the authentication process transparently.

This includes:

  • User authentication
  • Authentication cookies
  • Request Digest generation for write operations
  • Default SharePoint headers
  • Environment-specific configuration

As a result, developers can focus on implementing business logic rather than infrastructure concerns.

Example from the Reference Project

The following example retrieves the same SharePoint list item shown in the previous chapter, this time using SPHttpClient.

public async GetWithSPHttpClient(): Promise<any[]> { const listUrl = `${this.absoluteURL}/_api/web/lists/getbytitle('${LIB}')/items?$select=id&$top=1`; const options: ISPHttpClientOptions = { headers: { "odata-version": "3.0", "Accept": "application/json;odata=verbose", "Content-Type": "application/json" } }; const response = await this.spHttpClient.get( listUrl, SPHttpClient.configurations.v1, options ); const data = await response.json(); return data; }

At first glance, this implementation appears very similar to the Fetch API. However, several important differences exist behind the scenes. SPHttpClient automatically integrates with the SharePoint Framework runtime, manages authentication and applies SharePoint-specific request processing.

Using the SPFx Context

SPHttpClient is provided through the current Web Part Context and is typically injected into service classes during construction.

constructor(private context: WebPartContext) { this.spHttpClient = context.spHttpClient; }

This allows the same client instance to be reused throughout the application, ensuring consistent configuration and authentication behavior.

Full Visibility of the REST API

Unlike higher-level libraries such as PnPjs, SPHttpClient does not hide the underlying REST API. Developers continue to construct the complete endpoint, preserving full control over:

  • REST endpoints
  • OData query parameters
  • HTTP methods
  • Request headers
  • Query options

This makes it particularly easy to transfer examples directly from Microsoft documentation into production code.

Newly introduced REST endpoints can also be used immediately without waiting for third-party libraries to support them.

Write Operations

The benefits of SPHttpClient become even more apparent when performing POST, PATCH or DELETE operations.

While the Fetch API often requires manual handling of Request Digest values, SPFx automatically manages these security requirements.

A typical POST request therefore remains compact and easy to understand.

const response = await this.context.spHttpClient.post( listUrl, SPHttpClient.configurations.v1, { headers: { "Accept": "application/json" }, body: JSON.stringify(item) } );

Required SharePoint security information is automatically included by the framework.

Advantages

Native SPFx Integration

Since SPHttpClient is part of the SharePoint Framework, no additional npm packages are required. This minimizes bundle size and reduces long-term maintenance.

Transparent Authentication

All requests execute in the context of the current user without additional authentication code.

Direct REST Access

Developers retain complete control over the SharePoint REST API while still benefiting from SPFx integration.

Minimal Runtime Overhead

SPHttpClient adds only a very thin abstraction layer. The generated HTTP requests are almost identical to those created by the native Fetch API.

Limitations

Manual REST Construction

Developers must continue to construct REST endpoints manually.

Complex OData queries can quickly become difficult to read and maintain.

_api/web/lists/getbytitle('Projects')/ items? $select=Id,Title,Author/Title& $expand=Author& $filter=Status eq 'Open'

Long endpoint definitions like this often become maintenance challenges as applications evolve.

No Fluent API

SPHttpClient intentionally exposes the REST API directly rather than providing an object-oriented programming model.

Consequently, advanced functionality such as:

  • Batch requests
  • Paging helpers
  • Recursive folder traversal
  • Complex object abstractions

must still be implemented manually.

Limited to SharePoint

SPHttpClient is designed exclusively for SharePoint REST services. Microsoft Graph is accessed through a separate client implementation, MSGraphClient.

Projects that combine SharePoint and Microsoft 365 services therefore frequently use both clients side by side.

Performance Considerations

Since SPHttpClient generates almost identical HTTP requests to the Fetch API, there is virtually no measurable performance difference between the two.

Overall execution time depends primarily on:

  • Server-side processing
  • Network latency
  • Payload size
  • Number of REST requests
  • Quality of OData queries

Significant performance improvements are usually achieved through:

  • Using $select to reduce payload size
  • Avoiding unnecessary $expand operations
  • Implementing paging
  • Using batch requests where appropriate
  • Creating indexes on large SharePoint lists

These optimizations typically have a much greater impact than changing the HTTP client itself.

Typical Use Cases

SPHttpClient is particularly well suited for:

  • Traditional SharePoint Web Parts
  • List operations
  • Document library access
  • CRUD functionality
  • Site and web information
  • SharePoint-specific REST endpoints
  • Applications without external dependencies

Whenever an application communicates exclusively with SharePoint Online, SPHttpClient is often the most straightforward and reliable solution.

Best Practices

In larger applications, data access should never be implemented directly inside React components or Web Parts.

Instead, a dedicated service layer should encapsulate all SharePoint communication.

services/ ├── ListService.ts ├── DocumentService.ts ├── UserService.ts └── SiteService.ts

This architecture offers several important advantages:

  • Improved maintainability
  • Reusable business logic
  • Centralized error handling
  • Better testability
  • Separation of presentation and data access layers

Service-oriented architectures have become the preferred approach for enterprise-scale SharePoint Framework applications.

Summary

SPHttpClient is the native client for accessing the SharePoint REST API within SharePoint Framework. It combines direct REST access with seamless authentication and tight integration into the SPFx runtime, eliminating much of the repetitive infrastructure code required by the native Fetch API.

For applications that work exclusively with SharePoint Online resources, SPHttpClient offers an excellent balance between transparency, flexibility and ease of implementation. As projects become more sophisticated—requiring extensive batching, paging or higher-level abstractions—its limitations become more apparent, making alternative approaches increasingly attractive.

In addition, SPHttpClient is limited to SharePoint-specific resources. Modern business applications frequently combine data from SharePoint, Microsoft Teams, Outlook, Planner, OneDrive and Microsoft Entra ID. For these scenarios, SharePoint Framework provides another built-in client: MSGraphClient, which enables secure access to the Microsoft Graph API and the broader Microsoft 365 ecosystem.

MSGraphClient – Accessing Microsoft Graph from SharePoint Framework Applications

As Microsoft 365 has evolved into an integrated collaboration platform, Microsoft Graph has become the central API for accessing organizational data. While the SharePoint REST API focuses exclusively on SharePoint resources, Microsoft Graph provides a unified endpoint for information stored across the entire Microsoft 365 ecosystem.

For SPFx developers, this opens up opportunities that extend far beyond traditional SharePoint development. Data from Microsoft Entra ID, Microsoft Teams, Outlook, Planner, OneDrive and SharePoint can be combined within a single application, enabling richer and more connected business solutions.

To simplify this integration, SharePoint Framework provides the MSGraphClient. The client automatically handles authentication against Microsoft Graph while integrating seamlessly with the SPFx security model.

Microsoft Graph as the Central Microsoft 365 API

Microsoft continues to position Microsoft Graph as the preferred API for Microsoft 365 development. New cloud services and capabilities are often introduced through Graph first, making it the recommended entry point for modern applications.

Unlike the SharePoint REST API, which focuses on SharePoint-specific objects, Microsoft Graph exposes resources across the entire tenant, including:

  • Users
  • Microsoft Entra ID groups
  • Microsoft Teams
  • Channels and chats
  • Planner plans and tasks
  • Outlook mail and calendars
  • OneDrive files
  • Organizational information
  • SharePoint sites and lists
  • Drive items and document libraries

Many modern intranet applications combine information from several of these services. An employee profile page, for example, may display:

  • User information from Microsoft Entra ID
  • Membership in Microsoft Teams
  • Planner assignments
  • Recent SharePoint documents
  • Upcoming Outlook meetings

Implementing such scenarios solely through the SharePoint REST API would either be impossible or require multiple independent APIs.

Architecture

Like SPHttpClient, MSGraphClient is provided by SharePoint Framework and is obtained through the current SPFx context.

The architecture consists of the following components:

  • SPFx Context
  • MSGraphClientFactory
  • Microsoft Graph
  • Microsoft 365 services

Unlike SPHttpClient, however, requests are sent to the Microsoft Graph API instead of the SharePoint REST API.

The client internally uses the official Microsoft Graph SDK and provides a fluent request builder that simplifies endpoint construction.

Authentication

One of the major advantages of MSGraphClient is that OAuth token management is completely handled by SharePoint Framework.

A typical request follows these steps:

  1. SPFx requests a Microsoft Graph client.
  2. The framework validates the required permissions.
  3. An access token is acquired automatically.
  4. The request is sent to Microsoft Graph.

The entire authentication process remains transparent to the developer, significantly reducing implementation complexity.

Permissions

Unlike SharePoint REST, Microsoft Graph requires explicit API permissions for every protected resource.

Required permissions are declared in the SPFx solution manifest:

config/package-solution.json

After deployment, these permissions must be approved by a Microsoft 365 or SharePoint administrator before the application can access the requested Graph endpoints.

This permission model provides an additional layer of security and ensures that SPFx solutions cannot automatically access tenant-wide information.

Example from the Reference Project

The reference project retrieves the same SharePoint list through Microsoft Graph rather than the SharePoint REST API.

public async GetWithGraphClient(): Promise<any[]> { const client = await this.graphClientPromise; const response = await client .api(`/sites/${this.SITEID}/lists/${this.LISTID}/items`) .version("v1.0") .select("id,lastModifiedDateTime,createdDateTime") .top(1) .get(); return response.value; }

Compared to SPHttpClient, the implementation no longer requires manually constructing a REST endpoint. Instead, requests are built using the Graph request builder.

Fluent Request Builder

MSGraphClient provides a fluent API that allows requests to be built step by step.

client .api("/users") .select("displayName,mail") .filter("accountEnabled eq true") .orderby("displayName") .top(25) .get();

This approach is considerably easier to read than manually assembling long query strings and enables developers to focus on the logical structure of the request.

Accessing SharePoint Through Microsoft Graph

Microsoft Graph now supports many SharePoint resources, including:

  • Sites
  • Lists
  • Document libraries
  • Drive items
  • Permissions
  • Columns
  • Content types
  • Modern pages

Nevertheless, Microsoft Graph does not yet cover every SharePoint feature. Several specialized APIs continue to be available only through the SharePoint REST API.

Examples include:

  • Some taxonomy operations
  • Specific Search API endpoints
  • Web property management
  • Certain administrative operations
  • Legacy publishing features

For this reason, many enterprise solutions continue to combine SharePoint REST and Microsoft Graph depending on the functionality required.

Advantages

Unified Microsoft 365 API

Microsoft Graph provides a consistent programming model across the Microsoft 365 platform, eliminating the need to work with multiple service-specific APIs.

Future-Oriented Platform

Microsoft continuously expands Microsoft Graph with new capabilities. Modern Microsoft 365 services frequently expose new functionality through Graph before it becomes available elsewhere.

Fluent Programming Model

The fluent request builder improves readability while reducing the amount of manual endpoint construction required.

Automatic Token Management

Developers do not need to implement OAuth flows manually. SPFx manages authentication transparently.

Limitations

Incomplete SharePoint Coverage

Although Microsoft Graph continues to evolve, certain SharePoint features remain available only through the SharePoint REST API.

Additional Permission Requirements

Every Microsoft Graph endpoint requires appropriate delegated permissions. These permissions must be reviewed and approved by an administrator before the application can be used.

More Complex Object Model

Microsoft Graph operates on tenant-wide identifiers rather than SharePoint-specific names.

Developers frequently work with:

  • Site IDs
  • List IDs
  • Drive IDs
  • Group IDs
  • User IDs

Understanding these relationships requires a broader knowledge of the Microsoft 365 data model.

Performance Considerations

Microsoft Graph is often perceived as being slower than SharePoint REST. In reality, performance depends largely on the specific scenario.

If an application retrieves data exclusively from a single SharePoint site, the SharePoint REST API may provide slightly more direct access.

However, when information from multiple Microsoft 365 workloads must be combined, Microsoft Graph frequently reduces the total number of HTTP requests and simplifies the overall architecture.

Typical Use Cases

MSGraphClient is particularly well suited for applications requiring tenant-wide information, such as:

  • Employee directories
  • User profile applications
  • Microsoft Teams integrations
  • Planner dashboards
  • Outlook integrations
  • OneDrive solutions
  • Viva Connections dashboards
  • Microsoft 365 portals
  • Organizational charts
  • Group management applications

Best Practices

  • Always limit the returned properties using .select().
  • Request only the permissions that are actually required.
  • Encapsulate Graph access in dedicated service classes.
  • Cache data whenever appropriate.
  • Use the v1.0 endpoint for production applications.
  • Reserve beta endpoints for testing and evaluation only.

Combining Microsoft Graph and SharePoint REST

A common misconception is that projects must choose either Microsoft Graph or the SharePoint REST API. In reality, both technologies complement each other.

A typical enterprise SPFx application might:

  • Retrieve user information through Microsoft Graph.
  • Load SharePoint documents via the SharePoint REST API.
  • Execute SharePoint Search queries.
  • Display Planner tasks using Microsoft Graph.

This hybrid architecture is now common practice in enterprise SharePoint solutions.

Summary

MSGraphClient extends SharePoint Framework beyond traditional SharePoint development by providing secure access to the complete Microsoft 365 platform. Thanks to its built-in authentication support and fluent request builder, developers can integrate information from multiple Microsoft 365 services without implementing complex OAuth flows.

For applications focused solely on SharePoint content, SPHttpClient often remains the simplest solution because it exposes the complete SharePoint REST API. As soon as data from Microsoft Teams, Outlook, Planner, OneDrive or Microsoft Entra ID is required, Microsoft Graph becomes the preferred choice.

Nevertheless, developers still need to understand the Microsoft Graph object model and permission system. Although MSGraphClient simplifies communication considerably, it does not completely abstract the underlying API. Developers seeking an even higher level of abstraction for SharePoint development often choose PnPjs, which provides a fluent, strongly typed programming model and dramatically reduces the amount of SharePoint-specific code.

PnPjs – A Modern Fluent API for SharePoint and Microsoft Graph

While SPHttpClient provides direct access to the SharePoint REST API and MSGraphClient simplifies communication with Microsoft Graph, PnPjs follows a different philosophy. Instead of exposing REST endpoints directly, it provides a modern, object-oriented abstraction layer that allows developers to work with SharePoint concepts rather than HTTP requests.

PnPjs is an open-source TypeScript library maintained by the Microsoft 365 Patterns and Practices (PnP) community. Over the years it has evolved into one of the most widely adopted libraries for SharePoint Framework development and is used extensively in enterprise projects where maintainability and developer productivity are key priorities.

Although PnPjs ultimately communicates with the SharePoint REST API (and optionally Microsoft Graph), developers rarely interact with REST endpoints directly. Instead, they work with fluent, strongly typed APIs that greatly improve readability and reduce repetitive code.

Architecture

PnPjs is not a standalone runtime environment. It is a TypeScript library that builds upon the authentication and HTTP infrastructure provided by SharePoint Framework.

A typical architecture consists of:

  • SPFx Context
  • PnPjs
  • SharePoint REST API
  • Optional Microsoft Graph modules

Internally, PnPjs still generates REST requests. The difference is that developers interact with business-oriented objects such as sites, lists, libraries, folders and users instead of manually constructing REST URLs.

Initialization

Before PnPjs can be used, it must be initialized with the current SPFx context. This is typically performed once during the Web Part initialization or inside a shared service layer.

import { spfi, SPFI } from "@pnp/sp"; import { SPFx } from "@pnp/sp/presets/all"; private sp: SPFI; public onInit(): Promise<void> { this.sp = spfi().using(SPFx(this.context)); return Promise.resolve(); }

Once initialized, the configured SPFI instance can be reused throughout the application.

Accessing SharePoint Lists

The reference project demonstrates the same list query shown in the previous chapters, this time implemented with PnPjs.

const items = await this.sp.web .lists .getByTitle(LIB) .items .select("Id") .top(1)();

Compared to SPHttpClient, the code immediately becomes more expressive. Instead of navigating through a manually constructed REST endpoint, the fluent API reflects the logical SharePoint object hierarchy:

  • Web
  • Lists
  • List
  • Items
  • Selected fields

This significantly improves readability, particularly for developers who are less familiar with SharePoint REST syntax.

The Fluent API

One of the defining characteristics of PnPjs is its fluent programming model. Instead of concatenating REST URLs and OData parameters, functionality is expressed through method chaining.

const items = await this.sp.web .lists .getByTitle("Projects") .items .select( "Id", "Title", "Status", "Author/Title" ) .expand("Author") .filter("Status eq 'Open'") .orderBy("Title") .top(100)();

Although this request is functionally identical to its REST counterpart, the resulting code is considerably easier to read, extend and maintain.

Strong Typing

Since PnPjs is built for TypeScript, it integrates naturally with strongly typed application models.

interface IProject { Id: number; Title: string; Status: string; } const items: IProject[] = await this.sp.web .lists .getByTitle("Projects") .items();

Strong typing improves IntelliSense support, enables compile-time validation and significantly reduces runtime errors.

This becomes increasingly valuable in large enterprise applications with many developers working on the same code base.

Batch Processing

One of the most powerful features of PnPjs is its native support for batching.

Instead of executing several independent HTTP requests, multiple operations can be combined into a single network request.

const [batchedSP, execute] = this.sp.batched(); batchedSP.web.lists.getByTitle("Projects").items(); batchedSP.web.lists.getByTitle("Customers").items(); await execute();

Especially in dashboard scenarios, batching can significantly reduce latency by minimizing the number of HTTP roundtrips.

Paging Support

Loading thousands of SharePoint items at once is rarely recommended. PnPjs provides built-in paging functionality that greatly simplifies working with large lists.

const page = await this.sp.web .lists .getByTitle("Projects") .items .top(100) .getPaged();

Skip tokens and page navigation are managed internally, eliminating the need for custom paging logic.

Additional SharePoint Functionality

Beyond basic CRUD operations, PnPjs exposes a comprehensive set of SharePoint capabilities, including:

  • Document libraries
  • Files and folders
  • Permissions
  • Users and groups
  • Navigation
  • Search
  • Managed metadata
  • Content types
  • Site Scripts
  • Site Designs
  • Recycle Bin
  • Version history
  • Webhooks

This broad functionality allows developers to use a consistent programming model throughout an entire SharePoint solution.

Microsoft Graph Integration

Modern versions of PnPjs are no longer limited to SharePoint.

Optional modules also provide convenient access to Microsoft Graph, allowing developers to work with SharePoint and Microsoft 365 resources through a consistent development model.

This reduces the number of libraries required in many enterprise applications and promotes a unified coding style across projects.

Advantages

Excellent Readability

The fluent API closely mirrors SharePoint's logical object hierarchy, making code significantly easier to understand than manually constructed REST URLs.

Reduced Development Effort

Many repetitive implementation tasks are handled by the library, including:

  • Authentication integration
  • Paging
  • Batching
  • Configuration
  • Strong typing
  • Request construction

Excellent Community Support

As part of the Microsoft 365 Patterns and Practices initiative, PnPjs benefits from extensive documentation, community contributions and a large collection of real-world examples.

Improved Maintainability

Extending an existing query often requires only adding another fluent method, rather than rewriting complex REST URLs.

Limitations

Additional Dependency

Unlike SPHttpClient, PnPjs is not included with SharePoint Framework. Projects must install and maintain the library as an external npm package.

Major version upgrades may require code changes as APIs evolve.

Less Visibility into Generated Requests

Since REST requests are generated internally, developers sometimes need to inspect browser developer tools when troubleshooting complex issues.

Learning Curve

Although the fluent API is intuitive, developers familiar only with raw REST may require some time to become comfortable with the extensive feature set.

Performance Considerations

A common assumption is that PnPjs is slower because it introduces an additional abstraction layer.

In practice, the overhead is negligible.

Overall performance is primarily influenced by:

  • Network latency
  • Server processing time
  • Payload size
  • Number of HTTP requests

In many cases, built-in batching and paging actually produce better overall performance than manually implemented REST solutions.

Typical Use Cases

PnPjs is particularly well suited for:

  • Large enterprise applications
  • Corporate intranet portals
  • Complex SharePoint Web Parts
  • Dashboard solutions
  • Projects with multiple data services
  • Applications containing extensive SharePoint business logic
  • Long-term maintainable SPFx solutions
  • Development teams with multiple contributors

As project size and complexity increase, the benefits of PnPjs become more significant.

Best Practices

  • Initialize PnPjs only once during application startup.
  • Centralize data access inside dedicated service classes.
  • Separate presentation logic from business logic.
  • Use strongly typed interfaces consistently.
  • Prefer batching whenever multiple independent queries are required.
  • Always limit returned fields using select().
  • Use paging for large lists.
  • Encapsulate frequently used queries into reusable methods.

Summary

PnPjs has become one of the most productive approaches for SharePoint data access within modern SPFx applications. Its fluent programming model, strong TypeScript integration and comprehensive feature set significantly reduce development effort while improving code readability and maintainability.

Features such as batching, paging, reusable query construction and SharePoint object abstractions make PnPjs particularly attractive for medium-sized and enterprise-scale solutions.

Although it introduces an additional dependency compared to SPHttpClient, the benefits generally outweigh the costs in larger applications. Consequently, many organizations have standardized on PnPjs as their primary SharePoint data access layer while using MSGraphClient—or the PnPjs Graph modules—for Microsoft 365 resources.

The final section of this article compares all four approaches, discusses architectural best practices and provides practical guidance for selecting the most appropriate data access strategy for modern SharePoint Framework solutions.

Comparison of Data Access Options and Best Practices

The four technologies presented throughout this article address different requirements within SharePoint Framework applications. Rather than competing with each other, they complement one another and are often used together in modern enterprise solutions.

Choosing the appropriate technology should be based on architectural requirements instead of personal preference. Factors such as the target system, project size, maintainability requirements and long-term support strategy all influence this decision.

Selecting the Appropriate Technology

Target System

The first decision criterion is the source of the required data.

If the application works exclusively with SharePoint lists, document libraries and site resources, either SPHttpClient or PnPjs will typically be the most suitable choice.

Whenever data originates from Microsoft Teams, Outlook, Planner, Microsoft Entra ID or other Microsoft 365 services, Microsoft Graph becomes the preferred API.

External business systems, custom REST services and Azure Functions are usually accessed through the browser's native Fetch API.

Project Size

Small projects containing only a handful of REST calls often benefit from the simplicity of SPHttpClient.

As the number of services, business objects and SharePoint queries grows, maintaining manually constructed REST endpoints becomes increasingly difficult. In larger projects, PnPjs typically offers a significant productivity advantage due to its higher level of abstraction.

Maintainability

Long-term enterprise applications should prioritize maintainability over implementation speed.

Long REST URLs containing multiple OData parameters become difficult to review, extend and debug over time. Fluent APIs reduce this complexity and make business intent much easier to understand.

A consistent data access layer also improves onboarding for new developers and reduces the risk of introducing inconsistencies across larger teams.

Performance

From a performance perspective, the choice of client library usually has only a minor impact.

Much more significant factors include:

  • Number of HTTP requests
  • Payload size
  • Network latency
  • Query optimization
  • Use of $select
  • Paging
  • Batch requests
  • Indexed SharePoint lists

Optimizing requests typically delivers much greater performance gains than replacing one client library with another.

Combining Multiple Technologies

Modern SharePoint Framework solutions rarely rely on a single data access technology.

A typical enterprise application might retrieve:

  • News articles from SharePoint lists.
  • User information from Microsoft Graph.
  • Project metrics from an Azure Function.
  • Configuration data from a custom REST service.

A layered architecture helps separate responsibilities and keeps each service focused on a single data source.

React Web Part │ ├───────────────┐ │ │ ▼ ▼ SharePointService GraphService │ │ ▼ ▼ PnPjs MSGraphClient │ │ └──────┬────────┘ │ ExternalApiService │ Fetch API

With this approach, presentation components remain completely independent of the underlying communication technology.

Recommended Solution Architecture

Regardless of the selected client library, data access should be isolated from the presentation layer.

A commonly used project structure resembles the following:

src │ ├── components │ ├── services │ ├── ListService.ts │ ├── DocumentService.ts │ ├── UserService.ts │ ├── GraphService.ts │ └── ApiService.ts │ ├── models │ ├── hooks │ └── utils

This architecture provides several important benefits:

  • Reusable business logic
  • Centralized error handling
  • Improved testability
  • Consistent authentication
  • Clear separation of concerns
  • Improved maintainability

Service-oriented architectures have become the de facto standard for enterprise SharePoint Framework applications.

General Best Practices

Retrieve Only Required Fields

Every query should limit the returned data using $select or .select().

Reducing payload size improves:

  • Response times
  • Network utilization
  • Memory consumption
  • Rendering performance

Use Paging

Large SharePoint lists should never be loaded completely. Paging significantly reduces network traffic and improves user experience.

Use Batch Requests

Whenever multiple independent requests target the same SharePoint site, batching should be considered to minimize HTTP roundtrips.

Apply Strong Typing

TypeScript interfaces improve code quality, simplify maintenance and enable early detection of implementation errors during development.

Centralize Data Access

Web Parts and React components should never communicate directly with SharePoint or Microsoft Graph.

Dedicated service classes provide a cleaner architecture and make future changes significantly easier.

Which Technology Fits Which Scenario?

Fetch API

The native Fetch API is ideal for communicating with external REST services, Azure Functions and custom enterprise APIs. Although it can also access SharePoint REST, the required boilerplate code makes it less attractive for larger SharePoint applications.

SPHttpClient

SPHttpClient is an excellent choice for traditional SharePoint applications that require direct access to the SharePoint REST API without introducing additional dependencies.

MSGraphClient

Applications that combine information from multiple Microsoft 365 services should rely on Microsoft Graph. The built-in client simplifies authentication while providing secure access to tenant-wide resources.

PnPjs

For medium-sized and enterprise-scale SharePoint Framework solutions, PnPjs typically offers the highest level of developer productivity, readability and maintainability.

Conclusion

SharePoint Framework offers several mature and well-established approaches for accessing data within Microsoft 365. Each technology addresses a different set of requirements and contributes unique strengths to the development process.

The Fetch API provides maximum flexibility and is particularly well suited for communicating with external REST services or specialized HTTP endpoints. For SharePoint-specific development, however, it often results in unnecessary boilerplate code.

SPHttpClient extends this approach with seamless SPFx integration, automatic authentication and direct access to the SharePoint REST API. It remains an excellent choice for many traditional SharePoint applications.

MSGraphClient enables applications to consume data from the entire Microsoft 365 ecosystem. User profiles, Microsoft Teams, Outlook, Planner and SharePoint resources can all be integrated through a single API while maintaining a secure authentication model.

PnPjs offers the highest abstraction level and greatly improves developer productivity through its fluent API, strong typing, batching capabilities and reusable programming model. For complex enterprise applications, it has become the preferred choice for SharePoint data access.

There is no universally "best" solution. Modern SPFx applications often combine multiple approaches and use each technology where it provides the greatest benefit. This flexibility is one of the key strengths of the SharePoint Framework and enables developers to build scalable, high-performance and maintainable business applications.

Still not sure what to use? Check out the decision matrix 💡

Which API should I choose?

Comparison of SharePoint Data Access Options

Criteria Fetch API SPHttpClient MSGraphClient PnPjs
Included in SPFx Browser API ✖ (npm package)
Access to SharePoint REST Limited (via Graph)
Access to Microsoft Graph Manual authentication ✔ (Graph modules)
Access to External REST APIs Limited Via Fetch/Extensions
Automatic Authentication Partial
Fluent API
Strong Typing Manual Manual Good Excellent
Batch Support Manual Manual Limited
Paging Support Manual Manual Limited
Readability of Complex Queries Moderate Moderate Good Excellent
Additional Dependencies None None None Yes
Learning Curve Low Low Moderate Moderate
Suitable for Small Projects ✔✔
Suitable for Enterprise Projects Limited Good Good Excellent
Microsoft 365 Integration Limited SharePoint only Excellent Excellent
Recommended Primary Use External REST APIs SharePoint REST Microsoft 365 Services Enterprise SharePoint Solutions

Final Thoughts

The technologies discussed in this article should not be viewed as competing alternatives but as complementary building blocks within a modern SharePoint architecture.

SPHttpClient and PnPjs are ideal for SharePoint-centric scenarios, while MSGraphClient extends applications into the broader Microsoft 365 ecosystem. The Fetch API remains indispensable whenever external REST services must be integrated.

For newly developed SharePoint Framework solutions, a layered architecture combining PnPjs for SharePoint data, MSGraphClient (or the PnPjs Graph modules) for Microsoft 365 resources and the native Fetch API for external services has proven to be a robust, scalable and future-proof approach.

By selecting the appropriate technology for each scenario and applying consistent architectural principles, developers can build SharePoint Framework applications that are performant, maintainable and well positioned for the continuous evolution of the Microsoft 365 platform.

Reference list

Kommentare

Beliebte Posts aus diesem Blog

Power Automate: Abrufen von SharePoint Listenelementen mit ODATA-Filter

SPFx: Be prepared for the Content Security Policy (CSP) in SharePoint Online

SharePoint Online: Optimale Bildgrößen für Seiten (Teil 1)