RESTMessageV2 - Scoped, Global

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.

You can use this API in scoped applications, or within the global scope.

RESTMessageV2 - execute()

Send the REST message to the endpoint.

Table 1. Parameters
Name Type Description
None
Table 2. Returns
Type Description
RESTResponse The response returned by the REST provider.
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","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()

Send 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 3. Parameters
Name Type Description
None
Table 4. Returns
Type Description
RESTResponse The response returned by the REST provider.
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","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.
response.waitForResponse(60); // In seconds. Wait at most 60 seconds to get response from ECC Queue/Mid Server //Might throw exception timing out waiting for response in ECC queue.

RESTMessageV2 - getEndpoint()

Get the URL of the endpoint for the REST message.

Table 5. Parameters
Name Type Description
None
Table 6. Returns
Type Description
String The URL of the REST web service provider.
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","get"); //Might throw exception if message doesn't exist or not visible due to scope.
var endpoint = sm.getEndpoint();

RESTMessageV2 - getRequestBody()

Get the content of the REST message body.

Table 7. Parameters
Name Type Description
None
Table 8. Returns
Type Description
String the REST message body.
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","get"); //Might throw exception if message doesn't exist or not visible due to scope.
var body = sm.getRequestBody();

RESTMessageV2 - getRequestHeader(String headerName)

Get 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 9. Parameters
Name Type Description
headerName String The request header you want to get the value for.
Table 10. Returns
Type Description
String The value of the specified header.
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","get"); //Might throw exception if message doesn't exist or not visible due to scope.
var header = sm.getRequestHeader("Accept");

RESTMessageV2 - getRequestHeaders()

Get 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 11. Parameters
Name Type Description
None
Table 12. Returns
Type Description
Object An Object that maps the name of each header to the associated value.
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","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 13. Parameters
Name Type Description
None
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 14. 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 or PUT.
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","get"); //Might throw exception if message doesn't exist or not visible due to scope.

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

Configure 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 15. 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 16. Returns
Type Description
void

(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.print(" http response status_code:  " + httpResponseStatus);    
  }
  catch(ex){
    var message  = ex.getMessage();        
    gs.print(message);    
  }
})();

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

Configure 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 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.
encryptContext String Specify the sys_id of an encryption context. The saved file is encrypted using this context.
Table 18. Returns
Type Description
void

RESTMessageV2 - setAuthenticationProfile(String type, String profileId)

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

Table 19. 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 20. Returns
Type Description
void
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("Yahoo Finance", "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 21. Parameters
Name Type Description
userName String The username you want to use to authenticate the REST message.
userPass String The password for the specified user.
Table 22. Returns
Type Description
void
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","get"); //Might throw exception if message doesn't exist or not visible due to scope.
sm.setBasicAuth("username","password");

RESTMessageV2 - setEccCorrelator(String correlator)

Associate 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 23. Parameters
Name Type Description
correlator String A unique identifier
Table 24. Returns
Type Description
void
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","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)

Override 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 25. 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 26. Returns
Type Description
void
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","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)

Set 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 27. Parameters
Name Type Description
endpoint String The URL of the REST provider you want to interface with.
Table 28. Returns
Type Description
void
var sm = new sn_ws.RESTMessageV2();
sm.setEndpoint("http://web.service.endpoint");

RESTMessageV2 - setHttpMethod(String method)

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 29. Parameters
Name Type Description
method String The HTTP method to perform.
Table 30. Returns
Type Description
void
var sm = new sn_ws.RESTMessageV2();
sm.setHttpMethod("post");

RESTMessageV2 - setHttpTimeout(Number timeoutMs)

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

Table 31. Parameters
Name Type Description
timeoutMs Number The amount of time, in milliseconds, before the call to the REST provider times out.
Table 32. Returns
Type Description
void
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","get"); //Might throw exception if message doesn't exist or not visible due to scope.
sm.setHttpTimeout(6000);

RESTMessageV2 - setLogLevel(String level)

Set 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 blacklisted, 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 33. Parameters
Name Type Description
level String The log level. Valid values are basic, elevated, and all.
Table 34. Returns
Type Description
void
var rm = new sn_ws.RESTMessageV2();
rm.setLogLevel(‘all’);

RESTMessageV2 - setMIDServer(String midServer)

Configure the REST message to communicate through a MID Server.

Table 35. Parameters
Name Type Description
midServer String The name of the MID Server to use. Your instance must have an active MID Server with the specified name.
Table 36. Returns
Type Description
void
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","get"); //Might throw exception if message doesn't exist or not visible due to scope.
sm.setMIDServer("mid_server_name");

RESTMessageV2 - setMutualAuth(String profileName)

Set 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 37. Parameters
Name Type Description
profileName String The Name of the protocol profile to use for mutual authentication.
Table 38. Returns
Type Description
void
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","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)

Append 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 39. Parameters
Name Type Description
name String The name of the URL parameter to pass.
value String The value to assign the URL parameter.
Table 40. Returns
Type Description
void
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)

Set 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 41. Parameters
Name Type Description
body String The request body to send.
Table 42. Returns
Type Description
void
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)

Set 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 43. Parameters
Name Type Description
attachmentSysId String The sys_id of the Attachment [sys_attachment] record you want to send in this REST message.
Table 44. Returns
Type Description
void

(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.print("http response status_code: " + httpResponseStatus);        
    }
    catch (ex) {
        var message = ex.getMessage();
        gs.print(message);
    }
})();

RESTMessageV2 - setRequestBodyFromStream(Object stream)

Set the body content of a PUT or POST message using a binary stream.

You can use this method to send binary files such as images or archives using REST messages. If the request is not a PUT or POST request, the request body is ignored.

Table 45. Parameters
Name Type Description
stream Object The binary data to send, such as an attachment or a stream from a 3rd-party service.
Table 46. Returns
Type Description
void

RESTMessageV2 - setRequestHeader(String name, String value)

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

Table 47. Parameters
Name Type Description
name String The name of the header.
value String The value to assign to the specified header.
Table 48. Returns
Type Description
void
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","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)

Override 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)

Set 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 The 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 The value to assign the variable.
Table 52. Returns
Type Description
void
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","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)

Set 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 The 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 The value to assign the variable.
Table 54. Returns
Type Description
void
var sm = new sn_ws.RESTMessageV2("Yahoo Finance","get"); //Might throw exception if message doesn't exist or not visible due to scope.
sm.setStringParameterNoEscape("s","NOW");