Here is an English text for your technical blog:


Fetching SharePoint List Items Using SPFx HttpClient

When working with SharePoint Framework (SPFx), retrieving data from a SharePoint list is a common requirement. The following TypeScript function demonstrates how to fetch list items using the SPFx HttpClient and transform them into a structured object.

How It Works

  1. Construct the API URL: The function dynamically builds the REST API endpoint based on the SharePoint site URL and the list title.
  2. Send an HTTP GET Request: It uses the HttpClient to fetch list data in JSON format.
  3. Process the Response: The retrieved data is mapped into a structured object containing essential fields like id, title, created, and modified.
  4. Handle Errors: If the request fails, the function catches the error and logs it.

Code Implementation

import { HttpClient, HttpClientResponse } from '@microsoft/sp-http';

/**
 * Fetches items from a SharePoint list and transforms them into a structured object.
 *
 * @param {any} context - The SharePoint context to access API endpoints.
 * @param {string} listTitle - The title of the SharePoint list to fetch data from.
 * @returns {Promise<any[]>} A promise that resolves to a structured list of items.
 */
export async function FetchListItems(context: any, listTitle: string): Promise<any[]> {
    try {
        // Construct the API URL based on the site URL and list title
        const siteUrl = context.pageContext.web.absoluteUrl;
        const apiUrl = `${siteUrl}/_api/web/lists/getbytitle('${listTitle}')/items`;

        console.log("Fetching API URL:", apiUrl);

        // Make the HTTP GET request using HttpClient
        const response: HttpClientResponse = await context.httpClient.get(apiUrl, HttpClient.configurations.v1, {
            headers: {
                'Accept': 'application/json;odata=nometadata',
                'Content-Type': 'application/json;odata=nometadata'
            }
        });

        console.log("Response Status:", response.status);

        // Check if the response is successful
        if (!response.ok) {
            throw new Error(`Failed to fetch list items: ${response.statusText}`);
        }

        // Parse the JSON response
        const data = await response.json();
        console.log("Raw Data:", data);

        // Transform the list items into a structured object
        const items = data.value.map((item: any) => ({
            id: item.Id,
            title: item.Title,
            created: item.Created,
            modified: item.Modified
        }));

        console.log("Processed Items:", items);
        return items;
    } catch (error) {
        console.error("Error fetching list items:", error);
        return [];
    }
}

Example Usage

const listItems = await FetchListItems(context, "Documents");
console.log(listItems);

Conclusion

This function provides a simple yet powerful way to retrieve and structure SharePoint list items using SPFx.

Edvaldo Guimrães Filho Avatar

Published by