How to use script include to import data from api to servicenow tables.

rahul16
Giga Guru

I want to create a scheduled job where the script hits an API to get the data in JSON and using that data I have to insert the data 

 

(function sample_http_request() {
    try {
        var request = new sn_ws.RESTMessageV2();
        request.setHttpMethod('get');
        request.setEndpoint('https://test.com/api/1/tests');
        request.setRequestHeader("Bearer", "[token]");
        var response = request.execute();
        var httpResponseStatus = response.getStatusCode();
        var httpResponseContentType = response.getHeader('Content-Type');
        var parser = new global.JSONParser();
        var parsed = {};
        var httpResponseBody;


        gs.debug("http response status_code: " + httpResponseStatus);
        gs.debug("http response content-type: " + httpResponseContentType);


        //  if request is successful then parse the response body
        if (httpResponseStatus == 200 && httpResponseContentType == 'application/json') {
            httpResponseBody = response.getBody();

            //  parse JSON string returned from request into a json object
            parsed = parser.parse(httpResponseBody);

            // iterate over JSON object only printing the id property of JSON objects in results array
            for (var i = 0; i < parsed.results.length; i++) {
                gs.print('id: ' + parsed.results[i].id)
            }
        }
    }
    catch (ex) {
        var message = ex.getMessage();
        gs.debug(message);
    }
})();
 
I tried this for testing to hit API but it's not working can anyone help me with a sample code to hit API and use that data to insert records in ServiceNow.
2 REPLIES 2

MD AQUIB KHAN
Giga Guru

Hi Rahul,

Please find the sample script to insert the record. My requirement was to insert the record in the incident table.

I have used business rule to trigger the integration. You can replicate the same as per your requirement.

(function executeRule(current, previous /*null when async*/) {

	try { 
var incnum =[];
 var r = new sn_ws.RESTMessageV2('Integration using  SCripted Rest API', 'Create Incident'); // get the scripted rest API from target;
// pass the payload : from source to target :
 r.setStringParameterNoEscape('description', current.getValue('description'));
 r.setStringParameterNoEscape('short_description', current.getValue('short_description'));
 r.setStringParameterNoEscape('category',current.getValue('category') );
 r.setStringParameterNoEscape('caller_id', current.getDisplayValue('caller_id'));
 r.setStringParameterNoEscape('contact_type', current.getValue('contact_type'));
 //r.setStringParameterNoEscape('assignment_group', current.getDisplayValue('assignment_group'));	
 r.setStringParameterNoEscape('assignment_group', 'b85d44954a3623120004689b2d5dd60a');
 r.setStringParameterNoEscape('subcategory', current.getValue('subcategory'));
 r.setStringParameterNoEscape('state', current.getDisplayValue('state'));
r.setStringParameterNoEscape('close_notes', current.getValue('close_notes'));
r.setStringParameterNoEscape('close_code', current.getValue('close_code'));
 r.setStringParameterNoEscape('priority', current.getValue('priority'));
r.setStringParameterNoEscape('number', current.getValue('number'));
//r.setStringParameterNoEscape('work_notes',gr1);// get all the worknotes 
//r.setStringParameterNoEscape('comments_and_work_notes', current.getValue('comments_and_work_notes'));
 var response = r.execute();
 var responseBody = response.getBody();	   //get Response Body        		
 var httpStatus = response.getStatusCode(); 
 var getBody = r.getRequestBody(); // get body
var obj =JSON.parse(responseBody);
incnum.push(obj.result.INCNumber); // get the response from the target and update in the work_notes .
gs.log('RESPONSE: ' +responseBody); 
gs.log('RESPOSE_BODY:' +getBody);
gs.log('Target Number:' + incnum);
gs.log(incnum ,'test');
gs.log(incnum + '','test1');


}
catch(ex) {
 var message = ex.message;
}
 current.work_notes = 'Target Incident Number :' + incnum;
 current.correlation_id = incnum + '';
 current.update();
})(current, previous);

Tony Chatfield1
Kilo Patron

Hi, with no clear details of your target environments expectations the forum can't provide specific response.
Testing as a background script in a PDI the only issue I encounter are specific to SNC expectations\requirements.
This is the format SNC will expect for authentication, but you will need to validate your target requirements and the best solution is normally to test\validate using a tool like Postman before mapping to a code based solution.

request.setRequestHeader("Authorization", "Bearer oneWhiteSpaceAndThenTheTokenString");

 

JSONParser() is depreciated, and I would not recommend using it for new code,

and the 'results' of your payload might be 'result' and you should confirm if you haven't already.

var responseBody = response.getBody();
var parsed = new global.JSON.parse(responseBody);
gs.info('responseBody ' + responseBody);

 

The correctness of response status code and content-type may also be platform specific, and I would validate or exclude the conditional check until you have the result of your code functioning.