get all incidents number from caller_id via scripted rest api

Sneha39
Mega Guru

Hi,

I have to created scripted rest api ,To get all the incident number from caller_id .

Thanks in advance

1 ACCEPTED SOLUTION

antin_s
ServiceNow Employee
ServiceNow Employee

Hi Sneha,



The below script should work.



(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {




var jsonStr = {"incidents":[]};


var gr = new GlideRecord('incident');


gr.addQuery('caller_id',request.queryParams.caller_id);


gr.query();



while(gr.next()){


var incidentOb =   {};


incidentOb.number = gr.number + '';


incidentOb.short_description = gr.short_description + '';


jsonStr['incidents'].push(incidentOb);


}



return jsonStr;




})(request, response);



Hope this helps. Mark the answer as correct/helpful based on impact.



Thanks


Antin


View solution in original post

18 REPLIES 18

Shishir Srivast
Mega Sage

Hi Sneha,



Please try below code.



find_real_file.png


(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {


// implement resource here


var incidentnum={};


var writer = response.getStreamWriter(),


hdrs = {};


hdrs['Content-Type'] = 'application/json';


response.setStatus(200);


response.setHeaders(hdrs);


var gr = new GlideRecord('incident');


gr.addQuery('caller_id',request.pathParams.caller_id);


gr.query();


writer.writeString("{\"results\":[");


while(gr.next())


{


incidentnum.inc_number = gr.number + '';


writer.writeString(global.JSON.stringify(incidentnum));


gs.log(incidentnum.inc_number);


}


writer.writeString("]}");


})(request, response);



Result:


find_real_file.png


Hi Shishir,



I tried on rest api explorer but its not showing any response


find_real_file.png






Thanks


Please pass the sys_id in caller_id


antin_s
ServiceNow Employee
ServiceNow Employee

Hi Sneha,



As per Shishir's code, it is looking Caller's sys_id as the input for the variable 'caller_id' and not the User's name. If you pass sys_id, it will work.



If your requirement is to pass User's name only, you need to change the script to refer the 'name' field as follows.



gr.addQuery('caller_id.name',request.pathParams.caller_id);



Hope this helps. Mark the answer as correct/helpful based on impact.



Thanks


Antin