The RESTMessageV2 API allows you to send outbound REST messages using JavaScript.

Use the RESTResponseV2 API to manage the response returned by the REST provider.

The User-Agent value is "ServiceNow/1.0". To change this, add the glide.http.user.agent system property in the System Properties [sys_properties] table.

This API runs in the sn_ws namespace.

RESTMessageV2 - disableForcedVariableSubstitution()

Disables forced variable substitution in outbound REST messages.

Note: Use of curly brackets or dollar signs in your request may inadvertently return a truncated output. If your request erroneously truncates the response or splits the response onto new lines, refer to this Community article for a potential solution.
Table 1. Parameters
Name Type Description
None
Table 2. Returns
Type Description
void

Example

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get");
sm.disableForcedVariableSubstitution();
var response = sm.execute();

RESTMessageV2 - execute()

Sends the REST message to the endpoint.

Table 3. Parameters
Name Type Description
None
Table 4. Returns
Type Description
RESTResponse The response returned by the REST provider.

In the following example, replace REST_message_record with the name of the REST message record from your instance.

Example

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
var response = sm.execute(); //Might throw exception if http connection timed out or some issue with sending request itself because of encryption/decryption of password.

RESTMessageV2 - executeAsync()

Sends the REST message to the endpoint asynchronously. The instance does not wait for a response from the web service provider when making asynchronous calls.

Table 5. Parameters
Name Type Description
None
Table 6. Returns
Type Description
RESTResponse The response returned by the REST provider.

In the following example, replace REST_message_record with the name of the REST message record from your instance. When using executeAsync, consider processing the response body in a separate business rule to take advantage of the asynchronous call.

Example

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
var response = sm.executeAsync(); //Might throw exception if http connection timed out or some issue with sending request itself because of encryption/decryption of password.

RESTMessageV2 - getEndpoint()

Gets the URL of the endpoint for the REST message.

Table 7. Parameters
Name Type Description
None
Table 8. Returns
Type Description
String The URL of the REST web service provider.

In the following example, replace REST_message_record with the name of the REST message record from your instance.

Example

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
var endpoint = sm.getEndpoint();

RESTMessageV2 - getRequestBody()

Gets the content of the REST message body.

Table 9. Parameters
Name Type Description
None
Table 10. Returns
Type Description
String the REST message body.

In the following example, replace REST_message_record with the name of the REST message record from your instance.

Example

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
var body = sm.getRequestBody();

RESTMessageV2 - getRequestHeader(String headerName)

Gets the value for an HTTP header specified in the REST message.

By default, this method cannot return the value for a header set automatically by the system. To grant this method access to all headers, set the property glide.http.log_debug to true.

Table 11. Parameters
Name Type Description
headerName String Request header you want to get the value for.
Table 12. Returns
Type Description
String The value of the specified header.

In the following example, replace REST_message_record with the name of the REST message record from your instance.

Example

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
var header = sm.getRequestHeader("Accept");

RESTMessageV2 - getRequestHeaders()

Gets HTTP headers that were set by the REST client and the associated values.

This method does not return headers set automatically by the system. To configure this method to return all headers, set the property glide.http.log_debug to true.

Table 13. Parameters
Name Type Description
None
Table 14. Returns
Type Description
Object An Object that maps the name of each header to the associated value.

In the following example, replace REST_message_record with the name of the REST message record from your instance.

Example

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
var headers = sm.getRequestHeaders();

RESTMessageV2 - RESTMessageV2()

Instantiates an empty RESTMessageV2 object.

When using an object instantiated this way, you must manually specify an HTTP method and endpoint.

Table 15. Parameters
Name Type Description
None

Example

var sm = new sn_ws.RESTMessageV2();

RESTMessageV2 - RESTMessageV2(String name, String methodName)

Instantiates a RESTMessageV2 object using information from a REST message record.

You must have a REST message record defined before you can use this constructor.

Table 16. Parameters
Name Type Description
name String The name of the REST message record.
methodName String The name of the HTTP method to use, such as GET/get or PUT/put - case insensitive.

In the following example, replace REST_message_record with the name of the REST message record from your instance.

Example

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.

RESTMessageV2 - saveResponseBodyAsAttachment(String tableName, String recordSysId, String fileName)

Configures the REST message to save the returned response body as an attachment record.

When you use this function with a REST message that is sent through a MID server, the MID server user must have any roles required to read and write attachment records, as well as any roles required to read and write records on the table specified in the tableName parameter.

The response body does not need to be a binary file to be saved as an attachment. Response bodies using text formats, such as JSON or XML can also be saved. If the instance fails to save the attachment, call getErrorMessage() on the related RESTResponseV2 object for error details.

Table 17. Parameters
Name Type Description
tableName String Specify the table that contains the record you want to attach the saved file to.
recordSysId String Specify the sys_id of the record you want to attach the saved file to.
fileName String Specify the file name to give to the saved file.
Table 18. Returns
Type Description
void

Example

(function sampleRESTMessageV2() {
  try{
    var request  = new sn_ws.RESTMessageV2();        
    request.setHttpMethod('get');

    var attachment_sys_id  = '<attachment_record_sys_id>', 
      tablename = 'incident',
      recordSysId = '<incident_sys_id>',            
      response,            
      httpResponseStatus,             
      filename ='<filename>';

    //endpoint - ServiceNow REST Attachment API        
    request.setEndpoint('https://<instance_name>.service-now.com/api/now/attachment/' + attachment_sys_id  +'/file');        
    request.setBasicAuth('<username>', '<password>');

    //RESTMessageV2 - saveResponseBodyAsAttachment(String tableName, String recordSysId, String fileName)        
    request.saveResponseBodyAsAttachment(tablename, recordSysId, filename);        

    response = request.execute();        
    httpResponseStatus = response.getStatusCode();  
      
    gs.info(" http response status_code:  " + httpResponseStatus);    
  }
  catch(ex){
    var message  = ex.getMessage();        
    gs.info(message);    
  }
})();

RESTMessageV2 - saveResponseBodyAsAttachment(String tableName, String recordSysId, String fileName, String encryptContext)

Configures the REST message to save the returned response body as an encrypted attachment record.

When you use this function with a REST message that is sent through a MID server, the MID server user must have any roles required to read and write attachment records, as well as any roles required to read and write records on the table specified in the tableName parameter.

The response body does not need to be a binary file to be saved as an attachment. Response bodies using text formats, such as JSON or XML can also be saved. If the instance fails to save the attachment, call getErrorMessage() on the related RESTResponseV2 object for error details.

Table 20. Returns
Type Description
void

RESTMessageV2 - setAuthenticationProfile(String type, String profileId)

Sets the credentials for the REST message using an existing basic auth or OAuth 2.0 profile.

Table 21. Parameters
Name Type Description
type String The type of authentication profile to use. Valid values are 'basic' to use basic authentication, or 'oauth2' to use OAuth 2.0.
profileId String The sys_id of an authentication profile record. When using basic auth, specify the sys_id of a Basic Auth Configuration [sys_auth_profile_basic] record. When using OAuth 2.0, specify the sys_id of a OAuth Entity Profile [oauth_entity_profile] record.
Table 22. Returns
Type Description
void

In the following example, replace REST_message_record with the name of the REST message record from your instance.

Example

var requestBody;
var responseBody;
var status;
var sm;
try{
       // Might throw exception if message doesn't exist or not visible due to scope.
	sm = new sn_ws.RESTMessageV2("<REST_message_record>", "get");  

       //set auth profile to an OAuth 2.0 profile record.
	sm.setAuthenticationProfile('oauth2', '1234adsf123212131123qasdsf'); 

	sm.setStringParameter("symbol", "NOW");
	sm.setStringParameterNoEscape("xml_data","<data>test</data>");

       //In milliseconds. Wait at most 10 seconds for response from http request.
	sm.setHttpTimeout(10000); 
       //Might throw exception if http connection timed out or some issue 
       //with sending request itself because of encryption/decryption of password.
	response = sm.execute();	
       responseBody = response.haveError() ? response.getErrorMessage() : response.getBody();
	status = response.getStatusCode();
} catch(ex) {
	responseBody = ex.getMessage();
	status = '500';
} finally {
	requestBody = sm ? sm.getRequestBody():null;
}

RESTMessageV2 - setBasicAuth(String userName, String userPass)

Sets basic authentication headers for the REST message.

Setting security values using this method overrides basic authentication values defined for the REST message record.

Table 23. Parameters
Name Type Description
userName String Username you want to use to authenticate the REST message.
userPass String Password for the specified user.
Table 24. Returns
Type Description
void

In the following example, replace REST_message_record with the name of the REST message record from your instance.

Example

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
sm.setBasicAuth("username","password");

RESTMessageV2 - setEccCorrelator(String correlator)

Associates outbound requests and the resulting response record in the ECC queue. This method only applies to REST messages sent through a MID Server.

The correlator provided populates the Agent correlator field on the ECC queue record for the response. Provide a unique correlator for each outbound request to associate the correct results in the ECC queue with the request when designing asynchronous automation through a MID Server.

Table 25. Parameters
Name Type Description
correlator String Unique identifier
Table 26. Returns
Type Description
void

In the following example, replace REST_message_record with the name of the REST message record from your instance.

Example

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
sm.setEccCorrelator("unique_identifier");

RESTMessageV2 - setEccParameter(String name, String value)

Overrides a value from the database by writing to the REST message payload. This method only applies to REST messages sent through a MID Server.

Use this method when a value from the REST message in the database is invalid, such as when the endpoint URL is longer than the maximum REST endpoint field length. You can set only the endpoint URL using this method by passing source as the name parameter.

Table 27. Parameters
Name Type Description
name String The name of the parameter, such as source.
value String The value to assign to the specified parameter.
Table 28. Returns
Type Description
void

In the following example, replace REST_message_record with the name of the REST message record from your instance.

Example

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
sm.setEccParameter("source","http://very.long.endpoint.url");

RESTMessageV2 - setEndpoint(String endpoint)

Sets the endpoint for the REST message.

By default, the REST message uses the endpoint specified in the REST message record. Use this method to override this default. You must call this method when using the RESTMessageV2 - RESTMessageV2() constructor with no parameters.

Table 29. Parameters
Name Type Description
endpoint String The URL of the REST provider you want to interface with.
Table 30. Returns
Type Description
void

Example

var sm = new sn_ws.RESTMessageV2();
sm.setEndpoint("http://web.service.endpoint");

RESTMessageV2 - setHttpMethod(String method)

Sets the HTTP method this REST message performs, such as GET or PUT.

You must set an HTTP method when using the RESTMessageV2 - RESTMessageV2() constructor with no parameters.

Table 31. Parameters
Name Type Description
method String HTTP method to perform.
Table 32. Returns
Type Description
void

Example

var sm = new sn_ws.RESTMessageV2();
sm.setHttpMethod("post");

RESTMessageV2 - setHttpTimeout(Number timeoutMs)

Sets the amount of time the REST message waits for a response from the web service provider before the request times out.

Table 33. Parameters
Name Type Description
timeoutMs Number Amount of time in milliseconds before the call to the REST provider times out.
Note: This value sets a timeout on the socket and only times out if the socket does not receive data within the specified time. For environments in which responses are streamed, it's possible that connections last much longer than the timeout value.
Table 34. Returns
Type Description
None

Example

To use the following example, replace <REST_message_record> with the name of the REST message record from your instance.

// Might throw exception if message doesn't exist or not visible due to scope.
var sm = new sn_ws.RESTMessageV2("<REST_message_record>", "get");
sm.setHttpTimeout(6000);

RESTMessageV2 - setLogLevel(String level)

Sets the log level for this message and the corresponding response.

Setting a log level using the RESTMessageV2 API overrides the log level configured on the REST message record. This log level may not apply if the endpoint domain is excluded, or if the property glide.outbound_http_log.override is true. To view outbound web service logs, navigate to System Logs > Outbound HTTP Requests.

Table 35. Parameters
Name Type Description
level String The log level. Valid values are basic, elevated, and all.
Table 36. Returns
Type Description
void

Example

var rm = new sn_ws.RESTMessageV2();
rm.setLogLevel('all');

RESTMessageV2 - setMIDServer(String midServer)

Configures the REST message to communicate through a MID Server.

Table 37. Parameters
Name Type Description
midServer String Name of the MID Server to use. Your instance must have an active MID Server with the specified name.
Table 38. Returns
Type Description
void

Example

In the following example, replace REST_message_record with the name of the REST message record from your instance.

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
sm.setMIDServer("mid_server_name");

RESTMessageV2 - setMutualAuth(String profileName)

Sets the mutual authentication protocol profile for the REST message.

Setting a protocol profile using this method overrides the protocol profile selected for the REST message record.

Table 39. Parameters
Name Type Description
profileName String The Name of the protocol profile to use for mutual authentication.
Table 40. Returns
Type Description
void

Example

In the following example, replace REST_message_record with the name of the REST message record from your instance.

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
sm.setMutualAuth("mutual_auth_profile_name");

RESTMessageV2 - setQueryParameter(String name, String value)

Appends a parameter to the end of the request URL with the form name=value.

For example, the code setQueryParameter("sysparm_query","active=true^ORDERBYnumber^ORDERBYDESCcategory"); appends the text sysparm_query=active=true^ORDERBYnumber^ORDERBYDESCcategory to the request URL.

Table 41. Parameters
Name Type Description
name String Name of the URL parameter to pass.
value String Value to assign the URL parameter.
Table 42. Returns
Type Description
void

Example

var sm = new sn_ws.RESTMessageV2();
//Set up message, including endpoint and authentication
sm.setQueryParameter("sysparm_query","active=true^ORDERBYnumber^ORDERBYDESCcategory");

RESTMessageV2 - setRequestBody(String body)

Sets the body content to send to the web service provider when using PUT or POST HTTP methods.

When you set the body content using this method, variables in the body are not substituted for parameters from the REST message function record. You must explicitly define all values within the REST message body.

Table 43. Parameters
Name Type Description
body String Request body to send.
Table 44. Returns
Type Description
void

Example

var sm = new sn_ws.RESTMessageV2("Update user","post"); //Might throw exception if message doesn't exist or not visible due to scope.
var body = "<Message body content>";
sm.setRequestBody(body);

RESTMessageV2 - setRequestBodyFromAttachment(String attachmentSysId)

Sets the request body using an existing attachment record.

When you use this function with a REST message that is sent through a MID Server, the MID Server user must have any roles required to read attachment records.

Table 45. Parameters
Name Type Description
attachmentSysId String Sys_id of the Attachment [sys_attachment] record you want to send in this REST message.
Table 46. Returns
Type Description
void

Example

(function sampleRESTMessageV2() {
    try {
        var request = new sn_ws.RESTMessageV2();
        request.setHttpMethod('post');
        request.setEndpoint('<web service endpoint URL>');
        request.setRequestBodyFromAttachment('<attachment sys_id>');
        
        var response = request.execute();
        var httpResponseStatus = response.getStatusCode();
      
        gs.info("http response status_code: " + httpResponseStatus);        
    }
    catch (ex) {
        var message = ex.getMessage();
        gs.info(message);
    }
})();

RESTMessageV2 - setRequestHeader(String name, String value)

Sets an HTTP header in the REST message to the specified value.

Table 47. Parameters
Name Type Description
name String Name of the header.
value String Value to assign to the specified header.
Table 48. Returns
Type Description
void

Example

In the following example, replace REST_message_record with the name of the REST message record from your instance.

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
sm.setRequestHeader("Accept","Application/json");

RESTMessageV2 - setRequestorProfile(String requestorContext, String requestorId)

Overrides the default requestor profile for the REST message in order to retrieve an OAuth access token associated with a different requestor.

This method applies only to REST messages configured to use OAuth 2.0 authentication. This method is optional and is unnecessary in most configurations.

Table 49. Parameters
Name Type Description
requestorContext String
requestorId String
Table 50. Returns
Type Description
void

RESTMessageV2 - setStringParameter(String name, String value)

Sets a REST message function variable with the specified name from the REST message record to the specified value.

XML reserved characters in the value are converted to the equivalent escaped characters. Use setStringParameterNoEscape to set a variable without escaping XML reserved characters.

Table 51. Parameters
Name Type Description
name String Name of the REST message variable. This parameter must be defined in the REST message record before you can assign a value to it.
value String Value to assign the variable.
Table 52. Returns
Type Description
void

Example

In the following example, replace REST_message_record with the name of the REST message record from your instance.

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
sm.setStringParameter("s","NOW");

RESTMessageV2 - setStringParameterNoEscape(String name, String value)

Sets a REST message function variable with the specified name from the REST message record to the specified value.

This method is equivalent to setStringParameter but does not escape XML reserved characters.

Table 53. Parameters
Name Type Description
name String Name of the REST message variable. This parameter must be defined in the REST message record before you can assign a value to it.
value String Value to assign the variable.
Table 54. Returns
Type Description
void

Example

In the following example, replace REST_message_record with the name of the REST message record from your instance.

var sm = new sn_ws.RESTMessageV2("<REST_message_record>","get"); //Might throw exception if message doesn't exist or not visible due to scope.
sm.setStringParameterNoEscape("s","NOW");