SharePoint REST Calls With SPHttpClient Class In SPFx Webparts

Introduction

Let us look at the usage of sphttpclient in SPFx solutions for making REST calls. To access the required information on SharePoint sites, traditional REST API calls are made previously with JavaScript or jQuery. In the SharePoint Framework solutions, there is an option of making calls using predefined classes. These are the base communication layer used in the SPFx solutions for accessing SharePoint data.

SPHttpClient Class 

HttpClient is the class which has basic features to perform REST calls. It can be used to perform REST calls for non-SharePoint services.

SPHttpClient is a subclass which inherits the functionalities from HttpClient, and is used to perform REST calls for SharePoint specific services. This will have default headers and digest information required for get or post calls.

SPHttpClient has the methods and properties. The methods are beginBatch, fetch, get, post, and getWebUrlFromRequestUrl.

Let us focus on retrieving the SharePoint list information using SPHttpClient class. Make sure the latest web part generator packages are available on the environment, before you start creating the SPFx project.

For getting the information, get method is used. This indirectly calls the fetch method. The fetch method will have the same  functionalities same as get method. The required parameters are,

  • URL (string)
  • Configurations (SPHttpClientConfiguration) - Used to set the default headers and version numbers. There is only one value available at this stage (v1).
  • Options (ISPHttpClientOptions) - optional parameter, for setting the web URL explicitly.

The get method is triggered using the context with the help of SPHttpClient. URL and configurations are passed as parameters. The URL can be constructed with the help of context available on the component.

The response will be in the type SPHttpClientResponse. JSON data will then be extracted from the response using the methods available.

The required packages to be imported on the webpart file.
  1. import { SPHttpClient, SPHttpClientResponse, SPHttpClientConfiguration } from '@microsoft/sp-http';  

The below code snippet shows retrieval of SharePoint list items.

  1. this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/lists/GetByTitle('TestList')/items`,  
  2.       SPHttpClient.configurations.v1)  
  3.       .then((response: SPHttpClientResponse) => {  
  4.         response.json().then((responseJSON: any) => {  
  5.           console.log(responseJSON);  
  6.         });  
  7.       });  
Note

"this.context" is used to get the context on the web part TypeScript file. Alternatively, this can be changed in other framework component files.

Summary

Thus, you have learned about getting data from SharePoint lists using SPHttpClient class and methods.