Written by

Jayakumar Balasubramaniam

Share

  

Category

see all categories
intranet as a service

How to work with List Items in SPFx using REST API – Part 1 (Retrieve List data)

SharePoint Framework is a powerful client side development used to develop SharePoint apps with full support of maximum of other Javascript frameworks like Angular, React, Knockout…

Generally in order to access the SharePoint REST API call request we would be in need of authentication parameters like access tokens, Request Digest value, etc..

But in SPFx we no need to worry about that because SPFx take care of that authentication by using the current user’s context in SPHttpClient class, the only thing we need to do is to pass the Url with some headers and post body.

We can accomplish all the list operations by using  the “Get” and “Post” methods with the below options

url: SP Rest API url to access your data

configuration: SPHttpClientConfiguration which uses predefined objects required for SPHttpClient class

options: ISPHttpClientOptions which is optional in GET request and required in POST request, with this parameter we can pass custom headers and payload to post.

Let’s see real examples to retrieve data from list with the help of spHttpClientClass. Below are the basic request Urls required to read list data.

GetListItemCount: To get the count of the items in a list

“/_api/web/Lists/GetByTitle('YourListTitle')/ItemCount”

GetListItems: To get the count of the items in a list

/_api/web/Lists/GetByTitle('YourListTitle')/items$select=Attachments,AttachmentFiles,*&$expand=AttachmentFiles”

Here OData query is used to read the attachment files in list in a single call while reading the list items.

GetListItemsWithCAMLQuery: To get the count of the items in a list

/_api/web/Lists/GetByTitle('YourListTitle')/GetItems$select=Attachments,AttachmentFiles,*&$expand=AttachmentFiles”

GetListItemByItemId: To get the count of the items in a list

/_api/web/Lists/GetByTitle('YourListTitle')/items(YourItemID)$select=Attachments,AttachmentFiles,*&$expand=AttachmentFiles”

First step is to import the below modules in your typescript file from the package “@microsoft/sp-http” like below,

import {

    SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions} from

'@microsoft/sp-http';

Next, to get the web absolute url where the SPFx app is running

let currentWebUrl = this.context.pageContext.web.absoluteUrl;

1. Get Items Count in a list (Get operation is used)

let requestUrl =

currentWebUrl.concat(“/_api/web/Lists/GetByTitle('YourListTitle')/ItemCount”)

this.context.spHttpClient.get(requestUrl, SPHttpClient.configurations.v1)

.then((response: SPHttpClientResponse) => {

if (response.ok) {

response.json().then((responseJSON) => {

if (responseJSON!=null && responseJSON.value!=null){

 let itemCount:number = parseInt(responseJSON.value.toString());

                        }

                  });

         

   }

      });

      Finally the highlighted line yields you the items count in a list.

2. Get all Items in a list without using caml query (Get operation is used)

let requestUrl =

currentWebUrl.concat(“/_api/web/Lists/GetByTitle('YourListTitle')/items$sel

ect=Attachments,AttachmentFiles,*&$expand=AttachmentFiles”)

this.context.spHttpClient.get(requestUrl, SPHttpClient.configurations.v1)

   .then((response: SPHttpClientResponse) => {

         if (response.ok) {

               response.json().then((responseJSON) => {

                     if (responseJSON!=null && responseJSON.value!=null){

                           let items:any[] = responseJSON.value;

                     }

               });

         }

Code Snippet

let camlQueryPayLoad: any = {

            query: {

                __metadata: { type: “SP.CamlQuery” },

                ViewXml: query

            }

        };

   });

Finally the highlighted line give you the items in a list, but be sure your list doesn’t have more than 5000 items, because SharePoint has limitation that we cannot read more than 5000 items at a time to improve performance. In case if you have more than 5000 items in a list you must apply caml query to get the filtered list items. (Note: you have to ensure that caml query also shouldn’t return more than 5000 items) Below is sample for that also.

3.Get all Items in a list WITH caml query (Post operation is used)

There are two difference between the request with caml query and without caml query

  1. We will be using POST method to use caml query in request body because if CAML query string length is exceeds we cannot directly pass it in ODATA url since there is some url length restriction is available hence we are posting our caml query in request body.
  2. A slight change in the URL

With Query: api/web/Lists/GetByTitle('YourListTitle')/GetItems

Without Query: api/web/Lists/GetByTitle('YourListTitle')/items

In SPFx everything you post in Request Body should have metadata about the body contents same for caml query too as below

Code Snippet

let camlQueryPayLoad: any = {

            query: {

                __metadata: { type: “SP.CamlQuery” },

                ViewXml: query

            }

        };

      let spOpts = {               

                body: JSON.stringify(camlQueryPayLoad)

            };

this.context.spHttpClient.post(requestUrl, SPHttpClient.configurations.v1, spOpts)

   .then((response: SPHttpClientResponse) => {

         if (response.ok) {

               response.json().then((responseJSON) => {

                     if (responseJSON!=null && responseJSON.value!=null){

                           let items:any[] = responseJSON.value;

                     }

               });

         }

   });

4. Get list item by itemId (Get operation is used)

let requestUrl =

currentWebUrl.concat(“/_api/web/Lists/GetByTitle('YourListTitle')/items

(YourItemID)$select=Attachments,AttachmentFiles,*&$expand=AttachmentFiles”)

this.context.spHttpClient.get(requestUrl, SPHttpClient.configurations.v1)

      .then((response: SPHttpClientResponse) => {

            if (response.ok) {

                  response.json().then((responseJSON) => {

                  if (responseJSON!=null){

                        let items:any = responseJSON;

                        }

                  });

            }

      });

If you are working with SPFx for the first time please make use of browser console for better understanding, console.log(responseJSON)

Look forward for our next part of this blog to know about item add/update/delete from a list.

Jayakumar Balasubramaniam

Written by Jayakumar Balasubramaniam

A technology evangelist working on Microsoft 365, SharePoint & Azure. Gets my hands dirty with latest and greatest of SharePoint, Azure & front-end frameworks. Currently working with “Hubfly – A unified digital workplace” as a Product Engineer. Getting in to the depth of the domain & technology, with my eyes for perfection, ensures that the product releases go right every time.