How to call REST Massage in Script-Background of ServiceNow

haruna naka
Tera Contributor

I made JSON on OpenWeatherMap like below and I tried to call REST Massage in Script-Background of ServiceNow by entering JSON's script below and clicking "Run Script".However I couldn't call REST Massage.

If someone knows solution, please let me know.Thanks.

[JSON]   

try {
var r = new sn_ws.RESTMessageV2('application name, 'title');
r.setStringParameterNoEscape('timezoon', '322440');
var response = r.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
}
catch(ex) {
var message = ex.message;
}

 

1 ACCEPTED SOLUTION

Marc Mouries
ServiceNow Employee
ServiceNow Employee

you need to set the end point. 

 

(function execute() {
    var restMessage = new sn_ws.RESTMessageV2();
    restMessage.setEndpoint('https://api.openweathermap.org/data/2.5/weather?zip='+ YOUR_ZIP_CODE +'&appid='+ YOUR_KEY);
    restMessage.setHttpMethod('get');
    var response = restMessage.execute();
    var httpResponseStatus = response.getStatusCode();

    if (httpResponseStatus == 200) {
       var responseBody = response.getBody();
       var responseObject = JSON.parse(responseBody);

    // do what you need to do with the response

    return body;
}
})()

View solution in original post

7 REPLIES 7

Hitoshi Ozawa
Giga Sage
Giga Sage

Hi Haruna,

I've created a REST Message and ran the script.

1. REST Message. Created a REST Message named "OpenWeatherMap" with HTTP Method name "GET" (changed the default method name).

find_real_file.png

 Executed the following script. Note that parameters to RESTMessageV2 are REST Message name and HTTP Method name that I've created above.

try {
    var r = new sn_ws.RESTMessageV2('OpenWeatherMap', 'GET');
    r.setStringParameterNoEscape('timezone', '322440');
    var response = r.execute();
    var responseBody = response.getBody();
    var httpStatus = response.getStatusCode();
    gs.info(responseBody);
} catch (ex) {
    var message = ex.message;
}

Execution result:

find_real_file.png

Thanks a lot!

The complete step is as follows.

  1. In the "Endpoint", use "${appid}" instead of hardcoding the application id in the url. Hardcoding app id or url in script is a bad practice.
    find_real_file.png
  2. Click on "Auto-generate variables" under "Related Links". This will generate a new record under "Variable Substitution".
    find_real_file.png
  3. Click "appid" and enter application id in the "Test value" field.
    find_real_file.png
  4. Save the setting and click on "Test" link under Related Links to test endpoint.
    find_real_file.png

https://docs.servicenow.com/bundle/sandiego-application-development/page/integrate/outbound-rest/con...