RESTMessageV2 ServiceNow Guide

Share

RESTMessageV2 ServiceNow

RESTMessageV2 in ServiceNow is a server-side scripting API used to send outbound REST requests from ServiceNow to external or internal REST services. It is particularly useful when an integration needs dynamic request construction, runtime parameters, response processing, conditional logic, or execution from Business Rules, Script Includes, Scheduled Jobs, and other server-side scripting contexts. ServiceNow’s current documentation describes RESTMessageV2 as part of the sn_ws namespace and supports both constructing requests from a configured REST Message and creating a request programmatically.

Note: This article focuses on ServiceNow RESTMessageV2 rather than the ServiceNow Communities product. The examples use current ServiceNow outbound REST concepts and reference Oracle Fusion Cloud 26A where Oracle integration scenarios are discussed.

What is RESTMessageV2 in ServiceNow?

RESTMessageV2 is a server-side ServiceNow API that allows developers to invoke REST-based web services through JavaScript.

A typical integration has four layers:

LayerPurpose
REST MessageStores reusable endpoint and authentication configuration
HTTP MethodDefines GET, POST, PUT, PATCH, DELETE, headers and payload
RESTMessageV2JavaScript API used to invoke the configured REST message
RESTResponseV2Provides access to status, body and response information

ServiceNow documents two primary ways to instantiate the API:

 
var request = new sn_ws.RESTMessageV2(
    'Customer_API',
    'get_customer'
);
 

Here, Customer_API is the REST Message record and get_customer is its HTTP method.

Alternatively, the request can be created completely through scripting:

 
var request = new sn_ws.RESTMessageV2();

request.setEndpoint('https://api.example.com/customers');
request.setHttpMethod('GET');
 

The second approach is useful when the endpoint or HTTP method must be determined dynamically.

For most enterprise implementations, however, the first approach is easier to maintain because endpoint, authentication and HTTP method definitions remain configuration rather than being scattered throughout scripts.


RESTMessageV2 Architecture and Technical Flow

A practical outbound REST integration can be visualized as:

 
ServiceNow Business Logic
        |
        v
Script Include / Business Rule / Scheduled Job
        |
        v
RESTMessageV2
        |
        v
REST Message Configuration
        |
        +---- Authentication
        +---- Endpoint
        +---- HTTP Method
        +---- Headers
        +---- Variables
        +---- Request Body
        |
        v
External REST API
        |
        v
HTTP Response
        |
        v
RESTResponseV2
        |
        +---- Status Code
        +---- Response Body
        +---- Error Information
 

The important design principle is that RESTMessageV2 is the execution mechanism; the REST Message record is the reusable configuration layer.

ServiceNow’s current outbound REST documentation confirms that REST messages can be sent through REST workflow functionality or the RESTMessageV2 scripting API. REST messages can also use a MID Server when the destination is on an internal network.


Real-World RESTMessageV2 Integration Use Cases

Use Case 1 – ServiceNow to Oracle Fusion Cloud

Consider an organization using ServiceNow for employee service requests and Oracle Fusion Cloud HCM for employee master data.

When a ServiceNow HR case is approved, ServiceNow may need to retrieve employee information from Oracle Fusion.

The flow could be:

 
ServiceNow HR Case
      |
      v
Business Rule / Flow-triggered Script
      |
      v
RESTMessageV2
      |
      v
Oracle Fusion HCM REST API
      |
      v
Employee JSON Response
      |
      v
Update ServiceNow Case
 

Oracle Fusion Cloud exposes REST APIs for its business objects. Oracle’s 26A API documentation provides resource-specific REST endpoints and examples for working with Fusion Cloud data.

For example, the ServiceNow request could dynamically provide an employee identifier:

 
var request = new sn_ws.RESTMessageV2(
    'Oracle_HCM_API',
    'get_employee'
);

request.setStringParameter(
    'personNumber',
    current.u_employee_number
);

var response = request.execute();

var status = response.getStatusCode();
var body = response.getBody();
 

The response can then be parsed and mapped into ServiceNow fields.


Use Case 2 – ServiceNow Incident to External IT Platform

A company may use ServiceNow as the primary ITSM system but maintain application records in another platform.

When a Priority 1 incident is created, ServiceNow can send:

  • Incident number
  • Short description
  • Description
  • Priority
  • Assignment group
  • Caller
  • Configuration item

to the external API.

A POST request might look conceptually like:

 
var payload = {
    incident_number: current.number.toString(),
    short_description: current.short_description.toString(),
    priority: current.priority.toString()
};

var request = new sn_ws.RESTMessageV2(
    'External_ITSM',
    'create_incident'
);

request.setRequestBody(JSON.stringify(payload));

var response = request.execute();

gs.info('Status: ' + response.getStatusCode());
 

The key point is that the integration script should not contain passwords or unnecessarily hard-code authentication information.


Use Case 3 – ServiceNow to Internal Application Through MID Server

Suppose an organization’s ERP application is hosted inside a private network and is not directly reachable from the ServiceNow instance.

The architecture can become:

 
ServiceNow
   |
   v
RESTMessageV2
   |
   v
MID Server
   |
   v
Internal REST API
 

ServiceNow supports sending REST messages through a MID Server for endpoints behind firewalls or inside private networks.

This is common in hybrid environments where cloud applications and on-premises applications coexist.


Creating an Outbound REST Message

Before writing the script, create the reusable REST Message configuration.

Step 1 – Navigate to REST Message

Navigate to:

All → System Web Services → Outbound → REST Message

ServiceNow’s current documentation identifies web_service_admin as the role required to create a REST Message.

Click New.


Step 2 – Create the REST Message

Assume the external API is:

 
https://api.example.com/customer
 

Enter:

FieldExample
NameCustomer Management API
Endpointhttps://api.example.com/customer
Authentication TypeOAuth 2.0
OAuth ProfileCustomer API OAuth Profile

The endpoint can also contain variables.

For example:

 
https://api.example.com/customer/${customerId}
 

ServiceNow supports variables in endpoint URLs, HTTP headers, query parameter values, and POST/PUT content.

Click Submit.

After saving the REST Message, ServiceNow creates a default GET HTTP method.


Creating the HTTP Method

Open the REST Message and locate the HTTP Methods related list.

Click New.

Suppose the requirement is to create a customer.

Configure:

 
Name: create_customer
HTTP Method: POST
Endpoint: https://api.example.com/customer
 

Add required headers.

For example:

 
Content-Type: application/json
Accept: application/json
 

The exact headers depend on the target API.

Do not assume that every REST API accepts the same headers. Always verify the target provider’s API specification.


Using RESTMessageV2 in a Script

Once the REST Message is configured, the script becomes relatively simple.

 
var request = new sn_ws.RESTMessageV2(
    'Customer Management API',
    'create_customer'
);

var payload = {
    name: 'John Smith',
    email: 'john.smith@example.com',
    customerType: 'CORPORATE'
};

request.setRequestBody(JSON.stringify(payload));

var response = request.execute();

var statusCode = response.getStatusCode();
var responseBody = response.getBody();

gs.info('HTTP Status: ' + statusCode);
gs.info('Response: ' + responseBody);
 

This approach separates the integration configuration from business logic.


Working with REST Variables

Variables are extremely useful when the same REST Message must process different records.

Suppose the endpoint is:

 
https://api.example.com/customers/${customerId}
 

Create customerId as a REST Message variable.

Then use:

 
var request = new sn_ws.RESTMessageV2(
    'Customer Management API',
    'get_customer'
);

request.setStringParameter(
    'customerId',
    current.u_customer_id.toString()
);

var response = request.execute();
 

ServiceNow documents setStringParameter() for assigning values to configured REST message variables. It also provides setStringParameterNoEscape() when XML-reserved characters should not be escaped.

Practical consultant tip

Prefer configured variables instead of building URLs manually inside every script.

For example, this is easier to maintain:

 
/customer/${customerId}
 

than:

 
request.setEndpoint(
    'https://api.example.com/customer/' +
    current.u_customer_id
);
 

The first approach keeps endpoint design centralized.


Sending a POST Request

For POST requests, construct the JSON payload carefully.

 
var request = new sn_ws.RESTMessageV2(
    'Employee API',
    'create_employee'
);

var employee = {
    employeeNumber: 'E10045',
    firstName: 'Ravi',
    lastName: 'Kumar',
    department: 'Finance'
};

request.setRequestBody(
    JSON.stringify(employee)
);

var response = request.execute();

if (response.getStatusCode() == 201) {
    gs.info('Employee created successfully');
} else {
    gs.error(
        'Employee creation failed: ' +
        response.getStatusCode()
    );
}
 

The target API may return 200, 201, 202, or another status depending on its design. Therefore, do not automatically assume that only 200 means success.


Processing the REST Response

The REST response should normally be evaluated in three stages:

  1. Did the ServiceNow call execute successfully?
  2. What HTTP status did the provider return?
  3. Is the response body valid and useful?

Example:

 
try {

    var request = new sn_ws.RESTMessageV2(
        'Customer API',
        'get_customer'
    );

    request.setStringParameter(
        'customerId',
        current.u_customer_id.toString()
    );

    var response = request.execute();

    var statusCode = response.getStatusCode();
    var responseBody = response.getBody();

    if (statusCode >= 200 && statusCode < 300) {

        var data = JSON.parse(responseBody);

        gs.info(
            'Customer Name: ' + data.name
        );

    } else {

        gs.error(
            'REST API failed. Status: ' +
            statusCode +
            ', Body: ' +
            responseBody
        );
    }

} catch (ex) {

    gs.error(
        'REST integration exception: ' +
        ex.getMessage()
    );
}
 

The RESTResponseV2 API exposes methods such as getStatusCode() for retrieving the numeric HTTP status returned by the provider.


Configuring Authentication

Authentication should be designed before development begins.

ServiceNow outbound REST supports:

  • Basic authentication
  • OAuth 2.0
  • Mutual authentication through protocol profiles

The current ServiceNow documentation also identifies limitations around some authentication scenarios, particularly when MID Servers are involved.

Basic Authentication

Navigate to:

All → System Web Services → Outbound → REST Message

Select the REST Message.

Set:

 
Authentication Type = Basic
Basic Auth Profile = <configured profile>
 

ServiceNow recommends using RESTMessageV2 when authenticated REST messages are invoked from scripts.

OAuth 2.0

For OAuth:

 
Authentication Type = OAuth 2.0
OAuth Profile = <OAuth profile>
 

The OAuth provider and OAuth profile must already be configured.

ServiceNow’s current procedure also provides a Get OAuth Token action for obtaining the authorization token where applicable.

Important security practice

Do not do this:

 
request.setBasicAuth(
    'integration_user',
    'MyPassword123'
);
 

Hard-coded credentials create avoidable security and maintenance problems.

Instead, use ServiceNow authentication profiles and allow the platform to manage the credentials.


Configuring a MID Server

A MID Server becomes relevant when the destination cannot be reached directly from the ServiceNow cloud environment.

Example:

 
ServiceNow Cloud
      |
      | HTTPS
      v
MID Server
      |
      | Internal network
      v
Corporate REST API
 

A RESTMessageV2 request can specify a MID Server.

 
var request = new sn_ws.RESTMessageV2(
    'Internal Customer API',
    'get_customer'
);

request.setMIDServer('MID_SERVER_NAME');

var response = request.executeAsync();
 

ServiceNow documents MID Server RESTMessageV2 execution using executeAsync(). It also notes that REST messages sent through a MID Server are asynchronous.


execute() vs executeAsync()

This is one of the most important RESTMessageV2 decisions in a production implementation.

execute()

 
var response = request.execute();
 

The script waits for the outbound request to complete.

This can be appropriate when the immediate response is genuinely required and the service call is short.

executeAsync()

 
var response = request.executeAsync();
 

The outbound operation is handled asynchronously.

This is generally more appropriate for integrations where the initiating transaction does not need to wait for the external response.

ServiceNow’s current scripting documentation points developers to guidance covering execute() versus executeAsync(), and ServiceNow community guidance referencing the platform’s best-practice knowledge article recommends avoiding long-running synchronous outbound calls in high-volume transaction paths.

Example

Avoid putting a slow external API call directly into a high-volume Business Rule:

 
var response = request.execute();
 

if the user transaction does not actually need the response.

A better architecture may be:

 
Record Created
     |
     v
Event / Async Processing
     |
     v
RESTMessageV2
     |
     v
External API
 

This prevents an external dependency from unnecessarily increasing the response time of the ServiceNow transaction.


Testing RESTMessageV2

Testing should happen at multiple levels.

Level 1 – Test the REST Message

Open:

System Web Services → Outbound → REST Message

Open the HTTP Method and use the available testing functionality.

Confirm:

  • Endpoint
  • HTTP method
  • Headers
  • Authentication
  • Variables
  • Request body
  • Response

Level 2 – Test with a Script

Use a controlled script in a suitable non-production environment.

Example:

 
var request = new sn_ws.RESTMessageV2(
    'Customer API',
    'get_customer'
);

request.setStringParameter(
    'customerId',
    'CUST10001'
);

var response = request.execute();

gs.info(
    'Status = ' +
    response.getStatusCode()
);

gs.info(
    'Body = ' +
    response.getBody()
);
 

Expected result:

 
Status = 200
Body = {"id":"CUST10001","name":"ABC Corporation"}
 

Level 3 – Test the Business Scenario

Technical success is not enough.

Suppose the business requirement is:

When an approved ServiceNow request contains an Oracle employee number, retrieve employee information and populate the request.

Test:

  1. Create the ServiceNow request.
  2. Enter a valid employee number.
  3. Trigger the integration.
  4. Verify outbound request.
  5. Confirm Oracle API response.
  6. Verify ServiceNow field updates.
  7. Test an invalid employee number.
  8. Test an authentication failure.
  9. Test an unavailable endpoint.
  10. Test a slow endpoint.

This is how an implementation team discovers real integration problems rather than merely proving that the API works once.


Common RESTMessageV2 Errors and Troubleshooting

401 Unauthorized

Usually indicates an authentication problem.

Check:

  • Username/password
  • OAuth profile
  • OAuth token
  • Token scope
  • Authentication inheritance
  • API permissions

Do not immediately modify the script. First verify the REST Message authentication configuration.


403 Forbidden

Authentication succeeded, but the account may not have sufficient authorization.

Check the target application’s roles, scopes and permissions.


404 Not Found

Check:

  • Endpoint
  • API version
  • Resource path
  • Environment
  • Record identifier
  • URL variables

A common implementation mistake is mixing development and production URLs.


400 Bad Request

Usually indicates a request-format problem.

Check:

 
Content-Type
JSON structure
Required fields
Date format
Enumerated values
Query parameters
 

For example, these two payloads may not be equivalent to the target application:

 
{
  "employeeNumber": "10045"
}
 

and:

 
{
  "employee_number": 10045
}
 

The API contract determines which one is valid.


500 Internal Server Error

Do not automatically conclude that ServiceNow caused the problem.

First reproduce the exact request in an API client such as Postman, then compare:

  • Endpoint
  • Authentication
  • Headers
  • Body
  • Query parameters

If Postman succeeds but ServiceNow fails, compare the actual outbound request configuration.


Timeout

Review:

  • External API response time
  • ServiceNow HTTP timeout
  • Network connectivity
  • MID Server availability
  • Firewall rules
  • Target application performance

RESTMessageV2 supports setHttpTimeout() for controlling the amount of time the request waits for response data.

Example:

 
request.setHttpTimeout(10000);
 

This sets a 10-second timeout in milliseconds.


Debugging Outbound REST Calls

For difficult integration issues, increase logging temporarily.

RESTMessageV2 supports:

 
request.setLogLevel('all');
 

ServiceNow documents log levels including basic, elevated, and all, with outbound HTTP information available through the outbound HTTP request logging area.

Use detailed logging carefully in production because request and response information may contain sensitive business data.

A practical troubleshooting sequence is:

 
1. Verify endpoint
       ↓
2. Verify authentication
       ↓
3. Verify HTTP method
       ↓
4. Verify headers
       ↓
5. Verify request payload
       ↓
6. Check HTTP status
       ↓
7. Inspect response body
       ↓
8. Check ServiceNow outbound logs
       ↓
9. Check MID Server if applicable
       ↓
10. Compare with Postman/API client
 

RESTMessageV2 Best Practices

1. Separate configuration from code

Use REST Message records for:

  • Endpoint
  • Authentication
  • HTTP methods
  • Headers
  • Variables

Use scripts for:

  • Business logic
  • Dynamic values
  • Response processing
  • Error handling

2. Never hard-code credentials

Use authentication profiles rather than putting passwords inside Script Includes or Business Rules.


3. Avoid synchronous calls in high-volume transactions

If the business transaction does not need the external response immediately, consider asynchronous processing.

This is particularly important for:

  • Bulk record updates
  • Imports
  • High-volume Business Rules
  • Scheduled processing

4. Validate HTTP status codes

Do not assume that:

 
response.getStatusCode() == 200
 

is the only success condition.

A REST API may legitimately return:

 
200 OK
201 Created
202 Accepted
204 No Content
 

depending on the operation.


5. Handle malformed responses

Do not blindly execute:

 
JSON.parse(response.getBody());
 

without considering whether the provider returned JSON.

An error response might be HTML, plain text or another format.


6. Make integration failures traceable

A production integration should capture enough information to answer:

  • Which record triggered the integration?
  • Which API was called?
  • When was it called?
  • What was the HTTP status?
  • What business error was returned?
  • Should the transaction be retried?

Avoid storing credentials or unnecessarily sensitive payloads in custom logs.


7. Design retry behavior deliberately

Do not automatically retry every error.

For example:

ResponseTypical treatment
400Fix request; don’t blindly retry
401Refresh/fix authentication
403Fix authorization
404Validate endpoint/resource
429Consider controlled retry/backoff
500Controlled retry may be appropriate
TimeoutControlled retry may be appropriate

The exact retry strategy should depend on the external API’s contract.

ServiceNow’s current documentation notes that built-in configurable retry policies available through the IntegrationHub REST Step are not available through RESTMessageV2, meaning custom retry logic is required when using the scripted API.


RESTMessageV2 with Oracle Fusion Cloud

A common enterprise architecture is:

 
ServiceNow
   |
   | RESTMessageV2
   |
   v
Oracle Fusion Cloud
   |
   +-- HCM
   +-- ERP
   +-- SCM
   +-- Financials
 

For example, an organization could retrieve employee information from Oracle Fusion HCM, obtain financial information from Oracle Fusion Financials, or exchange supply-chain information with Oracle Fusion SCM.

Oracle’s 26A REST API documentation provides resource-specific API documentation, including endpoint paths, methods and supported operations.

The important implementation rule is to design the ServiceNow REST Message against the specific Fusion REST resource and API version required by the project instead of assuming that all Fusion REST endpoints behave identically.

For example:

 
ServiceNow Request
      |
      v
RESTMessageV2
      |
      v
OAuth 2.0
      |
      v
Oracle Fusion REST API
      |
      v
JSON Response
      |
      v
ServiceNow Transformation
 

If the integration involves Oracle Time and Labor, Oracle’s current documentation describes Time and Labor as supporting time reporting and transfer of time data to consumers such as payroll, project costing and external applications.

For an implementation team, that means the integration design should account not only for the REST call itself, but also for business validation, processing status and downstream consequences.


FAQ

1. What is RESTMessageV2 in ServiceNow?

RESTMessageV2 is ServiceNow’s server-side JavaScript API for sending outbound REST messages. It can invoke a configured REST Message or create the endpoint and HTTP method programmatically. It operates in the sn_ws namespace.

2. What is the difference between REST Message and RESTMessageV2?

A REST Message is the configuration record containing endpoint, authentication, HTTP methods, headers and variables.

RESTMessageV2 is the scripting API used to execute that configured REST message and process its response.

In a typical implementation:

 
REST Message = Configuration
RESTMessageV2 = Execution
RESTResponseV2 = Response Handling
 

3. Should I use execute() or executeAsync()?

Use execute() when the calling logic genuinely requires the immediate response and the external operation is appropriate for synchronous processing.

Use asynchronous processing when the transaction does not need to wait for the external system, particularly for longer-running or higher-volume integrations. ServiceNow provides specific guidance around the performance considerations of synchronous versus asynchronous outbound calls.


Summary

RESTMessageV2 is an important ServiceNow integration capability for developers building outbound REST integrations through server-side JavaScript. The most maintainable implementation pattern is to keep endpoint, authentication, HTTP methods and reusable variables in REST Message configuration while keeping business logic and response processing in Script Includes or other appropriate server-side components.

A production-ready RESTMessageV2 integration should address more than simply getting a 200 OK. It should include authentication design, variable handling, payload validation, response processing, error handling, timeout strategy, asynchronous processing where appropriate, logging, retry behavior and security.

When integrating ServiceNow with Oracle Fusion Cloud, the same principles apply. The ServiceNow side should consume the appropriate Oracle Fusion REST resource and API version, while the Oracle side should be designed according to the relevant Fusion Cloud business process and security model. Oracle’s 26A documentation provides the current REST API references for Fusion Cloud applications.

For additional Oracle documentation, refer to the Oracle Cloud Applications documentation and the Oracle Fusion Cloud Time and Labor implementation documentation where Time and Labor is part of the integration requirement.

For the ServiceNow side, the current RESTMessageV2 API reference and Outbound REST documentation are the primary references for API behavior and implementation details.


Share

Leave a Reply

Your email address will not be published. Required fields are marked *