🔍 Code Extractor

class GroupCollection

Maturity: 48

A collection class for managing Microsoft Graph API Group resources, providing methods to create, retrieve, and manage groups including Microsoft 365 groups and Security groups.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/groups/collection.py
Lines:
7 - 68
Complexity:
moderate

Purpose

GroupCollection serves as a container and factory for Group objects in the Microsoft Graph API. It extends DeltaCollection to provide specialized functionality for creating different types of groups (Microsoft 365 and Security groups), retrieving groups by name, and provisioning groups with associated Microsoft Teams. This class handles the lifecycle of group resources including creation, querying, and team provisioning.

Source Code

class GroupCollection(DeltaCollection[Group]):
    """Group's collection"""

    def __init__(self, context, resource_path=None):
        super(GroupCollection, self).__init__(context, Group, resource_path)

    def add(self, group_properties):
        """
        Create a Group resource.
        You can create the following types of groups:
           - Microsoft 365 group (unified group)
           - Security group

        :param GroupProfile group_properties: Group properties
        """
        return_type = Group(self.context)
        self.add_child(return_type)
        qry = CreateEntityQuery(self, group_properties, return_type)
        self.context.add_query(qry)
        return return_type

    def create_m365(self, name, description=None, owner=None):
        """
        Creates a Microsoft 365 group.
        If the owners have not been specified, the calling user is automatically added as the owner of the group.
        :param str name: The display name for the group
        :param str description: An optional description for the group
        :param str owner: The group owner
        """
        params = GroupProfile(name, description, True, False, ["Unified"])
        return self.add(params)

    def create_security(self, name, description=None):
        """
        Creates a Security group
        :param str name: The display name for the group
        :param str description: An optional description for the group
        """
        params = GroupProfile(name, description, False, True, [])
        return self.add(params)

    def create_with_team(self, group_name):
        """
        Provision a new group along with a team.

        Note: After the group is successfully created, which can take up to 15 minutes,
        create a Microsoft Teams team using this method could throw an error since
        the group creation process might not be completed. For that scenario prefer submit the request to server via
        execute_query_retry instead of execute_query when using this method.
        :param str group_name: The display name for the group
        """

        def _after_group_created(return_type):
            # type: (Group) -> None
            return_type.add_team()

        return self.create_m365(group_name).after_execute(_after_group_created)

    def get_by_name(self, name):
        # type: (str) -> Group
        """Retrieves group by displayName"""
        return self.single("displayName eq '{0}'".format(name))

Parameters

Name Type Default Kind
bases DeltaCollection[Group] -

Parameter Details

context: The execution context object that manages API requests, authentication, and communication with the Microsoft Graph API. This context is passed to all child Group objects and used to execute queries.

resource_path: Optional string representing the API endpoint path for the group collection resource. If not provided, defaults to the standard groups endpoint. Used for constructing API request URLs.

Return Value

Instantiation returns a GroupCollection object that manages a collection of Group resources. Methods return Group objects (add, create_m365, create_security, create_with_team, get_by_name) that represent individual groups in the Microsoft Graph API. These Group objects are not immediately populated but are loaded when queries are executed via the context.

Class Interface

Methods

__init__(self, context, resource_path=None)

Purpose: Initializes a new GroupCollection instance with the provided context and optional resource path

Parameters:

  • context: The execution context for API operations
  • resource_path: Optional API endpoint path for the collection

Returns: None (constructor)

add(self, group_properties) -> Group

Purpose: Creates a new Group resource with the specified properties, supporting both Microsoft 365 and Security groups

Parameters:

  • group_properties: GroupProfile object containing the group configuration including name, description, mail settings, security settings, and group types

Returns: A Group object representing the newly created group (not yet committed to server until execute_query is called)

create_m365(self, name, description=None, owner=None) -> Group

Purpose: Creates a Microsoft 365 group (unified group) with the specified name and optional description

Parameters:

  • name: The display name for the group
  • description: Optional description for the group
  • owner: Optional group owner (if not specified, the calling user becomes the owner)

Returns: A Group object representing the newly created Microsoft 365 group

create_security(self, name, description=None) -> Group

Purpose: Creates a Security group with the specified name and optional description

Parameters:

  • name: The display name for the security group
  • description: Optional description for the security group

Returns: A Group object representing the newly created security group

create_with_team(self, group_name) -> Group

Purpose: Provisions a new Microsoft 365 group along with an associated Microsoft Teams team

Parameters:

  • group_name: The display name for the group and team

Returns: A Group object with an associated team (requires execute_query_retry for reliability due to potential delays in group provisioning)

get_by_name(self, name) -> Group

Purpose: Retrieves a single group by its display name using OData filtering

Parameters:

  • name: The display name of the group to retrieve

Returns: A Group object matching the specified display name (requires execute_query to load data)

Attributes

Name Type Description Scope
context ClientContext The execution context inherited from parent class, used for managing API requests and authentication instance
resource_path str or None The API endpoint path for this collection, inherited from parent class instance

Dependencies

  • office365

Required Imports

from office365.delta_collection import DeltaCollection
from office365.directory.groups.group import Group
from office365.directory.groups.profile import GroupProfile
from office365.runtime.queries.create_entity import CreateEntityQuery

Usage Example

from office365.graph_client import GraphClient
from office365.directory.groups.collection import GroupCollection

# Authenticate and get context
client = GraphClient(credentials)
groups = client.groups  # GroupCollection instance

# Create a Microsoft 365 group
m365_group = groups.create_m365(
    name="Marketing Team",
    description="Marketing department collaboration"
)
client.execute_query()
print(f"Created group: {m365_group.id}")

# Create a security group
sec_group = groups.create_security(
    name="IT Admins",
    description="IT administrators security group"
)
client.execute_query()

# Create group with team (use retry for reliability)
team_group = groups.create_with_team("Project Alpha")
client.execute_query_retry()

# Retrieve group by name
group = groups.get_by_name("Marketing Team")
client.execute_query()
print(f"Found group: {group.display_name}")

Best Practices

  • Always call context.execute_query() or context.execute_query_retry() after creating or modifying groups to commit changes to the server
  • Use execute_query_retry() instead of execute_query() when calling create_with_team() as group creation can take up to 15 minutes and may fail initially
  • The add() method accepts a GroupProfile object for fine-grained control over group properties, while create_m365() and create_security() provide convenient shortcuts
  • Group objects returned by creation methods are not fully populated until execute_query() is called
  • Use after_execute() callbacks for operations that depend on successful group creation, as demonstrated in create_with_team()
  • The get_by_name() method uses OData filtering and requires execute_query() to retrieve the actual group data
  • Ensure the authenticated user has appropriate permissions (Group.ReadWrite.All) before attempting group creation
  • For Microsoft 365 groups, if no owner is specified, the calling user is automatically added as the owner

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class Group 72.4% similar

    Represents an Azure Active Directory (Azure AD) group, which can be an Office 365 group or a security group, providing methods to manage group operations, memberships, and associated resources.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/groups/group.py
  • class UserCollection 71.9% similar

    UserCollection is a specialized collection class for managing User objects in Microsoft 365/Office 365 directory services, providing methods to retrieve, create, and manage users with delta query support.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/users/collection.py
  • class GroupCollection_v1 71.8% similar

    Represents a collection of Group resources.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/principal/groups/collection.py
  • class DeltaCollection 70.5% similar

    A specialized collection class for handling delta queries in Microsoft Graph API, allowing retrieval of newly created, updated, or deleted entities (changes) with filtering capabilities.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/delta_collection.py
  • class ServicePrincipalCollection 68.9% similar

    A collection class for managing Microsoft Graph Service Principal objects, providing methods to add, retrieve, and query service principals by various identifiers.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/serviceprincipals/collection.py
← Back to Browse