Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Scripted REST API Response returned as "Undefined"

rohit121
Kilo Contributor

Hi Folks,

Have created a scripted rest API which takes in a company sys_id as input and is supposed to return all the assignment group names and member count (for the respective groups) tagged under the company. But currently I am getting back no responses once I test it through the API explorer.

Below is the Get resource code I have implemented. 

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

// implement resource here
var clientID = request.pathParams.client_id;
gs.log('client id:' + clientID);
var writer = response.getStreamWriter();
var cnt1 = 0;
var hdrs = {};
hdrs['Content-Type'] = 'application/json';
response.setStatus(200);
response.setHeaders(hdrs);
//start building the JSON string
writer.writeString("{\"results\":[");

//query comapny table for sys_id validation
var comp = new GlideRecord('core_company');
comp.addQuery('sys_id','=',clientID);
comp.query();

cnt1 = comp.getRowCount();
gs.log("company count:" + cnt1);
if(cnt1== 0){
writer.writeString("Error: Invalid Client ID");

}
else{
writer.writeString(global.JSON.stringfy("valid Client ID"));
var grp = new GlideRecord('sys_user_group');
grp.addQuery('company','=',clientID);
//grp.addActiveQuery();
grp.query();



var cnt2 = grp.getRowCount();
gs.log('group count:' + cnt2);
if(cnt2==0){
writer.writeString(global.JSON.stringfy("No group is associated with the specific client"));
}
else{
while(grp.next()){
var groupObj = {};
var grpm = new GlideAggregate('sys_user_grmember');
grpm.addQuery('group',grp.sys_id);
grpm.addAggregate('COUNT');
grpm.query();
var grpMembers = 0;
if(grpm.next()){
grpMembers = grpm.getAggregate('COUNT');
}
groupObj.groupName = grp.name + '';
groupObj.groupID = grp.sys_id + '';
groupObj.groupMembers = grpMembers;
writer.writeString(global.JSON.stringfy(groupObj));
if(grp.hasNext()){
writer.writeString(",");
}
}
}
//close the response object
writer.writeString("]}");
}

})(request, response);

Let me know if someone also faced something similar.

7 REPLIES 7

Hi Rohit,

Why are you using writer object and not directly setting it into json object and then use response.setBody(jsonObj);

Regards

Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Ashutosh Munot1
Kilo Patron
Kilo Patron

HI,

Can you try using queryParms instead of this var clientID = request.pathParams.client_id;

 

Meaning use this: var clientID = request.queryParams.client_id;

 

Thanks,
Ashutosh Munot

Thanks for the reply Ashutosh. Have configured my API to take in the client_id from the path param. So it has to be the 

request.pathParams.client_id.

GET https://mydev.service-now.com/api/amspa/company_groups_and_memebers_count/{client_id}