user989988
user989988

Reputation: 3736

Get ONLY the count of members of 'GROUP' type from an AAD group using Graph API

Is there a Graph API to get the count of members of a specific type from AAD group? For example, consider the following AAD group:

enter image description here

This group contains 2 members of type 'Group'. Is there a Graph API to get that count (2)? Or should I get all members from the group and do some filtering to get the members of 'Group' type as follows:

var groups = new List<Guid>();
var response = await _graphServiceClient
           .Groups[groupId]
           .TransitiveMembers
           .Request()
           .Top(999)
           .GetAsync();

groups.AddRange(ToGroups(response));

private IEnumerable<Guid> ToGroups(IEnumerable<DirectoryObject> members)
{
            foreach (var directoryObj in fromGraph)
            {
                switch (directoryObj)
                {                    
                    case Group group:
                        yield return Guid.Parse(group.Id);
                        break;
                    default:
                        break;
                }
            }
}

Upvotes: 1

Views: 689

Answers (1)

user2250152
user2250152

Reputation: 20635

You can cast microsoft.graph.group type like this

GET https://graph.microsoft.com/v1.0/groups/{groupId}/transitiveMembers/microsoft.graph.group

To retrieve the count the query will be

GET https://graph.microsoft.com/v1.0/groups/{groupId}/transitiveMembers/microsoft.graph.group/$count

To achieve this in C# I would create request, add casting and count parameter to request URL. Then create http request message and sent this message, read the response and parse the response as integer.

var requestUrl = _graphServiceClient.Groups[groupId].TransitiveMembers.Request().RequestUrl;

// add casting and count query
requestUrl = $"{requestUrl}/microsoft.graph.group/$count";

// Create the request message
var hrm = new HttpRequestMessage(HttpMethod.Get, requestUrl);
// $count requires header ConsistencyLevel
hrm.Headers.Add("ConsistencyLevel", "eventual");

// Authenticate (add access token) our HttpRequestMessage
await _graphServiceClient.AuthenticationProvider.AuthenticateRequestAsync(hrm);

// Send the request and get the response.
var response = await _graphServiceClient.HttpProvider.SendAsync(hrm);

// read the content and parse it as an integer
var content = await response.Content.ReadAsStringAsync();
var groupCount = int.Parse(content);

Upvotes: 2

Related Questions