Calling REST message from widget

kiri265
Kilo Explorer

I am not able get information regarding how to call Outbound REST message from widget Please help

3 REPLIES 3

ChrisBurks
Giga Sage

If you're talking about using the ServiceNow Outbound REST Message then you would follow the documentation on scripting outbound rest messages in the server script of the widget:


Scripting outbound REST



Example using the OOB Yahoo Finance endpoint that is setup in the Outbound REST Message application using the "get" method:


var r = new sn_ws.RESTMessageV2('Yahoo Finance', 'get');


r.setStringParameter('symbol', 'GOOG');


var response = r.execute();


var responseBody = response.getBody();


var httpStatus = response.getStatusCode();




Example building a REST call from scratch without the use of the Outbound REST Message application using a "post" method and basic auth:



var method = "post";


var endpoint = 'https://www.your_endpoint_'


  var rm = new sn_ws.RESTMessageV2();


  rm.setHttpMethod(method);


  rm.setEndpoint(endpoint);


  var body = { some JSON stuff };


  rm.setRequestHeader("Content-type", "application/json");


  rm.setRequestBody(body);


  var response = rm.execute();


  var responseBody = new JSON().decode(response.getBody());





---------


If you want to use an xmlhttprequest call from the client controller section of the widget then you would just do the same as you would a normal angularjs application by injecting $http into the client controller:


AngularJS



function($http){


      $http.get('url').then(function(response){


                          console.log(response);


      });



      var options = {


                      method: 'POST',


                      url: 'http://your.endpoint',


                      data: { data stuff in here },


                      headers: {


                                  'Content-Type': 'application/json;charset=UTF-8'


                      };



        $http(options).then(function(response){


                      console.log(response);


        });


}


strawberrybeard
Kilo Contributor

Kiran, I actually recently put up a post on how to do this. It can be found here How to use a REST API with RESTMessageV2 in Service Portal. I hope this helps out.


Abhijeet Upadhy
Tera Expert

Hello Kiri

 

Use this call back timeout code to wait for the response till the "response_back" variable gets a value.

 

Script:

$http(options).then(function(response){

                      var response_back = response;

        });

$scope.call_back_function();

 

$scope.call_back_function= function()
{
if(response_back == "")
{
$window.setTimeout($scope.call_back_function, 100);
}
else

{

//use response_back here

}

 

Thanks

Abhijeet Upadhyay