Simplified SharePoint HTTP Client

raw JSON →
3.0.0 verified Thu Apr 23 auth: no javascript

sp-request is a Node.js-specific HTTP client designed for simplified interaction with SharePoint REST APIs, supporting SharePoint 2013, SharePoint Online, and later versions. It is currently at version 3.0.0. The library abstracts SharePoint authentication using `node-sp-auth` and leverages the `got` library for making HTTP requests, providing a consistent API similar to `got`. This combination allows developers to send REST queries with various authentication options without manually managing authentication flows or request digests. It is strictly for server-side (Node.js) usage and does not support browser environments. While a specific release cadence isn't detailed, the presence of a 3.x upgrade guide indicates ongoing development. Key differentiators include its focus on Node.js, seamless integration with `node-sp-auth` for diverse authentication strategies, and a `got`-like request syntax.

error Error: read ECONNRESET / 401 Unauthorized / Ohhh, something went wrong...
cause A generic network issue, incorrect SharePoint URL, or failed authentication due to invalid credentials, incorrect tenant configuration, or misconfigured `node-sp-auth` options.
fix
Double-check all credentialOptions (siteUrl, username, password, client ID/secret), verify network connectivity to the SharePoint instance, and ensure the SharePoint URL is correct and accessible from the Node.js host.
error Error: Request failed with status code 404 (Not Found)
cause The requested SharePoint resource (e.g., list, file, web, API endpoint) does not exist at the specified URL path, or the authenticated user lacks permissions to see it.
fix
Verify the SharePoint REST API endpoint and object identifiers (e.g., list title, item ID) are accurate. Confirm the authenticated user has appropriate permissions to the resource.
error Response code 500 (Internal Server Error)
cause An unhandled exception occurred on the SharePoint server during request processing, possibly due to an invalid request body, headers (like `X-RequestDigest`), or server-side custom code issues.
fix
Review the SharePoint ULS logs (for on-prem) or SharePoint diagnostic logs (for Online) to get more details about the server error. Ensure the request body, headers, and API calls conform to SharePoint's expectations. Regenerate X-RequestDigest if applicable.
breaking Upgrading from version 2.x to 3.x involves breaking changes. Developers should consult the `Upgrade guide` mentioned in the README for specific migration steps and API adjustments.
fix Refer to the official `sp-request` upgrade guide for detailed instructions on migrating your codebase from 2.x to 3.x.
gotcha This module is strictly designed for Node.js environments and does not work in browsers. Attempting to use it in a browser context will result in errors.
fix For browser-based SharePoint interactions, consider using `sp-rest-proxy` in conjunction with `PnPjs` or similar client-side libraries. `sp-request` is server-side only.
gotcha `sp-request` relies on `node-sp-auth` for all authentication. Users must provide valid `credentialOptions` as defined by `node-sp-auth`, which can be complex depending on the SharePoint environment (Online, On-Prem, ADFS, App-Only, etc.). Incorrect options will lead to authentication failures.
fix Carefully review the `node-sp-auth` documentation (https://github.com/s-KaiNet/node-sp-auth#params) to ensure `credentialOptions` are correctly configured for your specific SharePoint environment and desired authentication method.
gotcha By default, `sp-request` sets `rejectUnauthorized: false` for the underlying `got` requests. While this can simplify development with self-signed certificates, it poses a security risk in production environments as it disables SSL certificate validation. This could make your application vulnerable to man-in-the-middle attacks.
fix For production deployments, ensure `rejectUnauthorized` is explicitly set to `true` (if possible for your environment) or that proper certificate trust is established. Be aware that this default simplifies initial setup but should be addressed for security.
npm install sp-request
yarn add sp-request
pnpm add sp-request

Demonstrates installation, creating an authenticated `sp-request` instance, and performing a basic GET request to retrieve a SharePoint list by title using environment variables for credentials.

import * as sprequest from 'sp-request';
import * as process from 'process';

// In a real application, retrieve these securely, e.g., from environment variables or a config service.
// This example uses dummy values for demonstration. For specific auth types and options,
// refer to the `node-sp-auth` documentation (https://github.com/s-KaiNet/node-sp-auth#params).
const credentialOptions = {
  // Example for SharePoint Online App-Only via Client ID/Secret:
  // clientId: process.env.SP_CLIENT_ID ?? 'your-client-id',
  // clientSecret: process.env.SP_CLIENT_SECRET ?? 'your-client-secret',

  // Example for SharePoint Online with ADFS/Forms auth via username/password:
  username: process.env.SP_USERNAME ?? 'user@yourtenant.onmicrosoft.com',
  password: process.env.SP_PASSWORD ?? 'YourSecurePassword123!',
  siteUrl: process.env.SP_SITE_URL ?? 'https://yourtenant.sharepoint.com/sites/dev' // Your SharePoint site URL
};

// Create an authenticated sprequest instance
const spr = sprequest.create(credentialOptions);

// Example: Get a SharePoint list by its title
const listTitle = 'Announcements'; // Replace with an actual list title in your site
const sharePointSiteUrl = credentialOptions.siteUrl; 

spr.get(`${sharePointSiteUrl}/_api/web/lists/GetByTitle('${listTitle}')`)
  .then(response => {
    if (response.body && response.body.d) {
      console.log(`Successfully retrieved list: '${listTitle}'`);
      console.log('List Id: ' + response.body.d.Id);
      console.log('List Title: ' + response.body.d.Title);
    } else {
      console.log('Unexpected response structure:', response.body);
    }
  })
  .catch(err => {
    console.error(`Failed to retrieve list '${listTitle}':`);
    if (err.response) {
      console.error(`Status Code: ${err.response.statusCode}`);
      console.error(`Response Body: ${JSON.stringify(err.response.body, null, 2)}`);
    } else {
      console.error(err);
    }
  });