Get list of users having a specific role using REST (Tables) APIs

krishh_ps
Kilo Contributor

Hi there,

Using Table APIs, how to get the list of all users under a role. Example: I need to get all users list who are having "admin" role.

Looking forward for suggestions/ solution for this.

1 ACCEPTED SOLUTION

Prateek kumar
Mega Sage

Hello

Your URL Should be 

https://yourinstancename.service-now.com/api/now/table/sys_user_has_role?role=your_role_name


Please mark my response as correct and helpful if it helped solved your question.
-Thanks

View solution in original post

3 REPLIES 3

Prateek kumar
Mega Sage

Hello

Your URL Should be 

https://yourinstancename.service-now.com/api/now/table/sys_user_has_role?role=your_role_name


Please mark my response as correct and helpful if it helped solved your question.
-Thanks

Aman Gurram
Giga Expert

Please take a look at the below example and make a function call with the required role and sys_user Column name.The function getUsersWithRole should return you all the users who have the required role.

//Call the below function with the ROLE and one of the columns on sys_user table. 
//The below function call returns all the userNames of the users who have the role "Test_Role"
var users = getUsersWithRole("Test_Role","user_name"); 
gs.print(users); //Array of Users with required role

function getUsersWithRole(role,user_column)
{
	var users = [];
	var userRoleJson = makeAPICall("https://***.service-now.com/api/now/table/sys_user_has_role?role="+role);
	for(var i=0; i<userRoleJson.result.length ;i++)
	{
		var usersJson = makeAPICall(userRoleJson.result[i].user.link);
		users.push(usersJson.result[user_column]);
	}
	return users;
}
function makeAPICall(endPoint)
{
	try {
		var rest = new sn_ws.RESTMessageV2();
		rest.setEndpoint(endPoint);
		rest.setHttpMethod("get");
		//This below user needs to have access to sys_user_role table and sys_user table
		rest.setBasicAuth("Test_User","Test_123"); 
		var response = rest.execute();
		var responseBody = response.getBody();
		var httpStatus = response.getStatusCode();
		if(httpStatus==200){
			return JSON.parse(responseBody);
		}
	}
	catch(ex) {
		var message = ex.getMessage();
	}
	
}

Thanks for the suggestion.

 

However, for my requirement, the first API call looks enough.