ServiceNow HTTP Request Client
sn-http-request is a specialized JavaScript HTTP client designed specifically for interacting with ServiceNow instances. It aims to simplify common HTTP operations within the ServiceNow ecosystem by providing features such as automatic user token refresh, asynchronous request queuing, request cancellation, request/response interceptors, and efficient request batching (defaulting to batch requests within a 50ms window). The current stable version is 24.0.3, though its public release cadence might be slower as it's primarily intended for internal ServiceNow development. Its key differentiators compared to generic HTTP clients like Axios or the Fetch API include built-in XSRF token handling and request compression, making it optimized for ServiceNow's API landscape and reducing boilerplate for common tasks in that environment.
Common errors
-
Error sending HTTP request
cause This error often indicates a timeout before the server sends a response, or an issue connecting to the remote service.fixIncrease the `timeout` setting in your request configuration or `snHttpFactory` options. Verify network connectivity to the ServiceNow instance and check the instance's availability. Ensure the target API endpoint is correct and accessible. For server-side issues, check ServiceNow instance logs. -
The HTTP request is unauthorized with client authentication scheme 'Digest'.
cause This specific error message (or similar 'unauthorized' errors like 401 or 403 Forbidden) typically means the provided credentials or authentication token are invalid or lack the necessary permissions for the requested operation.fixVerify that the `username` and `password` provided to `snHttpFactory` are correct for your ServiceNow instance and have the 'itil' role or other required permissions for the target API. Ensure any `xsrfToken` is correctly configured and still valid. Review ServiceNow security rules and API access policies. -
HTTP status code 404: Not Found
cause The requested API endpoint or resource could not be found on the ServiceNow instance.fixDouble-check the `baseURL` configured in `snHttpFactory` and the relative paths provided to `get`, `post`, etc. Ensure the ServiceNow API endpoint exists and is correctly spelled. Verify that the user account has access to the table or API being queried.
Warnings
- gotcha The `sn-http-request` library is primarily intended for internal ServiceNow development use. While publicly available, its release cadence and feature prioritization may differ from general-purpose HTTP clients, potentially leading to slower updates or fixes for external use cases.
- breaking As with any API client, changes to the underlying ServiceNow REST API (e.g., changes to endpoint paths, required parameters, response field names, or authentication methods) can cause breaking changes to applications using `sn-http-request`.
- gotcha By default, `sn-http-request` clients will batch HTTP requests made within a 50ms window. While beneficial for performance in some scenarios, this can lead to unexpected delays or behavior if immediate, unbatched requests are expected.
Install
-
npm install sn-http-request -
yarn add sn-http-request -
pnpm add sn-http-request
Imports
- snHttpFactory
const snHttpFactory = require('sn-http-request').snHttpFactory;import { snHttpFactory } from 'sn-http-request'; - snHttpFactory (CJS)
const snHttpFactory = require('sn-http-request'); // Would import the entire module, not the factory function directlyconst { snHttpFactory } = require('sn-http-request'); - SnHttpClientInstance
import type { SnHttpClientInstance } from 'sn-http-request';
Quickstart
import { snHttpFactory } from 'sn-http-request';
const SN_INSTANCE_URL = process.env.SN_INSTANCE_URL ?? 'https://yourinstance.service-now.com';
const SN_USERNAME = process.env.SN_USERNAME ?? 'admin';
const SN_PASSWORD = process.env.SN_PASSWORD ?? 'password';
const snHttp = snHttpFactory({
baseURL: SN_INSTANCE_URL + '/api/now/table/',
auth: {
username: SN_USERNAME,
password: SN_PASSWORD,
},
// Max 2 concurrent requests by default, set to 5 for demonstration
maxConcurrent: 5,
// Disable batching for this client instance for immediate requests
batching: false,
// Example interceptor to log requests
interceptors: {
request: [
(config) => {
console.log(`[Request Interceptor] Making ${config.method?.toUpperCase()} request to ${config.url}`);
return config;
},
],
response: [
(response) => {
console.log(`[Response Interceptor] Received ${response.status} from ${response.config.url}`);
return response;
},
],
},
});
async function fetchIncident(sysId: string) {
try {
console.log(`
Fetching incident with sys_id: ${sysId}...`);
const response = await snHttp.get(`incident/${sysId}`);
console.log('Incident Data:', JSON.stringify(response.data, null, 2));
} catch (error: any) {
console.error('Error fetching incident:', error.message || error);
if (error.response) {
console.error('Response status:', error.response.status);
console.error('Response data:', error.response.data);
}
}
}
// Example: Replace with a valid incident sys_id from your ServiceNow instance
fetchIncident('a_valid_incident_sys_id_here');
// Example: Creating a new incident (requires POST permissions and appropriate payload)
async function createIncident() {
try {
console.log('\nCreating a new incident...');
const newIncidentData = {
short_description: 'Test incident from sn-http-request client',
impact: '3',
urgency: '3',
};
const response = await snHttp.post('incident', { data: newIncidentData });
console.log('New Incident Created:', JSON.stringify(response.data, null, 2));
} catch (error: any) {
console.error('Error creating incident:', error.message || error);
if (error.response) {
console.error('Response status:', error.response.status);
console.error('Response data:', error.response.data);
}
}
}
// Uncomment to run the create incident example
// createIncident();