class UserCollection
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.
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/users/collection.py
7 - 29
moderate
Purpose
This class serves as a container and manager for User objects within the Office 365 directory. It extends DeltaCollection to provide delta query capabilities for tracking changes to users. The class enables operations such as retrieving users by principal name, creating new users, and managing the collection of users with proper context and resource path handling. It acts as an intermediary between the application and the Office 365 API for user management operations.
Source Code
class UserCollection(DeltaCollection[User]):
"""User's collection"""
def __init__(self, context, resource_path=None):
super(UserCollection, self).__init__(context, User, resource_path)
def get_by_principal_name(self, name):
"""
Retrieves User by principal name
:param str name: User principal name
"""
return User(self.context, ResourcePath(name, self.resource_path))
def add(self, user_properties):
"""Create a new user.
:type user_properties: office365.directory.users.profile.UserProfile
"""
return_type = User(self.context)
qry = CreateEntityQuery(self, user_properties, return_type)
self.context.add_query(qry)
self.add_child(return_type)
return return_type
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
DeltaCollection[User] | - |
Parameter Details
context: The execution context object that manages API communication, authentication, and request handling for Office 365 operations. This context is passed to all child User objects and queries.
resource_path: Optional. The resource path string or object that specifies the API endpoint location for this user collection. If None, a default path will be used. This path is used to construct URLs for API requests.
Return Value
Instantiation returns a UserCollection object that manages a collection of User objects. The get_by_principal_name method returns a User object representing the user with the specified principal name. The add method returns a newly created User object that will be populated after the query executes.
Class Interface
Methods
__init__(self, context, resource_path=None)
Purpose: Initializes a new UserCollection instance with the provided context and optional resource path
Parameters:
context: The execution context for API operationsresource_path: Optional resource path for the collection endpoint
Returns: None (constructor)
get_by_principal_name(self, name: str) -> User
Purpose: Retrieves a User object by their principal name (email address)
Parameters:
name: The user principal name (UPN) string, typically in email format (e.g., 'user@domain.com')
Returns: A User object representing the user with the specified principal name. The object is created immediately but data must be loaded via context.load() and context.execute_query()
add(self, user_properties: UserProfile) -> User
Purpose: Creates a new user in the directory with the specified properties
Parameters:
user_properties: A UserProfile object containing the properties for the new user (userPrincipalName, displayName, mailNickname, accountEnabled, passwordProfile, etc.)
Returns: A User object representing the newly created user. The object is added to the collection and will be populated with server-generated properties (like id) after context.execute_query() is called
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
context |
ClientContext | The execution context inherited from parent class, used for API communication and query management | instance |
resource_path |
ResourcePath | The resource path for this collection, inherited from parent class, specifying the API endpoint location | instance |
Dependencies
office365
Required Imports
from office365.delta_collection import DeltaCollection
from office365.directory.users.user import User
from office365.runtime.paths.resource_path import ResourcePath
from office365.runtime.queries.create_entity import CreateEntityQuery
Usage Example
from office365.directory.users.user_collection import UserCollection
from office365.directory.users.profile import UserProfile
from office365.runtime.client_context import ClientContext
# Assume context is already authenticated
context = ClientContext.connect_with_credentials(tenant, client_id, client_secret)
# Create user collection instance
user_collection = UserCollection(context, resource_path='users')
# Retrieve a user by principal name
user = user_collection.get_by_principal_name('john.doe@contoso.com')
context.load(user)
context.execute_query()
print(user.display_name)
# Create a new user
user_profile = UserProfile()
user_profile.user_principal_name = 'jane.smith@contoso.com'
user_profile.display_name = 'Jane Smith'
user_profile.mail_nickname = 'janesmith'
user_profile.account_enabled = True
user_profile.password_profile = {'password': 'TempPass123!', 'force_change_password_next_sign_in': True}
new_user = user_collection.add(user_profile)
context.execute_query()
print(f'Created user: {new_user.id}')
Best Practices
- Always ensure the context object is properly authenticated before creating a UserCollection instance
- Call context.execute_query() after add() or other mutation operations to commit changes to the server
- Use context.load() before context.execute_query() when retrieving user properties to ensure data is fetched
- Handle exceptions that may occur during API calls, especially authentication and permission errors
- When creating users with add(), ensure UserProfile contains all required fields (userPrincipalName, displayName, mailNickname, accountEnabled, passwordProfile)
- The get_by_principal_name method creates a User object immediately but doesn't fetch data until context.load() and context.execute_query() are called
- UserCollection inherits delta query capabilities from DeltaCollection, allowing efficient tracking of changes over time
- Resource paths are automatically managed; typically you don't need to specify resource_path unless working with nested collections
- The add method adds the new user to the collection's children automatically, maintaining proper parent-child relationships
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class ApplicationCollection 74.4% similar
-
class UserActivityCollection 72.8% similar
-
class ExternalUserCollection 72.3% similar
-
class GroupCollection 71.9% similar
-
class ContactCollection 69.4% similar