IT CanvassTalk to an advisor
Development · LessonBy , ServiceNow Trainer, 8 yrs · Published · ServiceNow · all levels

Outbound REST (RESTMessageV2)

Call external APIs from ServiceNow: REST messages, methods, authentication, error handling and MID server routing.

Quick answer

Call external APIs from ServiceNow: REST messages, methods, authentication, error handling and MID server routing.

Key takeaways
  • Keep endpoints and credentials in configuration, not in code
  • Always set a timeout and handle non 200 responses
  • Use connection and credential aliases so environments differ safely
  • MID server routing reaches internal endpoints without opening the firewall

Configuration first

Create a REST message with the base endpoint, then a method per operation with its HTTP verb and path. Variables in the endpoint use the ${var} syntax and are set at runtime, which keeps the script readable and the endpoint configurable.

Calling it

Instantiate from the record so configuration stays outside the code.

var r = new sn_ws.RESTMessageV2('Acme CMDB', 'getAsset');
r.setStringParameterNoEscape('assetTag', current.asset_tag.toString());
r.setHttpTimeout(15000);
var resp = r.execute();
var code = resp.getStatusCode();
if (code != 200) {
  gs.error('Acme CMDB call failed: ' + code + ' ' + resp.getErrorMessage());
} else {
  var body = JSON.parse(resp.getBody());
}

Production concerns

External calls fail, so plan for it.

  • Always set a timeout, the default is generous and blocks a worker
  • Log the status code and correlation id, never the full body with secrets
  • Use executeAsync for long running calls from a business rule
  • Route through a MID server when the endpoint is internal only
  • Store credentials in a credential record or connection alias, not in script

Practice challenge

+0 XPStreak ×0
Question 1 of 2
Which class sends an outbound REST call?

Frequently asked questions

Where should the API key live?
In a credential record referenced by a connection alias. Scripts then ask for the alias, and each environment points at its own credential.
How do I test a REST message quickly?
Use the Test related link on the method. It shows the full request and response, including headers, without writing a script.
Already working on ServiceNow and stuck on a live ticket?Get an expert ServiceNow developer on screen-share to finish your daily tasks with you. Deliver on time, protect your reputation and your job. Monthly support only, no task-wise plans.Task assigned · no idea where to startStill stuck · your job on the lineExpert joins your screenDelivered on timeExplore On Job Support