class ServicePrincipalCollection
A collection class for managing Microsoft Graph Service Principal objects, providing methods to add, retrieve, and query service principals by various identifiers.
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/directory/serviceprincipals/collection.py
7 - 44
moderate
Purpose
ServicePrincipalCollection manages a collection of ServicePrincipal objects in Microsoft Graph API. It extends DeltaCollection to provide specialized methods for creating service principals and retrieving them by application ID, application object, or display name. This class serves as the primary interface for service principal operations in the Microsoft Graph SDK, handling the relationship between applications and their corresponding service principals in Azure AD.
Source Code
class ServicePrincipalCollection(DeltaCollection[ServicePrincipal]):
"""Service Principal's collection"""
def __init__(self, context, resource_path=None):
super(ServicePrincipalCollection, self).__init__(
context, ServicePrincipal, resource_path
)
def add(self, app_id):
"""
Create a new servicePrincipal object.
:param str app_id: The unique identifier for the associated application
"""
return super(ServicePrincipalCollection, self).add(appId=app_id)
def get_by_app_id(self, app_id):
"""Retrieves the service principal using appId.
:param str app_id: appId is referred to as Application (Client) ID, respectively, in the Azure portal
"""
return ServicePrincipal(self.context, AppIdPath(app_id, self.resource_path))
def get_by_app(self, app):
# type: (str|Application) -> ServicePrincipal
if isinstance(app, Application):
return_type = ServicePrincipal(self.context, parent_collection=self)
def _app_resolved():
return_type.set_property("appId", app.app_id)
app.ensure_properties(["appId"], _app_resolved)
return return_type
else:
return self.get_by_app_id(app)
def get_by_name(self, name):
# type: (str) -> ServicePrincipal
"""Retrieves the service principal using displayName."""
return self.single("displayName eq '{0}'".format(name))
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
DeltaCollection[ServicePrincipal] | - |
Parameter Details
context: The client context object that provides authentication and connection details for making API requests to Microsoft Graph. This is required for all API operations.
resource_path: Optional. The resource path in the Microsoft Graph API hierarchy where this collection resides. If not provided, defaults to the standard service principals endpoint. Used for constructing API request URLs.
Return Value
Instantiation returns a ServicePrincipalCollection object that can be used to manage service principals. Methods return: add() returns a new ServicePrincipal object; get_by_app_id() and get_by_app() return a ServicePrincipal instance; get_by_name() returns a single ServicePrincipal matching the display name.
Class Interface
Methods
__init__(self, context, resource_path=None)
Purpose: Initializes a new ServicePrincipalCollection instance with the provided context and optional resource path
Parameters:
context: The client context for API operationsresource_path: Optional resource path for the collection endpoint
Returns: None (constructor)
add(self, app_id: str) -> ServicePrincipal
Purpose: Creates a new service principal object in Azure AD for the specified application ID
Parameters:
app_id: The unique identifier (GUID) for the associated application, also known as Application (Client) ID in Azure portal
Returns: A ServicePrincipal object representing the newly created service principal
get_by_app_id(self, app_id: str) -> ServicePrincipal
Purpose: Retrieves an existing service principal using its application ID
Parameters:
app_id: The application (client) ID as shown in Azure portal, used to identify the service principal
Returns: A ServicePrincipal object with the specified app ID, configured with the appropriate resource path
get_by_app(self, app: str | Application) -> ServicePrincipal
Purpose: Retrieves a service principal using either an Application object or an application ID string, handling lazy loading of properties
Parameters:
app: Either an Application object or a string containing the application ID. If Application object is provided, its appId property will be resolved and used
Returns: A ServicePrincipal object associated with the provided application, with automatic property resolution if Application object is passed
get_by_name(self, name: str) -> ServicePrincipal
Purpose: Retrieves a service principal by its display name using OData filtering
Parameters:
name: The display name of the service principal to search for (exact match required)
Returns: A single ServicePrincipal object matching the display name, or raises an error if not found or multiple matches exist
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
context |
ClientContext | Inherited from parent class. The client context used for making API requests to Microsoft Graph | instance |
resource_path |
ResourcePath | Inherited from parent class. The API endpoint path for this collection in the Microsoft Graph hierarchy | instance |
Dependencies
office365
Required Imports
from office365.delta_collection import DeltaCollection
from office365.directory.applications.application import Application
from office365.directory.serviceprincipals.service_principal import ServicePrincipal
from office365.runtime.paths.appid import AppIdPath
Usage Example
from office365.graph_client import GraphClient
from office365.directory.serviceprincipals.service_principal_collection import ServicePrincipalCollection
# Initialize Graph client with credentials
client = GraphClient.with_client_secret(tenant_id, client_id, client_secret)
# Access service principals collection
service_principals = client.service_principals
# Add a new service principal by app ID
app_id = '12345678-1234-1234-1234-123456789abc'
new_sp = service_principals.add(app_id)
new_sp.execute_query()
# Get service principal by app ID
sp = service_principals.get_by_app_id(app_id)
sp.get().execute_query()
print(sp.display_name)
# Get service principal by display name
sp_by_name = service_principals.get_by_name('MyApp')
sp_by_name.get().execute_query()
# Get service principal from Application object
app = client.applications.get_by_id('app-object-id')
sp_from_app = service_principals.get_by_app(app)
sp_from_app.get().execute_query()
Best Practices
- Always call execute_query() after operations to commit changes to Microsoft Graph API
- Use get_by_app_id() when you have the application (client) ID from Azure portal
- Use get_by_name() for human-readable lookups, but note it may be slower than ID-based lookups
- When working with Application objects, use get_by_app() to automatically resolve the relationship
- Ensure proper Azure AD permissions are granted before attempting to create or modify service principals
- The context parameter must be properly authenticated before instantiating this collection
- Service principals are automatically created when an application is registered, so check existence before calling add()
- Use ensure_properties() pattern when working with related Application objects to handle lazy loading
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class ServicePrincipal 76.5% similar
-
class ApplicationServicePrincipal 73.3% similar
-
class ProvisioningServicePrincipal 70.5% similar
-
class GroupCollection 68.9% similar
-
class ApplicationCollection 68.4% similar