Example 1: Retrieving all incident records from an external source
Summarize
Summary of Example 1: Retrieving all incident records from an external source
This example demonstrates how to create a script in ServiceNow to retrieve and cache all incident records from an external source using the Remote Table API. It is designed for ServiceNow customers who need to integrate incident data from another instance or external REST service into their current instance.
Show less
Key Features
- REST Message Execution: The script uses
RESTMessageV2to call a predefined REST message ('Remote Instance Incidents') and function ('All Incidents') that fetch all incident records from the external source. - Error Handling: If the REST call returns an error, the script captures and sets the error message for visibility in the query list view, aiding in debugging.
- Data Transformation: The Transformer API is utilized to parse the JSON response. A
TransformerDefinitionmaps external JSON fields (likeactive,callerid,number, etc.) to table fields in ServiceNow. - Row Addition: Each transformed record row is added to the remote table for further use within the ServiceNow instance.
- Sysid Mapping: The script explicitly maps the external record’s
sysidto enable proper form operations on the imported data. The sysid must be 32 characters or fewer.
Practical Use for ServiceNow Customers
By implementing this script, customers can seamlessly integrate and synchronize incident data from external sources into their ServiceNow instance. This enables unified incident management and reporting without manual data imports.
Key practical points include:
- Define and configure a REST Message in ServiceNow that points to the external incident source.
- Use the provided script structure to execute the REST call, handle errors, and transform the response data.
- Customize the transformer mappings to match the external data schema, ensuring all required fields, especially
sysid, are properly mapped. - Leverage the Transformer API to add the transformed data rows to your remote table, making external incident records accessible within your instance.
Additional Notes
- Understanding how to define and use
RESTMessageV2is essential; refer to ServiceNow documentation for creating direct REST messages. - Debugging tips include using
gs.error()or session debugger logs to troubleshoot REST call issues. - Only the fields mapped in the transformer definition will be retrieved and used; unmapped external fields are ignored.
These are examples of script definitions you might create for retrieval and caching of data from sources external to your current instance. In this first example, we create a script to load all incident records from an external source.
/**
* Using `v_query`, add the rows to `v_table`
*/
(function executeQuery(v_table, v_query) {
fetchAllIncidents(v_table, v_query);
/**
* fetch all incidents records from the remote instance
*/
function fetchAllIncidents(v_table, v_query) {
// Uses RestMessage with name 'Remote Instance Incidents' and function 'All Incidents'
// Create a RestMessage first which calls an external REST service
try {
var restMessage = new sn_ws.RESTMessageV2('Remote Instance Incidents', 'All Incidents');
var response = restMessage.execute();
var responseBody = response.getBody();
// if REST call ends up in an error, set the last error message which shows up
// at the bottom of the list view
if (response.haveError()) {
v_query.setLastErrorMessage(response.getErrorMessage());
// can use gs.error() or gs.addErrorMessage() while debugging
// gs.debug() messages visible in session debugger
// gs.debug(response.getErrorMessage());
return;
}
} catch (ex) {
v_query.setLastErrorMessage(ex.message);
// gs.debug(ex.message);
return;
}
var transformerDefinition = getTransformerDefinition();
var transformer = new sn_tfrm.Transformer(transformerDefinition, responseBody);
// transformer parses the responseBody and extracts rows
while (transformer.transform()) {
// row is field-value map e.g. { active:"true", number: "INC0000001"}
var row = transformer.getRow();
// you may do any additional transformations to the row like GlideDuration, GlideDataTime etc. For example,
// row.duration = new GlideDuration(row.duration);
// finally add the row to the remote table
v_table.addRow(row);
}
}
/**
* returns a sn_tfrm.TransformerDefinition, which defines the mapping of the table fields and elements in the response body
*/
function getTransformerDefinition() {
// create a rule list to map a field to its element path
var ruleList = new sn_tfrm.TransformerRuleList()
.fromJSON() // the response body is a JSON
// 'active' field maps to path '$.active'
.addRule("active", "$.active")
.addRule("caller_id", "$.caller_id.value")
.addRule("number", "$.number")
.addRule("short_description", "$.short_description")
.addRule("sys_id", "$.sys_id")
.addRule("updates", "$.sys_mod_count");
var recordPath = "$.result";
return new sn_tfrm.TransformerDefinition(ruleList, recordPath);
}
})(v_table, v_query);
These code snippets are of note in this script:
function fetchAllIncidents(v_table, v_query) {
// Uses RestMessage with name 'Remote Instance Incidents' and function 'All Incidents'
// Create a RestMessage first which calls an external REST service
try {
var restMessage = new sn_ws.RESTMessageV2('Remote Instance Incidents', 'All Incidents');
var response = restMessage.execute();
var responseBody = response.getBody();
// if REST call ends up in an error, set the last error message which shows up
// at the bottom of the list view
if (response.haveError()) {
v_query.setLastErrorMessage(response.getErrorMessage());
// can use gs.error() or gs.addErrorMessage() while debugging
// gs.debug() messages visible in session debugger
// gs.debug(response.getErrorMessage());
return;
}
} catch (ex) {
v_query.setLastErrorMessage(ex.message);
// gs.debug(ex.message);
return;
}
You can create a RestMessage and directly use it in the script. In this example, it
uses a RESTMessageV2 API with the name of Remote Instance
Incidents, and the function All Incidents, which gets all
incident data. Once a response is returned from the server, an error message appears
if problems are encountered in the data retrieval.
If no problems are encountered in the data retrieval, it gets the data body for the records.
var transformerDefinition = getTransformerDefinition();
var transformer = new sn_tfrm.Transformer(transformerDefinition, responseBody);
// transformer parses the responseBody and extracts rows
while (transformer.transform()) {
// row is field-value map e.g. { active:"true", number: "INC0000001"}
var row = transformer.getRow();
// you may do any additional transformations to the row like GlideDuration, GlideDataTime etc. For example,
// row.duration = new GlideDuration(row.duration);
// finally add the row to the remote table
v_table.addRow(row);
It then uses the Transformer API to perform any required data transformations, extracts rows, and then adds a row for each record to the remote table.
/**
* returns a sn_tfrm.TransformerDefinition, which defines the mapping of the table fields and elements in the response body
*/
function getTransformerDefinition() {
// create a rule list to map a field to its element path
var ruleList = new sn_tfrm.TransformerRuleList()
.fromJSON() // the response body is a JSON
// 'active' field maps to path '$.active'
.addRule("active", "$.active")
.addRule("caller_id", "$.caller_id.value")
.addRule("number", "$.number")
.addRule("short_description", "$.short_description")
.addRule("sys_id", "$.sys_id")
.addRule("updates", "$.sys_mod_count");
var recordPath = "$.result";
return new sn_tfrm.TransformerDefinition(ruleList, recordPath);
}
})(v_table, v_query);
getTransformerDefinition defines the schema of the record in the
external API response body. It maps each of the fields in the table script to an
element in the external record. Any external data elements outside of this mapping
are not supported or retrieved.