Skip to Content

REST API Client Utilities

Reusable functions for making REST API calls to external systems with error handling and authentication.

#rest-api #integration #http #external-api #utilities #webhook #authentication

Script Code

JavaScript
1var RestAPIClient = Class.create();
2RestAPIClient.prototype = {
3
4  /**
5   * Make a GET request to external API
6   *
7   * @param {string} endpoint - Full API endpoint URL
8   * @param {object} options - {headers, params, timeout}
9   * @returns {object} {success: boolean, status: number, data: object, error: string}
10   */
11  get: function(endpoint, options) {
12    return this._makeRequest('GET', endpoint, null, options);
13  },
14
15  /**
16   * Make a POST request to external API
17   *
18   * @param {string} endpoint - Full API endpoint URL
19   * @param {object} data - Request body data
20   * @param {object} options - {headers, params, timeout}
21   * @returns {object} {success: boolean, status: number, data: object, error: string}
22   */
23  post: function(endpoint, data, options) {
24    return this._makeRequest('POST', endpoint, data, options);
25  },
26
27  /**
28   * Make a PUT request to external API
29   *
30   * @param {string} endpoint - Full API endpoint URL
31   * @param {object} data - Request body data
32   * @param {object} options - {headers, params, timeout}
33   * @returns {object} {success: boolean, status: number, data: object, error: string}
34   */
35  put: function(endpoint, data, options) {
36    return this._makeRequest('PUT', endpoint, data, options);
37  },
38
39  /**
40   * Make a DELETE request to external API
41   *
42   * @param {string} endpoint - Full API endpoint URL
43   * @param {object} options - {headers, params, timeout}
44   * @returns {object} {success: boolean, status: number, data: object, error: string}
45   */
46  delete: function(endpoint, options) {
47    return this._makeRequest('DELETE', endpoint, null, options);
48  },
49
50  /**
51   * Internal method to make HTTP request
52   * @private
53   */
54  _makeRequest: function(method, endpoint, data, options) {
55    var result = {
56      success: false,
57      status: 0,
58      data: null,
59      error: ''
60    };
61
62    options = options || {};
63
64    try {
65      // Create REST message
66      var request = new sn_ws.RESTMessageV2();
67      request.setEndpoint(endpoint);
68      request.setHttpMethod(method);
69
70      // Set default headers
71      request.setRequestHeader('Content-Type', 'application/json');
72      request.setRequestHeader('Accept', 'application/json');
73
74      // Add custom headers
75      if (options.headers) {
76        for (var header in options.headers) {
77          request.setRequestHeader(header, options.headers[header]);
78        }
79      }
80
81      // Add query parameters to URL
82      if (options.params) {
83        var paramString = this._buildQueryString(options.params);
84        if (paramString) {
85          endpoint += (endpoint.indexOf('?') === -1 ? '?' : '&') + paramString;
86          request.setEndpoint(endpoint);
87        }
88      }
89
90      // Set request body for POST/PUT
91      if (data && (method === 'POST' || method === 'PUT')) {
92        var jsonData = typeof data === 'string' ? data : JSON.stringify(data);
93        request.setRequestBody(jsonData);
94      }
95
96      // Set timeout (default 30 seconds)
97      var timeout = options.timeout || 30000;
98      request.setHttpTimeout(timeout);
99
100      // Execute request
101      var response = request.execute();
102      result.status = response.getStatusCode();
103
104      // Parse response body
105      var responseBody = response.getBody();
106      if (responseBody) {
107        try {
108          result.data = JSON.parse(responseBody);
109        } catch (e) {
110          result.data = responseBody;  // Return as string if not JSON
111        }
112      }
113
114      // Check success
115      if (result.status >= 200 && result.status < 300) {
116        result.success = true;
117      } else {
118        result.error = 'HTTP ' + result.status + ': ' + response.getStatusMessage();
119      }
120
121      // Log request details
122      gs.debug('RestAPIClient ' + method + ' ' + endpoint + ' - Status: ' + result.status);
123
124    } catch (e) {
125      result.error = 'Request failed: ' + e.message;
126      gs.error('RestAPIClient error: ' + e.message + ', endpoint: ' + endpoint);
127    }
128
129    return result;
130  },
131
132  /**
133   * Build query string from parameters object
134   * @private
135   */
136  _buildQueryString: function(params) {
137    var parts = [];
138    for (var key in params) {
139      if (params[key] !== null && params[key] !== undefined) {
140        parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key]));
141      }
142    }
143    return parts.join('&');
144  },
145
146  /**
147   * Make authenticated request with Bearer token
148   *
149   * @param {string} method - HTTP method
150   * @param {string} endpoint - API endpoint
151   * @param {object} data - Request data
152   * @param {string} token - Bearer token
153   * @param {object} options - Additional options
154   * @returns {object} Response object
155   */
156  authenticatedRequest: function(method, endpoint, data, token, options) {
157    options = options || {};
158    options.headers = options.headers || {};
159    options.headers['Authorization'] = 'Bearer ' + token;
160
161    return this._makeRequest(method, endpoint, data, options);
162  },
163
164  /**
165   * Make request with Basic authentication
166   *
167   * @param {string} method - HTTP method
168   * @param {string} endpoint - API endpoint
169   * @param {object} data - Request data
170   * @param {string} username - Username
171   * @param {string} password - Password
172   * @param {object} options - Additional options
173   * @returns {object} Response object
174   */
175  basicAuthRequest: function(method, endpoint, data, username, password, options) {
176    options = options || {};
177    options.headers = options.headers || {};
178
179    // Create basic auth header
180    var credentials = username + ':' + password;
181    var encoded = GlideStringUtil.base64Encode(credentials);
182    options.headers['Authorization'] = 'Basic ' + encoded;
183
184    return this._makeRequest(method, endpoint, data, options);
185  },
186
187  type: 'RestAPIClient'
188};

How to Use

1. Create a new Script Include 2. Set Name to "RestAPIClient" 3. Leave "Client callable" unchecked 4. Copy the code above 5. Use in Business Rules or other Script Includes to call external APIs Example usage: var api = new RestAPIClient(); var response = api.get('https://api.example.com/data', {params: {id: '123'}}); if (response.success) { gs.info('Data: ' + JSON.stringify(response.data)); } else { gs.error('Error: ' + response.error); }

Explore More Scripts

Browse our complete library of ServiceNow scripts

View All Scripts