### Install Microsoft Graph Beta SDK for Python Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/README.md Use pip to install the Microsoft Graph Beta SDK for Python. Installation may take a few minutes due to the package size. Enable long paths in your environment if you encounter installation errors. ```python pip install msgraph-beta-sdk ``` -------------------------------- ### Install msgraph-core and msgraph-beta-sdk Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/UPGRADING.md Install the older msgraph-core and the new msgraph-beta-sdk packages using pip. ```python # msgraph-core pip install msgraph-core # msgraph-sdk pip install msgraph-beta-sdk ``` -------------------------------- ### Fetch a User with ClientSecretCredential Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/README.md Asynchronously fetch a user's details using the GraphServiceClient authenticated with ClientSecretCredential. This example demonstrates making a GET request to the users endpoint. ```python import asyncio from azure.identity.aio import ClientSecretCredential from msgraph_beta import GraphServiceClient credential = ClientSecretCredential( 'tenant_id', 'client_id', 'client_secret' ) scopes = ['https://graph.microsoft.com/.default'] client = GraphServiceClient(credential, scopes=scopes) async def get_user(): user = await client.users.by_user_id('userPrincipalName').get() if user: print(user.display_name) asyncio.run(get_user()) ``` -------------------------------- ### Get All Users in a Tenant Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/users_samples.md Retrieves a list of all users in the tenant. This sample iterates through the users and prints their ID, display name, and email. ```python async def get_users(): users = await client.users.get() if users and users.value: for user in users.value: print(user.id, user.display_name, user.mail) asyncio.run(get_users()) ``` -------------------------------- ### Compare Request Methods: msgraph-core vs. msgraph-beta-sdk Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/UPGRADING.md Illustrates the difference in making GET requests for user messages between the older msgraph-core and the new msgraph-beta-sdk using a fluent builder pattern. ```python # msgraph-core resp =client.get('/users/userId/messages') # msgraph-beta-sdk req = client.users_by_id('userId').messages().get() resp = asyncio.run(req) ``` -------------------------------- ### Get All Users in a Tenant Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/users_samples.md Retrieves a list of all users within the Microsoft 365 tenant. This operation corresponds to the GET /users endpoint. ```APIDOC ## GET /users ### Description Retrieves a collection of user objects, typically representing all users in a tenant. ### Method GET ### Endpoint /users ### Parameters None ### Request Example ```python async def get_users(): users = await client.users.get() if users and users.value: for user in users.value: print(user.id, user.display_name, user.mail) asyncio.run(get_users()) ``` ### Response #### Success Response (200) - **value** (array) - A collection of user objects. - **id** (string) - The unique identifier for the user. - **display_name** (string) - The user's display name. - **mail** (string) - The user's email address. ``` -------------------------------- ### List All Groups in the Tenant Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Retrieves a list of all groups present in the tenant. This operation corresponds to the GET /groups endpoint. ```APIDOC ## GET /groups ### Description Retrieves a list of all groups in the tenant. ### Method GET ### Endpoint /groups ### Response #### Success Response (200) - **value** (array) - A collection of group objects. ### Request Example ```python async def get_groups(): groups = await client.groups.get() if groups and groups.value: for group in groups.value: print(group.id, group.display_name) asyncio.run(get_groups()) ``` ``` -------------------------------- ### Get Drive Root Folder Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/drives_samples.md Retrieves the root folder of a specified drive. ```APIDOC ## GET THE ROOT FOLDER OF THE DRIVE (GET /drives/{id}/root) ### Description Retrieves the root folder object for a given drive. ### Method GET ### Endpoint /drives/{id}/root ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the drive. ### Request Example ```python async def get_drive_root(): root = await client.drives.by_drive_id('DRIVE_ID').root.get() if root: print(root.id, root.name, root.folder.child_count, root.root, root.size) asyncio.run(get_drive_root()) ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the root folder. - **name** (string) - The name of the root folder (usually 'root'). - **folder** (object) - Contains folder-specific properties like `child_count`. - **child_count** (integer) - The number of items directly within this folder. - **root** (boolean) - Indicates if this is the root folder (should be true). - **size** (integer) - The total size of the folder in bytes. #### Response Example ```json { "id": "ROOT_FOLDER_ID", "name": "root", "folder": { "child_count": 50 }, "root": true, "size": 10485760 } ``` ``` -------------------------------- ### Get a Group Drive Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Retrieves details for a specific drive within a group. This operation corresponds to the GET /groups/{id}/drives/{id} endpoint. ```APIDOC ## GET /groups/{id}/drives/{id} ### Description Retrieves details for a specific drive belonging to a group. ### Method GET ### Endpoint /groups/{id}/drives/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the group. - **id** (string) - Required - The unique identifier of the drive. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the drive. - **drive_type** (string) - The type of the drive. - **name** (string) - The name of the drive. - **web_url** (string) - The URL of the drive. - **items** (array) - A collection of items within the drive. ### Request Example ```python async def get_group_drive(): drive = await client.groups.by_group_id( 'GROUP_ID' ).drives.by_drive_id( 'DRIVE_ID' ).get() if drive: print(drive.id, drive.drive_type, drive.name, drive.web_url, drive.items) asyncio.run(get_group_drive()) ``` ``` -------------------------------- ### Get Drive by ID Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/drives_samples.md Fetches a specific drive using its unique ID. Displays the drive's details including ID, type, name, description, and web URL. ```python async def get_drive(): drive = await client.drives.by_drive_id('DRIVE_ID').get() if drive: print(drive.id, drive.drive_type, drive.name, drive.description, drive.web_url) asyncio.run(get_drive()) ``` -------------------------------- ### Get Drive by ID Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/drives_samples.md Retrieves a specific drive using its unique identifier. ```APIDOC ## GET DRIVE BY ID (GET /drives/{id}) ### Description Retrieves the details of a specific drive identified by its ID. ### Method GET ### Endpoint /drives/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the drive. ### Request Example ```python async def get_drive(): drive = await client.drives.by_drive_id('DRIVE_ID').get() if drive: print(drive.id, drive.drive_type, drive.name, drive.description, drive.web_url) asyncio.run(get_drive()) ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the drive. - **drive_type** (string) - The type of the drive. - **name** (string) - The name of the drive. - **description** (string) - A description of the drive. - **web_url** (string) - The URL to access the drive. #### Response Example ```json { "id": "DRIVE_ID", "drive_type": "personal", "name": "OneDrive", "description": "User's personal OneDrive", "web_url": "https://onedrive.live.com/" } ``` ``` -------------------------------- ### Get a Specific Group Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Retrieves details for a specific group identified by its ID. This operation corresponds to the GET /groups/{id} endpoint. ```APIDOC ## GET /groups/{id} ### Description Retrieves details for a specific group using its unique identifier. ### Method GET ### Endpoint /groups/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the group. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the group. - **display_name** (string) - The name of the group. - **description** (string) - The description of the group. - **group_types** (array) - The types of the group. - **security_enabled** (boolean) - Indicates if the group is security-enabled. ### Request Example ```python async def get_group(): group = await client.groups.by_group_id('GROUP_ID').get() if group: print(group.id, group.display_name, group.description, group.group_types, group.security_enabled) asyncio.run(get_group()) ``` ``` -------------------------------- ### Get Children of Root Folder Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/drives_samples.md Retrieves a list of items directly within the root folder of a specified drive. ```APIDOC ## GET ITEMS IN THE ROOT FOLDER OF THE DRIVE (GET drives/{id}/items/root/children) ### Description Retrieves a list of items (files and folders) that are direct children of the root folder within a specified drive. ### Method GET ### Endpoint /drives/{id}/items/root/children ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the drive. ### Request Example ```python async def get_drive(): items = await client.drives.by_drive_id('DRIVE_ID').items.by_drive_item_id('root').children.get() if items and items.value: for item in items.value: print(item.id, item.name, item.size, item.folder, item.file) asyncio.run(get_drive()) ``` ### Response #### Success Response (200) - **value** (array) - A collection of item objects within the root folder. - **id** (string) - The unique identifier for the item. - **name** (string) - The name of the item. - **size** (integer) - The size of the item in bytes. - **folder** (object) - Properties of the item if it is a folder. - **file** (object) - Properties of the item if it is a file. #### Response Example ```json { "value": [ { "id": "ITEM_ID_IN_ROOT_1", "name": "Report.pdf", "size": 20480, "file": {} }, { "id": "SUBFOLDER_ID_1", "name": "Projects", "size": 0, "folder": {} } ] } ``` ``` -------------------------------- ### Get a Specific User Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/users_samples.md Retrieves the details of a specific user identified by their ID or User Principal Name. This operation corresponds to the GET /users/{id | userPrincipalName} endpoint. ```APIDOC ## GET /users/{id | userPrincipalName} ### Description Retrieves a specific user object based on their unique identifier or User Principal Name (UPN). ### Method GET ### Endpoint /users/{id | userPrincipalName} ### Parameters #### Path Parameters - **id | userPrincipalName** (string) - Required - The unique identifier (GUID) or User Principal Name (UPN) of the user. ### Request Example ```python async def get_user(): user = await client.users.by_user_id('USER_ID').get() if user: print(user.user_principal_name, user.display_name, user.id) asyncio.run(get_user()) ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **user_principal_name** (string) - The User Principal Name (UPN) of the user. - **display_name** (string) - The user's display name. ``` -------------------------------- ### Get Children of Root Folder Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/drives_samples.md Lists the direct children (items and folders) within the root folder of a specified drive. Outputs item details. ```python async def get_drive(): items = await client.drives.by_drive_id('DRIVE_ID').items.by_drive_item_id('root').children.get() if items and items.value: for item in items.value: print(item.id, item.name, item.size, item.folder, item.file) asyncio.run(get_drive()) ``` -------------------------------- ### Get a Specific User by ID Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/users_samples.md Fetches details for a single user identified by their ID. The output includes the user's principal name, display name, and ID. ```python async def get_user(): user = await client.users.by_user_id('USER_ID').get() if user: print(user.user_principal_name, user.display_name, user.id) asyncio.run(get_user()) ``` -------------------------------- ### Get User Messages with Query Parameters Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/general_samples.md Retrieves user messages, applying query parameters like 'select', 'skip', and 'top' for filtering and pagination. This is configured via MessagesRequestBuilderGetQueryParameters. ```python from msgraph_beta.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder async def get_5_user_messages(): query_params = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters( select=['subject', 'from'], skip = 2, top=5 ) request_config = MessagesRequestBuilder.MessagesRequestBuilderGetRequestConfiguration( query_parameters=query_params ) messages = await (client.users.by_user_id('USER_ID') .messages .get(request_configuration=request_config)) if messages and messages.value: for msg in messages.value: print(msg.subject) asyncio.run(get_5_user_messages()) ``` -------------------------------- ### List All Group Drives Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Retrieves a list of all drives associated with a group. This operation corresponds to the GET /groups/{id}/drives endpoint. ```APIDOC ## GET /groups/{id}/drives ### Description Retrieves a list of all drives associated with a specified group. ### Method GET ### Endpoint /groups/{id}/drives ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the group. ### Response #### Success Response (200) - **value** (array) - A collection of drive objects. ### Request Example ```python async def get_group_drives(): drives = await client.groups.by_group_id('GROUP_ID').drives.get() if drives and drives.value: for drive in drives.value: print(drive.id, drive.name) asyncio.run(get_group_drives()) ``` ``` -------------------------------- ### Get Drive Root Folder Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/drives_samples.md Retrieves the root folder of a specified drive. Prints the root folder's ID, name, child count, and size. ```python async def get_drive_root(): root = await client.drives.by_drive_id('DRIVE_ID').root.get() if root: print(root.id, root.name, root.folder.child_count, root.root, root.size) asyncio.run(get_drive_root()) ``` -------------------------------- ### Get User Messages with Custom Headers Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/general_samples.md Fetches user messages while setting custom request headers, such as 'Prefer' for content type, using a RequestConfiguration object. ```python from msgraph_beta.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder async def get_user_messages(): request_config = MessagesRequestBuilder.MessagesRequestBuilderGetRequestConfiguration() request_config.headers.add('Prefer', 'outlook.body-content-type="text"') messages = await (client.users.by_user_id('USER_ID') .messages .get(request_configuration=request_config)) if messages and messages.value: for msg in messages.value: print(msg.subject, msg.id, msg.from_) asyncio.run(get_user_messages()) ``` -------------------------------- ### Get Drive Item by ID Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/drives_samples.md Retrieves a specific item (file or folder) within a drive using its ID. ```APIDOC ## GET AN ITEM IN THE DRIVE (GET /drives/{id}/items/{id}) ### Description Retrieves the details of a specific item within a drive, identified by both the drive ID and the item ID. ### Method GET ### Endpoint /drives/{id}/items/{itemId} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the drive. - **itemId** (string) - Required - The unique identifier of the item within the drive. ### Request Example ```python async def get_drive_item(): item = await client.drives.by_drive_id('DRIVE_ID').items.by_drive_item_id('ITEM_ID').get() if item: print(item.id, item.name, item.size, item.folder, item.file) asyncio.run(get_drive_item()) ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the item. - **name** (string) - The name of the item. - **size** (integer) - The size of the item in bytes. - **folder** (object) - Properties of the item if it is a folder. - **file** (object) - Properties of the item if it is a file. #### Response Example ```json { "id": "ITEM_ID", "name": "Document.docx", "size": 10240, "file": {} } ``` ``` -------------------------------- ### Get a Specific Group Drive Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Retrieves details for a specific drive within a group. Replace 'GROUP_ID' and 'DRIVE_ID' with the actual IDs. ```python async def get_group_drive(): drive = await client.groups.by_group_id( 'GROUP_ID' ).drives.by_drive_id( 'DRIVE_ID' ).get() if drive: print(drive.id, drive.drive_type, drive.name, drive.web_url, drive.items) asyncio.run(get_group_drive()) ``` -------------------------------- ### Get Current Signed-In User Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/general_samples.md Fetches the profile of the currently authenticated user using the '/me' endpoint. Requires delegated permissions. For application permissions, use '/users/[userPrincipalName]'. ```python async def get_me(): me = await client.me.get() if me: print(me.user_principal_name, me.display_name, me.id) asyncio.run(get_me()) ``` -------------------------------- ### Get Specific Group by ID Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Retrieves details for a specific group using its ID. Replace 'GROUP_ID' with the actual group ID. ```python async def get_group(): group = await client.groups.by_group_id('GROUP_ID').get() if group: print(group.id, group.display_name, group.description, group.group_types, group.security_enabled) asyncio.run(get_group()) ``` -------------------------------- ### Get Drive Item by ID Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/drives_samples.md Fetches a specific item within a drive using both drive and item IDs. Displays item details like ID, name, size, and type (folder/file). ```python async def get_drive_item(): item = await client.drives.by_drive_id('DRIVE_ID').items.by_drive_item_id('ITEM_ID').get() if item: print(item.id, item.name, item.size, item.folder, item.file) asyncio.run(get_drive_item()) ``` -------------------------------- ### List All Members in a Group Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Retrieves a list of all members directly associated with a specified group. This operation corresponds to the GET /groups/{id}/members endpoint. ```APIDOC ## GET /groups/{id}/members ### Description Retrieves a list of all direct members of a specified group. ### Method GET ### Endpoint /groups/{id}/members ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the group. ### Response #### Success Response (200) - **value** (array) - A collection of member objects. ### Request Example ```python async def get_group_members(): members = await client.groups.by_group_id('GROUP_ID').members.get() if members and members.value: for member in members.value: user = await client.users.by_user_id(member.id).get() if user: print(user.display_name, user.mail) asyncio.run(get_group_members()) ``` ``` -------------------------------- ### Get User Messages Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/general_samples.md Retrieves a collection of messages from a user's mailbox. Ensure the correct permissions are granted. The response is deserialized into Message model objects. ```python async def get_user_messages(): messages = await (client.users.by_user_id('USER_ID').messages.get()) if messages and messages.value: for msg in messages.value: print(msg.subject, msg.id, msg.from_) asyncio.run(get_user_messages()) ``` -------------------------------- ### List All Transitive Memberships of a User Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/users_samples.md Retrieves all groups and directory roles that a user is a direct or indirect member of. This operation corresponds to the GET /users/{id}/transitiveMemberOf endpoint. ```APIDOC ## GET /users/{id}/transitiveMemberOf ### Description Retrieves a collection of directory objects (groups, roles) that the user is a transitive member of. ### Method GET ### Endpoint /users/{id}/transitiveMemberOf ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier (GUID) of the user. ### Request Example ```python async def get_memberships(): memberships = await client.users.by_user_id('USER_ID').transitive_member_of.get() if memberships and memberships.value: for membership in memberships.value: obj = await client.directory_objects.by_directory_object_id(membership.id).get() if obj and obj.odata_type == '#microsoft.graph.group': group = await client.groups.by_group_id(obj.id).get() if group: print(group.id, group.group_types, group.display_name, group.mail) asyncio.run(get_memberships()) ``` ### Response #### Success Response (200) - **value** (array) - A collection of directory objects representing memberships. - **id** (string) - The unique identifier of the directory object (group or role). - **@odata.type** (string) - The OData type of the directory object (e.g., '#microsoft.graph.group'). ``` -------------------------------- ### Get Raw HTTP Response Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/general_samples.md Retrieves the raw HTTPX response from the Graph API by configuring the request options with NativeResponseHandler. The response body can then be accessed as JSON. ```python from kiota_abstractions.native_response_handler import NativeResponseHandler from kiota_http.middleware.options import ResponseHandlerOption from msgraph_beta.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder async def get_user_messages(): request_config = MessagesRequestBuilder.MessagesRequestBuilderGetRequestConfiguration( options=[ResponseHandlerOption(NativeResponseHandler())], ) messages = await client.users.by_user_id('USER_ID').messages.get(request_configuration=request_config) print(messages.json()) asyncio.run(get_user()) ``` -------------------------------- ### List a Group's Team SharePoint Sites Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Retrieves a list of SharePoint sites associated with a group's team. This operation corresponds to the GET /groups/{id}/sites endpoint. ```APIDOC ## GET /groups/{id}/sites ### Description Retrieves a list of SharePoint sites associated with a group's team. ### Method GET ### Endpoint /groups/{id}/sites ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the group. ### Response #### Success Response (200) - **value** (array) - A collection of site objects. ### Request Example ```python async def get_group_sites(): sites = await client.groups.by_group_id('GROUP_ID').sites.get() if sites and sites.value: for site in sites.value: print(site.id, site.web_url) asyncio.run(get_group_sites()) ``` ``` -------------------------------- ### List a Group's Transitive Members Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Retrieves a list of all members in a group, including members of nested groups. This operation corresponds to the GET /groups/{id}/transitiveMembers endpoint. ```APIDOC ## GET /groups/{id}/transitiveMembers ### Description Retrieves a list of all members in a group, including members of any nested groups. ### Method GET ### Endpoint /groups/{id}/transitiveMembers ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the group. ### Response #### Success Response (200) - **value** (array) - A collection of directory object objects. ### Request Example ```python async def get_group_transitive_members(): members = await client.groups.by_group_id('GROUP_ID').transitive_members.get() if members and members.value: for member in members.value: obj = await client.directory_objects.by_directory_object_id(member.id).get() if obj and obj.odata_type == '#microsoft.graph.user': user = await client.users.by_user_id(obj.id).get() if user: print(user.id, user.display_name, user.mail) asyncio.run(get_group_transitive_members()) ``` ``` -------------------------------- ### Create GraphServiceClient with ClientSecretCredential Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/users_samples.md Demonstrates how to set up authentication using ClientSecretCredential and create an instance of GraphServiceClient. Ensure you have the necessary Azure AD application registration and permissions. ```python import asyncio from azure.identity import ClientSecretCredential from msgraph_beta import GraphServiceClient # Set the event loop policy for Windows asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # Create authentication provider object. Used to authenticate request credential = ClientSecretCredential( tenant_id='TENANT_ID', client_id='CLIENT_ID', client_secret='CLIENT_SECRET' ) scopes = ['https://graph.microsoft.com/.default'] # Create an API client with the credentials and scopes. client = GraphServiceClient(credential, scopes=scopes) ``` -------------------------------- ### Instantiate Graph Client: msgraph-core vs. msgraph-beta-sdk Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/UPGRADING.md Compares the instantiation of the Graph client between msgraph-core and msgraph-beta-sdk, highlighting the new GraphRequestAdapter in the latter. ```python # msgraph-core from msgraph.core import GraphClient client = GraphClient(credential=credential) # msgraph-sdk from msgraph_beta.graph_request_adapter import GraphRequestAdapter from msgraph_beta.graph_service_client import GraphServiceClient adapter = GraphRequestAdapter(auth_provider) client = GraphServiceClient(request_adapter) ``` -------------------------------- ### Create GraphServiceClient Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/applications_samples.md Initializes the GraphServiceClient using environment credentials. Ensure you have set up your Azure environment variables for authentication. ```python import asyncio from azure.identity import EnvironmentCredential from msgraph_beta import GraphServiceClient # Set the event loop policy for Windows asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # Create authentication provider object. Used to authenticate request credential=EnvironmentCredential() # Get a service client. client = GraphServiceClient(credentials=credential) ``` -------------------------------- ### Create Graph Client with Custom AsyncClient Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/general_samples.md Initializes a Graph client using a custom httpx.AsyncClient instance, allowing for more control over the HTTP client configuration. ```python from msgraph_beta import GraphRequestAdapter from msgraph_core import GraphClientFactory http_client = GraphClientFactory.create_with_default_middleware(client=httpx.AsyncClient()) request_adapter = GraphRequestAdapter(auth_provider, http_client) ``` -------------------------------- ### Create GraphServiceClient Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/drives_samples.md Instantiate the GraphServiceClient with authentication credentials. Requires Azure Identity and GraphServiceClient. ```python import asyncio from azure.identity import ClientSecretCredential from msgraph_beta import GraphServiceClient # (Optional) Set the event loop policy for Windows asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # Create authentication provider object. Used to authenticate request credential = ClientSecretCredential( tenant_id='TENANT_ID', client_id='CLIENT_ID', client_secret='CLIENT_SECRET' ) scopes = ['https://graph.microsoft.com/.default'] # Create an API client with the credentials and scopes. client = GraphServiceClient(credential, scopes=scopes) ``` -------------------------------- ### Initialize GraphServiceClient with Async EnvironmentCredential Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/README.md Create a GraphServiceClient instance using asynchronous EnvironmentCredential for authentication. Define the required scopes for accessing Microsoft Graph resources. ```python from azure.identity.aio import EnvironmentCredential from msgraph_beta import GraphServiceClient scopes = ['User.Read', 'Mail.Read'] credential = EnvironmentCredential() client = GraphServiceClient(credential, scopes=scopes) ``` -------------------------------- ### Create a Default Graph Client Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/general_samples.md Creates a default Graph client using the AuthorizationCodeCredential. Ensure you have the necessary scopes defined. ```python from azure.identity import AuthorizationCodeCredential from msgraph_beta import GraphServiceClient # Set the event loop policy for Windows asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) AuthorizationCodeCredential( tenant_id: str, client_id: str, authorization_code: str, redirect_uri: str ) scopes = ['User.Read', 'Mail.ReadWrite'] # Create an API client with the credentials and scopes. client = GraphServiceClient(credential, scopes=scopes) ``` -------------------------------- ### List Applications in Tenant Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/applications_samples.md Retrieves and prints the IDs of all applications registered in the tenant. This requires the GraphServiceClient to be initialized. ```python async def get_applications(): apps = await client.applications.get() if apps and apps.value: for app in apps.value: print(app.id) asyncio.run(get_applications()) ``` -------------------------------- ### Execute Asynchronous Graph Requests Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/UPGRADING.md Demonstrates how to execute asynchronous requests using the msgraph-beta-sdk. Requires an async environment like asyncio. Configure requests with QueryParameters and RequestConfiguration. ```python # msgraph-core result = client.get('/users/userId/messages',params={'$select': 'subject','$top': '5', '$skip': '1'}) for message in result.json()['value']: print message['subject'] # msgraph-beta-sdk query_params = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters( select=['subject',], skip=1, top=5 ) request_config = MessagesRequestBuilder.MessagesRequestBuilderGetRequestConfiguration( query_parameters=query_params, ) messages = asyncio.run(client.users_by_id('userId').messages().get(request_configuration=request_config)) for msg in messages.value: print(msg.subject) ``` -------------------------------- ### List All Groups in Tenant Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Retrieves a list of all groups in the tenant. Requires the GraphServiceClient to be initialized. ```python async def get_groups(): groups = await client.groups.get() if groups and groups.value: for group in groups.value: print(group.id, group.display_name) asyncio.run(get_groups()) ``` -------------------------------- ### List All Drives Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/drives_samples.md Retrieves a list of all available drives and prints their basic information. ```APIDOC ## LIST ALL DRIVES (GET /drives) ### Description Retrieves a list of all drives available in the user's account. ### Method GET ### Endpoint /drives ### Parameters None ### Request Example ```python async def get_drives(): drives = await client.drives.get() if drives and drives.value: for drive in drives.value: print(drive.id, drive.drive_type, drive.name, drive.description, drive.web_url) asyncio.run(get_drives()) ``` ### Response #### Success Response (200) - **value** (array) - A collection of drive objects. - **id** (string) - The unique identifier for the drive. - **drive_type** (string) - The type of the drive (e.g., 'personal', 'business'). - **name** (string) - The name of the drive. - **description** (string) - A description of the drive. - **web_url** (string) - The URL to access the drive in a web browser. #### Response Example ```json { "value": [ { "id": "DRIVE_ID_1", "drive_type": "personal", "name": "OneDrive", "description": "User's personal OneDrive", "web_url": "https://onedrive.live.com/" } ] } ``` ``` -------------------------------- ### List All Drives Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/drives_samples.md Retrieves a list of all drives accessible to the authenticated user. Prints drive ID, type, name, description, and web URL. ```python async def get_drives(): drives = await client.drives.get() if drives and drives.value: for drive in drives.value: print(drive.id, drive.drive_type, drive.name, drive.description, drive.web_url) asyncio.run(get_drives()) ``` -------------------------------- ### List All Applications in the Tenant Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/applications_samples.md This snippet demonstrates how to retrieve a list of all applications registered in your Microsoft Graph tenant using the `client.applications.get()` method. ```APIDOC ## GET /applications ### Description Retrieves a list of all applications in the tenant. ### Method GET ### Endpoint /applications ### Request Example ```python async def get_applications(): apps = await client.applications.get() if apps and apps.value: for app in apps.value: print(app.id) asyncio.run(get_applications()) ``` ### Response #### Success Response (200) - **value** (array) - A collection of application objects. - **id** (string) - The unique identifier for the application. ``` -------------------------------- ### Create API Client with Azure Identity Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Initializes the GraphServiceClient using ClientSecretCredential for authentication. Ensure you have the necessary Azure AD app registration details. ```python import asyncio from azure.identity import ClientSecretCredential from msgraph_beta import GraphServiceClient # Set the event loop policy for Windows asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # Create authentication provider object. Used to authenticate request credential = ClientSecretCredential( tenant_id='TENANT_ID', client_id='CLIENT_ID', client_secret='CLIENT_SECRET' ) scopes = ['https://graph.microsoft.com/.default'] a# Create an API client with the credentials and scopes. client = GraphServiceClient(credential, scopes=scopes) ``` -------------------------------- ### Send an email using Microsoft Graph Beta SDK for Python Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/general_samples.md Use this snippet to send an email. Ensure you have the necessary Mail.Send permissions. The request body is constructed using provided models. ```python from msgraph_beta import GraphServiceClient from msgraph_beta.generated.me.send_mail.send_mail_post_request_body import SendMailPostRequestBody from msgraph_beta.generated.models.body_type import BodyType from msgraph_beta.generated.models.message import Message from msgraph_beta.generated.models.email_address import EmailAddress from msgraph_beta.generated.models.importance import Importance from msgraph_beta.generated.models.item_body import ItemBody from msgraph_beta.generated.models.recipient import Recipient from msgraph_beta.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder credential = ClientSecretCredential( 'tenant_id', 'client_id', 'client_secret' ) scopes = ['Mail.Send'] # Create an API client with the credentials and scopes. client = GraphServiceClient(credential, scopes=scopes) async def send_mail(): sender = EmailAddress() sender.address = 'john.doe@outlook.com' sender.name = 'John Doe' from_recipient = Recipient() from_recipient.email_address = sender recipients = [] recipient_email = EmailAddress() recipient_email.address = 'jane.doe@outlook.com' recipient_email.name = 'Jane Doe' to_recipient = Recipient() to_recipient.email_address = recipient_email recipients.append(to_recipient) email_body = ItemBody() email_body.content = 'Dummy content' email_body.content_type = BodyType.Text message = Message() message.subject = 'Test Email' message.from_escaped = from_recipient message.to_recipients = recipients message.body = email_body request_body = SendMailPostRequestBody() request_body.message = message response = await client.me.send_mail.post(request_body) asyncio.run(send_mail()) ``` -------------------------------- ### List Items in a Drive Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/drives_samples.md Retrieves all items within a specified drive. Outputs item ID, name, size, and whether it is a folder or file. ```python async def get_drive_items(): items = await client.drives.by_drive_id('DRIVE_ID').items.get() if items and items.value: for item in items.value: print(item.id, item.name, item.size, item.folder, item.file) asyncio.run(get_drive_items()) ``` -------------------------------- ### Environment Credentials Flow (Async) with Microsoft Graph SDK Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/authentication_samples.md Use EnvironmentCredential for applications that can authenticate using environment variables. This is useful for local development and CI/CD pipelines. ```python import asyncio from azure.identity.aio import EnvironmentCredential from msgraph_beta import GraphServiceClient # Set the event loop policy for Windows asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # Create authentication provider object. Used to authenticate request credential = EnvironmentCredential() scopes = ['https://graph.microsoft.com/.default'] # Create an API client with the credentials and scopes. client = GraphServiceClient(credential, scopes=scopes) # GET A USER USING THE USER ID (GET /users/{id}) async def get_user(): user = await client.users.by_user_id('USER_ID').get() if user: print(user.user_principal_name, user.display_name, user.id) asyncio.run(get_user()) ``` -------------------------------- ### Update Authentication Provider for msgraph-beta-sdk Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/UPGRADING.md Shows how to update the authentication mechanism from msgraph-core to msgraph-beta-sdk, utilizing Azure Identity for asynchronous credentials. ```python # msgraph-core from azure.identity import ClientSecretCredential from msgraph.core import GraphClient credential = ClientSecretCredential(tenant_id: str, client_id: str, client_secret: str) # msgraph-sdk from azure.identity.aio import ClientSecretCredential # async credentials only from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider credential=ClientSecretCredential(tenant_id: str, client_id: str, client_secret: str) auth_provider = AzureIdentityAuthenticationProvider(credential) ``` -------------------------------- ### List All Group Drives Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Retrieves a list of all drives associated with a group. Replace 'GROUP_ID' with the actual group ID. ```python async def get_group_drives(): drives = await client.groups.by_group_id('GROUP_ID').drives.get() if drives and drives.value: for drive in drives.value: print(drive.id, drive.name) asyncio.run(get_group_drives()) ``` -------------------------------- ### Conventional Commit Message Format Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/CONTRIBUTING.md Follow this format for commit messages to support the automated release process. It includes a header with type and description, an optional body, and optional footers. ```text [optional scope]: ``` -------------------------------- ### List Items in a Drive Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/drives_samples.md Retrieves a list of all items (files and folders) within a specified drive. ```APIDOC ## LIST ALL THE ITEMS IN A DRIVE (GET /drives/{id}/items) ### Description Retrieves a list of all items, including files and folders, contained within a specific drive. ### Method GET ### Endpoint /drives/{id}/items ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the drive. ### Request Example ```python async def get_drive_items(): items = await client.drives.by_drive_id('DRIVE_ID').items.get() if items and items.value: for item in items.value: print(item.id, item.name, item.size, item.folder, item.file) asyncio.run(get_drive_items()) ``` ### Response #### Success Response (200) - **value** (array) - A collection of item objects within the drive. - **id** (string) - The unique identifier for the item. - **name** (string) - The name of the item. - **size** (integer) - The size of the item in bytes. - **folder** (object) - Properties of the item if it is a folder. - **file** (object) - Properties of the item if it is a file. #### Response Example ```json { "value": [ { "id": "ITEM_ID_1", "name": "Document.docx", "size": 10240, "file": {} }, { "id": "FOLDER_ID_1", "name": "Photos", "size": 0, "folder": {} } ] } ``` ``` -------------------------------- ### Fetch Current User with InteractiveBrowserCredential Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/README.md Asynchronously retrieve the signed-in user's display name using the GraphServiceClient authenticated with InteractiveBrowserCredential. This requires delegated permissions and a signed-in user context. ```python import asyncio from azure.identity import InteractiveBrowserCredential from msgraph_beta import GraphServiceClient credential = InteractiveBrowserCredential() scopes=['User.Read'] client = GraphServiceClient(credential, scopes=scopes) async def me(): me = await client.me.get() if me: print(me.display_name) asyncio.run(me()) ``` -------------------------------- ### Client Secret Credentials Flow with Microsoft Graph SDK Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/authentication_samples.md Use ClientSecretCredential for application-only authentication where no user interaction is involved. Requires tenant ID, client ID, and client secret. ```python import asyncio from azure.identity import ClientSecretCredential from msgraph_beta import GraphServiceClient # Set the event loop policy for Windows asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # Create authentication provider object. Used to authenticate request credential = ClientSecretCredential( tenant_id='TENANT_ID', client_id='CLIENT_ID', client_secret='CLIENT_SECRET' ) scopes = ['https://graph.microsoft.com/.default'] # Create an API client with the credentials and scopes. client = GraphServiceClient(credential, scopes=scopes) # GET A USER USING THE USER ID (GET /users/{id}) async def get_user(): user = await client.users.by_user_id('USER_ID').get() if user: print(user.user_principal_name, user.display_name, user.id) asyncio.run(get_user()) ``` -------------------------------- ### Device Code Flow Authentication with Microsoft Graph SDK Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/authentication_samples.md Use DeviceCodeCredential for scenarios where a user needs to authenticate on a device without a web browser. Requires client and tenant IDs. ```python import asyncio from azure.identity import DeviceCodeCredential from msgraph_beta import GraphServiceClient # Set the event loop policy for Windows asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # Create authentication provider object. Used to authenticate requests credential = DeviceCodeCredential( client_id='CLIENT_ID', tenant_id='TENANT_ID', ) scopes = ["User.Read"] # Create an API client with the credentials and scopes. client = GraphServiceClient(credential, scopes=scopes) # GET A USER USING THE USER ID (GET /users/{id}) async def get_user(): user = await client.users_by_id('USER_ID').get() if user: print(user.user_principal_name, user.display_name, user.id) asyncio.run(get_user()) ``` -------------------------------- ### List a Group's SharePoint Sites Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Retrieves a list of SharePoint sites associated with a group. Replace 'GROUP_ID' with the actual group ID. ```python async def get_group_sites(): sites = await client.groups.by_group_id('GROUP_ID').sites.get() if sites and sites.value: for site in sites.value: print(site.id, site.web_url) asyncio.run(get_group_sites()) ``` -------------------------------- ### Handle API Exceptions Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/UPGRADING.md Shows how to catch and handle ApiException for 4xx or 5xx responses from the Graph API. The exception object provides details about the error. ```python try: users = asyncio.run(client.users().get()) except ApiException as e { return f"Exception occurred: {repr(e)}" ``` -------------------------------- ### List Transitive Memberships of a User Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/users_samples.md Retrieves all groups a user is a member of, directly or indirectly. It then fetches group details for each membership and prints group information if the object is a group. ```python # LIST ALL TRANSITIVE MEMBERSHIPS OF A USER (GET /users/{id}/transitiveMemberOf) async def get_memberships(): memberships = await client.users.by_user_id('USER_ID').transitive_member_of.get() if memberships and memberships.value: for membership in memberships.value: obj = await client.directory_objects.by_directory_object_id(membership.id).get() if obj and obj.odata_type == '#microsoft.graph.group': group = await client.groups.by_group_id(obj.id).get() if group: print(group.id, group.group_types, group.display_name, group.mail) asyncio.run(get_memberships()) ``` -------------------------------- ### Interactive Browser Flow Authentication with Microsoft Graph SDK Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/authentication_samples.md Use InteractiveBrowserCredential for applications that can open a web browser for user authentication. This is suitable for desktop or mobile applications. ```python import asyncio from azure.identity import InteractiveBrowserCredential from msgraph_beta import GraphServiceClient # Set the event loop policy for Windows asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # Create authentication provider object. Used to authenticate requests credential = InteractiveBrowserCredential() scopes = ["User.Read"] # Create an API client with the credentials and scopes. client = GraphServiceClient(credential, scopes=scopes) # GET A USER USING THE USER ID (GET /users/{id}) async def get_user(): user = await client.users_by_id('USER_ID').get() if user: print(user.user_principal_name, user.display_name, user.id) asyncio.run(get_user()) ``` -------------------------------- ### List All Members in a Group Source: https://github.com/microsoftgraph/msgraph-beta-sdk-python/blob/main/docs/groups_samples.md Retrieves all members of a specified group. This includes direct members. Replace 'GROUP_ID' with the actual group ID. ```python async def get_group_members(): members = await client.groups.by_group_id('GROUP_ID').members.get() if members and members.value: for member in members.value: user = await client.users.by_user_id(member.id).get() if user: print(user.display_name, user.mail) asyncio.run(get_group_members()) ```