### Install Microsoft Graph SDK for Python Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/README.md Install the SDK using pip. Ensure you are using Python 3.10+ and consider enabling long paths if installation fails. ```bash pip install msgraph-sdk ``` -------------------------------- ### Install msgraph-core and msgraph-sdk Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/UPGRADING.md Installs the older msgraph-core and the new msgraph-sdk packages using pip. ```python # msgraph-core pip install msgraph-core # msgraph-sdk pip install msgraph-sdk ``` -------------------------------- ### Update Authentication Provider Setup Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/UPGRADING.md Shows the updated authentication setup using AzureIdentityAuthenticationProvider from kiota-authentication for msgraph-sdk, compared to the older ClientSecretCredential with GraphClient. ```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) ``` -------------------------------- ### Get Specific User Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/users_samples.md Fetches a single user's details using their ID. This example also shows how to retrieve a user's transitive memberships. ```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()) # 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()) ``` -------------------------------- ### Get All Users Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/users_samples.md Retrieves a list of all users in the tenant. This function 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 Graph API Request Methods Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/UPGRADING.md Illustrates the difference in making GET requests between msgraph-core (raw URL) and msgraph-sdk (fluent builder pattern). ```python # msgraph-core resp =client.get('/users/userId/messages') # msgraph-sdk req = client.users.by_user_id('userId').messages.get() resp = asyncio.run(req) ``` -------------------------------- ### Asynchronous Authentication with ClientSecretCredential Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/README.md This example demonstrates asynchronous authentication using ClientSecretCredential, ideal for backend services or applications that can run in an async environment. Replace tenant_id, client_id, and client_secret with your application's credentials. ```python import asyncio from azure.identity.aio import ClientSecretCredential from msgraph import GraphServiceClient credential = ClientSecretCredential( 'tenant_id', 'client_id', 'client_secret' ) scopes = ['https://graph.microsoft.com/.default'] client = GraphServiceClient(credentials=credential, scopes=scopes) ``` -------------------------------- ### List All Groups in Tenant Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/groups_samples.md Retrieves and prints the ID and display name of all groups in the tenant. This corresponds to the GET /groups API endpoint. ```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 THE ITEMS IN A DRIVE (GET /drives/{id}/items) Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/drives_samples.md Retrieves a list of all items (files and folders) within a specified drive. ```APIDOC ## GET /drives/{id}/items ### Description Retrieves a list of all items (files and folders) within a specified drive. ### Method GET ### Endpoint /drives/{id}/items ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the drive. ### Request Example None ### Response #### Success Response (200) - **value** (array) - A list 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) - Information about the item if it is a folder. - **file** (object) - Information about the item if it is a file. #### Response Example { "value": [ { "id": "ITEM_ID", "name": "Document.docx", "size": 10240, "folder": null, "file": {}, "web_url": "https://..." } ] } ``` -------------------------------- ### GET THE ROOT FOLDER OF THE DRIVE (GET /drives/{id}/root) Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/drives_samples.md Retrieves the root folder of a specified drive. ```APIDOC ## GET /drives/{id}/root ### Description Retrieves the root folder of a specified drive. ### Method GET ### Endpoint /drives/{id}/root ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the drive. ### Request Example None ### 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) - Folder specific properties. - **child_count** (integer) - The number of items directly within this folder. - **root** (object) - Indicates if this is the root folder. - **size** (integer) - The total size of the folder in bytes. #### Response Example { "id": "ROOT_FOLDER_ID", "name": "root", "folder": { "child_count": 50 }, "root": {}, "size": 512000, "web_url": "https://..." } ``` -------------------------------- ### LIST ALL DRIVES (GET /drives) Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/drives_samples.md Retrieves a list of all drives available in the Microsoft Graph. ```APIDOC ## GET /drives ### Description Retrieves a list of all drives available in the Microsoft Graph. ### Method GET ### Endpoint /drives ### Parameters None ### Request Example None ### Response #### Success Response (200) - **value** (array) - A list of drive objects. - **id** (string) - The unique identifier for the drive. - **drive_type** (string) - The type of the drive (e.g., 'personal', 'documentLibrary'). - **name** (string) - The name of the drive. - **description** (string) - The description of the drive. - **web_url** (string) - The URL to access the drive in a web browser. #### Response Example { "value": [ { "id": "DRIVE_ID", "drive_type": "personal", "name": "OneDrive", "description": "", "web_url": "https://onedrive.live.com/" } ] } ``` -------------------------------- ### GET DRIVE BY ID (GET /drives/{id}) Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/drives_samples.md Retrieves a specific drive using its unique identifier. ```APIDOC ## GET /drives/{id} ### Description Retrieves a specific drive using its unique identifier. ### Method GET ### Endpoint /drives/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the drive. ### Request Example None ### 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) - The description of the drive. - **web_url** (string) - The URL to access the drive. #### Response Example { "id": "DRIVE_ID", "drive_type": "personal", "name": "OneDrive", "description": "", "web_url": "https://onedrive.live.com/" } ``` -------------------------------- ### GET ITEMS IN THE ROOT FOLDER OF THE DRIVE (GET /drives/{id}/items/root/children) Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/drives_samples.md Retrieves a list of items directly within the root folder of a specified drive. ```APIDOC ## GET /drives/{id}/items/root/children ### Description Retrieves a list of items directly within the root folder of 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 None ### Response #### Success Response (200) - **value** (array) - A list 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) - Information about the item if it is a folder. - **file** (object) - Information about the item if it is a file. #### Response Example { "value": [ { "id": "ITEM_ID", "name": "SubFolder", "size": 20480, "folder": {}, "file": null, "web_url": "https://..." } ] } ``` -------------------------------- ### Fetch a User Asynchronously Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/README.md This example shows how to fetch a user's details asynchronously using the GraphServiceClient. It requires a properly authenticated client and replaces 'userPrincipalName' with the actual user principal name. ```python import asyncio from azure.identity.aio import ClientSecretCredential from msgraph import GraphServiceClient credential = ClientSecretCredential( 'tenant_id', 'client_id', 'client_secret' ) scopes = ['https://graph.microsoft.com/.default'] client = GraphServiceClient(credentials=credential, scopes=scopes) # GET /users/{id | userPrincipalName} async def get_user(): user = await client.users.by_user_id('userPrincipalName').get() if user: print(user.display_name) asyncio.run(get_user()) ``` -------------------------------- ### Get Drive by ID Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/drives_samples.md Fetches a specific drive using its unique ID. The function then prints the details of the retrieved drive. ```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 AN ITEM IN THE DRIVE (GET /drives/{id}/items/{id}) Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/drives_samples.md Retrieves a specific item (file or folder) within a drive using its unique identifiers. ```APIDOC ## GET /drives/{id}/items/{id} ### Description Retrieves a specific item (file or folder) within a drive using its unique identifiers. ### 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. ### Request Example None ### 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) - Information about the item if it is a folder. - **file** (object) - Information about the item if it is a file. #### Response Example { "id": "ITEM_ID", "name": "Document.docx", "size": 10240, "folder": null, "file": {}, "web_url": "https://..." } ``` -------------------------------- ### List All Drives for a Group Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/groups_samples.md Fetches and prints the ID and name of all drives associated with a group. This utilizes the GET /groups/{id}/drives endpoint. Substitute 'GROUP_ID' with the actual group identifier. ```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()) ``` -------------------------------- ### Search User by Name Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/users_samples.md Searches for a user by display name, email, or user principal name using a specific query. This example uses Azure CLI credentials for authentication and requires 'az login' to be run beforehand. ```python import asyncio from azure.identity import AzureCliCredential from msgraph import GraphServiceClient from msgraph.generated.users.users_request_builder import UsersRequestBuilder async def find_user(user_name: str, client: GraphServiceClient) -> None: # The query used here is the same when searching for users in Azure AD via web console query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters( search=[ f'("displayName:{user_name}" OR "mail:{user_name}" OR "userPrincipalName:{user_name}" OR "givenName:{user_name}" OR "surName:{user_name}" OR "otherMails:{user_name}")', ], ) request_configuration = ( UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration( query_parameters=query_params, ) ) request_configuration.headers.add("ConsistencyLevel", "eventual") response = await client.users.get(request_configuration=request_configuration) if response.value: user = response.value[0] print( f"Found user for {user_name} in the Azure AD with user principal name {user.user_principal_name} and display name {user.display_name}" ) else: print(f"{user_name} user in the Azure AD not found") def main(): # Use cli credentials to authenticate against Azure # Before running script do `az login` credential = AzureCliCredential() scopes = ["https://graph.microsoft.com/.default"] client = GraphServiceClient(credentials=credential, scopes=scopes) asyncio.run(find_user("john", client)) main() ``` -------------------------------- ### Get Signed-In User Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/general_samples.md Fetches the current signed-in user's profile information 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 Drive Item Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/drives_samples.md Fetches a particular item (file or folder) from a drive using both the drive ID and the item ID. It then prints the item's details. ```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()) ``` -------------------------------- ### Get a Specific Group Drive Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/groups_samples.md Retrieves and prints details of a specific drive belonging to a group. This corresponds to the GET /groups/{id}/drives/{id} API endpoint. Replace 'GROUP_ID' and 'DRIVE_ID' with the correct identifiers. ```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 Specific Group by ID Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/groups_samples.md Fetches and prints details of a specific group using its ID. This maps to the GET /groups/{id} API endpoint. 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 User Messages with Query Parameters Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/general_samples.md Retrieves a specific subset of user messages by applying query parameters like 'select', 'skip', and 'top'. Uses `MessagesRequestBuilderGetQueryParameters` and `MessagesRequestBuilderGetRequestConfiguration`. ```python from msgraph.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()) ``` -------------------------------- ### Get Raw HTTP Response Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/general_samples.md Fetches user messages and retrieves the raw HTTPX response object instead of the deserialized model. Uses `ResponseHandlerOption` with `NativeResponseHandler`. ```python from kiota_abstractions.native_response_handler import NativeResponseHandler from kiota_http.middleware.options import ResponseHandlerOption from msgraph.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()) ``` -------------------------------- ### Get User Messages with Custom Headers Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/general_samples.md Fetches user messages while passing custom request headers, such as 'prefer' for content type. Uses `MessagesRequestBuilderGetRequestConfiguration` to set headers. ```python from msgraph.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()) ``` -------------------------------- ### List SharePoint Sites for a Group Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/groups_samples.md Fetches and prints the ID and web URL of SharePoint sites associated with a group. This corresponds to the GET /groups/{id}/sites endpoint. Ensure 'GROUP_ID' is replaced with the correct group identifier. ```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()) ``` -------------------------------- ### Get Drive Root Folder Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/drives_samples.md Retrieves the root folder of a specified drive. It prints details such as the folder's ID, name, child count, and whether it's the root. ```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 Items in Root Folder Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/drives_samples.md Retrieves all direct children (files and folders) within the root folder of a specified drive. It prints the ID, name, size, and type of each child item. ```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 User Messages Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/general_samples.md Retrieves a collection of messages from a user's mailbox. Ensure correct permissions are set. The response is deserialized into a collection of `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()) ``` -------------------------------- ### Handle API Errors Asynchronously Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/README.md This example shows how to catch and handle API errors that may occur during Graph API requests. It uses a try-except block to catch APIError exceptions and print the error message. ```python from kiota_abstractions.api_error import APIError async def get_user(): try: user = await client.users.by_user_id('userID').get() print(user.user_principal_name, user.display_name, user.id) except APIError as e: print(f'Error: {e.error.message}') asyncio.run(get_user()) ``` -------------------------------- ### List Members of a Group Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/groups_samples.md Retrieves and prints the display name and email of members within a specified group. This uses the GET /groups/{id}/members endpoint. Replace 'GROUP_ID' with the target group's 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()) ``` -------------------------------- ### List Transitive Members of a Group Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/groups_samples.md Retrieves and prints the ID, display name, and email of all users who are members of a group, including nested groups. This uses the GET /groups/{id}/transitiveMembers endpoint. Replace 'GROUP_ID' with the relevant group ID. ```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 Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/drives_samples.md Initializes the GraphServiceClient with authentication credentials. Ensure you replace placeholder values with your actual tenant ID, client ID, and client secret. ```python import asyncio from azure.identity import ClientSecretCredential from msgraph import GraphServiceClient # Create a credential object. Used to authenticate requests 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(credentials=credential, scopes=scopes) ``` -------------------------------- ### Create GraphServiceClient Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/users_samples.md Instantiate the GraphServiceClient with client credentials for authentication. Ensure you replace placeholder values with your actual tenant, client ID, and client secret. ```python import asyncio from azure.identity import ClientSecretCredential from msgraph import GraphServiceClient # Create a credential object. Used to authenticate requests 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(credentials=credential, scopes=scopes) ``` -------------------------------- ### Create GraphServiceClient Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/applications_samples.md Initialize the GraphServiceClient using ClientSecretCredential for authentication. Ensure you replace placeholder values with your actual tenant ID, client ID, and client secret. ```python import asyncio from azure.identity import ClientSecretCredential from msgraph import GraphServiceClient # Create a credential object. Used to authenticate requests 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(credentials=credential, scopes=scopes) ``` -------------------------------- ### Initialize ClientSecretCredential for Application Permissions Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/README.md Use ClientSecretCredential for applications running in the background without a signed-in user. Requires tenant ID, client ID, and client secret. ```python import asyncio from azure.identity.aio import ClientSecretCredential credential = ClientSecretCredential("tenantID", "clientID", "clientSecret") scopes = ['https://graph.microsoft.com/.default'] ``` -------------------------------- ### Initialize GraphServiceClient with Async Credentials Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/README.md Create a GraphServiceClient instance using asynchronous credentials and default scopes for app-only access. Ensure credentials and scopes are correctly configured. ```python # Example using async credentials and application access. from azure.identity.aio import ClientSecretCredential from msgraph import GraphServiceClient credentials = ClientSecretCredential( 'TENANT_ID', 'CLIENT_ID', 'CLIENT_SECRET', ) scopes = ['https://graph.microsoft.com/.default'] client = GraphServiceClient(credentials=credentials, scopes=scopes) ``` -------------------------------- ### Initialize DeviceCodeCredential for Delegated Permissions Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/README.md Use DeviceCodeCredential for environments where authentication is triggered in one machine and completed in another. Requires client ID and tenant ID. ```python import asyncio from azure.identity import DeviceCodeCredential credential = DeviceCodeCredential("client_id", "tenant_id") scopes = ['https://graph.microsoft.com/.default'] ``` -------------------------------- ### Create Graph Client with Custom AsyncClient Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/general_samples.md Creates a Graph client using a custom httpx.AsyncClient instance and GraphRequestAdapter. Useful for advanced HTTP client configurations. ```python from msgraph import GraphRequestAdapter from msgraph_core import GraphClientFactory http_client = GraphClientFactory.create_with_default_middleware(client=httpx.AsyncClient()) request_adapter = GraphRequestAdapter(auth_provider, http_client) client = GraphServiceClient(request_adapter=request_adapter) ``` -------------------------------- ### Create Default Graph Client Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/general_samples.md Instantiates a default Graph client using Azure Identity for authentication. Requires tenant ID, client ID, authorization code, and redirect URI. ```python from azure.identity import AuthorizationCodeCredential from msgraph import GraphServiceClient credentials = AuthorizationCodeCredential( tenant_id: str, client_id: str, authorization_code: str, redirect_uri: str ) scopes = ['User.Read', 'Mail.ReadWrite'] client = GraphServiceClient(credentials=credentials, scopes=scopes) ``` -------------------------------- ### List Applications in Tenant Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/applications_samples.md Retrieve and print the IDs of all applications registered in the Microsoft tenant using the initialized GraphServiceClient. This function requires an asynchronous context to run. ```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()) ``` -------------------------------- ### Fetch the Current User Asynchronously Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/README.md This snippet demonstrates how to retrieve the currently signed-in user's information asynchronously. It requires delegated permissions and an authenticated client. ```python import asyncio from azure.identity import InteractiveBrowserCredential from msgraph import GraphServiceClient credential = InteractiveBrowserCredential( client_id=os.getenv('client_id'), tenant_id=os.getenv('tenant_id'), ) scopes = ["User.Read"] client = GraphServiceClient(credentials=credential, scopes=scopes,) # GET /me async def me(): me = await client.me.get() if me: print(me.display_name) asyncio.run(me()) ``` -------------------------------- ### Update GraphServiceClient Instantiation Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/UPGRADING.md Demonstrates the new method of creating a GraphServiceClient using a GraphRequestAdapter for msgraph-sdk, contrasting with the direct GraphClient instantiation in msgraph-core. ```python # msgraph-core from msgraph.core import GraphClient client = GraphClient(credential=credential) # msgraph-sdk from msgraph import GraphRequestAdapter from msgraph import GraphServiceClient adapter = GraphRequestAdapter(auth_provider) client = GraphServiceClient(request_adapter) ``` -------------------------------- ### List All Drives Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/drives_samples.md Retrieves a list of all drives accessible to the authenticated user. It iterates through the drives and prints their basic information. ```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()) ``` -------------------------------- ### Execute a Graph Request with msgraph-core Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/UPGRADING.md This snippet demonstrates how to execute a basic graph request using the msgraph-core library and process the JSON response. ```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'] ``` -------------------------------- ### Asynchronous Authentication with InteractiveBrowserCredential Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/README.md Use this snippet for asynchronous authentication via interactive browser flow, suitable for user-facing applications. It requires setting the client_id and tenant_id environment variables. ```python import asyncio from azure.identity import InteractiveBrowserCredential from msgraph import GraphServiceClient credential = InteractiveBrowserCredential( client_id=os.getenv('client_id'), tenant_id=os.getenv('tenant_id'), ) scopes = ["User.Read"] client = GraphServiceClient(credentials=credential, scopes=scopes,) ``` -------------------------------- ### Execute a Graph Request with msgraph-sdk Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/UPGRADING.md This snippet shows how to configure and execute a graph request using the msgraph-sdk, including query parameters and request configuration, and process the results. ```python # msgraph-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_user_id('userId').messages.get(request_configuration=request_config)) for msg in messages.value: print(msg.subject) ``` -------------------------------- ### List Items in a Drive Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/drives_samples.md Retrieves all items (files and folders) within a specified drive. It prints the ID, name, size, and type (folder/file) of each item. ```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()) ``` -------------------------------- ### Synchronous Authentication with DeviceCodeCredential Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/README.md Use this snippet for synchronous authentication with DeviceCodeCredential, suitable for applications where user interaction is possible via a device code flow. Ensure CLIENT_ID and TENANT_ID are replaced with actual values. ```python from azure.identity import DeviceCodeCredential from msgraph import GraphServiceClient credentials = DeviceCodeCredential( 'CLIENT_ID', 'TENANT_ID', ) scopes = ['https://graph.microsoft.com/.default'] client = GraphServiceClient(credentials=credentials, scopes=scopes) ``` -------------------------------- ### Environment Credential Flow (Async) with Microsoft Graph SDK Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/authentication_samples.md This asynchronous flow uses credentials from environment variables, suitable for applications running in environments where these variables are pre-configured. ```python import asyncio from azure.identity.aio import EnvironmentCredential from msgraph import GraphServiceClient # Create a credential object. Used to authenticate requests credential = EnvironmentCredential() scopes = ['https://graph.microsoft.com/.default'] # Create an API client with the credentials and scopes. client = GraphServiceClient(credentials=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()) ``` -------------------------------- ### Paginate Group Members Asynchronously Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/README.md This snippet demonstrates how to fetch group members and iterate through paginated results using the odata_next_link. It fetches the initial batch of members and then continues to fetch subsequent batches until all members are retrieved. ```python # get group members members = await client.groups.by_group_id(id).members.get() if members: print(f"########## Members:") for i in range(len(members.value)): print(f"display_name: {members.value[i].display_name}, mail: {members.value[i].mail}, id: {members.value[i].id}") # iterate over result batches > 100 rows while members is not None and members.odata_next_link is not None: members = await client.groups.by_group_id(id).members.with_url(members.odata_next_link).get() if members: print(f"########## Members:") for i in range(len(members.value)): print(f"display_name: {members.value[i].display_name}, mail: {members.value[i].mail}, id: {members.value[i].id}") ``` -------------------------------- ### Interactive Browser Flow Authentication with Microsoft Graph SDK Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/authentication_samples.md This flow is suitable for applications where a user can interact with a browser to sign in. It uses the Azure Identity library for authentication. ```python import asyncio from azure.identity import InteractiveBrowserCredential from msgraph import GraphServiceClient # Create a credential object. Used to authenticate requests credentials = InteractiveBrowserCredential( client_id=os.getenv('client_id'), tenant_id=os.getenv('tenant_id'), ) scopes = ["User.Read"] # Create an API client with the credentials and scopes. client = GraphServiceClient(credentials=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()) ``` -------------------------------- ### Send Mail with User's Delegation Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/general_samples.md Use this snippet to send an email on behalf of the authenticated user. Ensure you have the 'Mail.Send' permission and have configured your app for public client flow. ```python import asyncio from msgraph import GraphServiceClient from msgraph.generated.users.item.send_mail.send_mail_post_request_body import SendMailPostRequestBody from msgraph.generated.models.body_type import BodyType from msgraph.generated.models.message import Message from msgraph.generated.models.email_address import EmailAddress from msgraph.generated.models.importance import Importance from msgraph.generated.models.item_body import ItemBody from msgraph.generated.models.recipient import Recipient from msgraph.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder from azure.identity import InteractiveBrowserCredential credential = InteractiveBrowserCredential( client_id, authority, tenant_id, redirect_uri ) scopes = ['Mail.Send'] # alternatively, use "Mail.Send.Shared" for a shared mailbox. client = GraphServiceClient(credentials=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()) ``` -------------------------------- ### Device Code Flow Authentication with Microsoft Graph SDK Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/authentication_samples.md Use this flow for applications that cannot provide direct browser interaction. It requires user sign-in via a device code. ```python import asyncio from azure.identity import DeviceCodeCredential from msgraph import GraphServiceClient # Create a credential 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(credentials=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()) ``` -------------------------------- ### Handle API Errors in Python Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/UPGRADING.md This snippet demonstrates how to catch and handle `APIError` exceptions that are thrown for `4xx` or `5xx` responses from the Graph API. ```python from kiota_abstractions.api_error import APIError try: users = asyncio.run(client.users().get()) except APIError as e { return f"Exception occurred: {e.error.message}" } ``` -------------------------------- ### Client Secret Credentials Flow with Microsoft Graph SDK Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/authentication_samples.md This flow is for application-only access, where the application authenticates itself using a client ID and secret, without a signed-in user. ```python import asyncio from azure.identity import ClientSecretCredential from msgraph import GraphServiceClient # Create a credential object. Used to authenticate requests 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(credentials=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()) ``` -------------------------------- ### Send Mail from Shared Mailbox Source: https://github.com/microsoftgraph/msgraph-sdk-python/blob/main/docs/general_samples.md Use this snippet to send an email from a shared mailbox. This requires 'Mail.Send.Shared' permissions and specific configuration for the 'From' recipient. ```python import asyncio from msgraph import GraphServiceClient from msgraph.generated.models.body_type import BodyType from msgraph.generated.models.message import Message from msgraph.generated.models.email_address import EmailAddress from msgraph.generated.models.item_body import ItemBody from msgraph.generated.models.recipient import Recipient from msgraph.generated.users.item.send_mail.send_mail_post_request_body import SendMailPostRequestBody from azure.identity import InteractiveBrowserCredential # Create a credential object. Used to authenticate requests credential = InteractiveBrowserCredential( client_id, authority, # e.g. https://login.microsoftonline.com/ for public Azure cloud tenant_id, redirect_uri # as configured in your App Registration > Authentication > Platform: Mobile and desktop applications ) scopes = ["Mail.Send.Shared"] # Create an API client with the credentials and scopes. client = GraphServiceClient(credentials=credential, scopes=scopes) async def send_mail(): sender = EmailAddress() sender.address = 'john.doe@outlook.com' sender.name = 'John Doe' # skip to use default sender_recipient = Recipient() sender_recipient.email_address = sender from_mailbox = EmailAddress() from_mailbox.address = 'your-shared-mailbox@outlook.com' # skip from_mailbox.name = ... to use the default display name of the shared mailbox from_recipient = Recipient() from_recipient.email_address = from_mailbox 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.sender = sender_recipient message.from_ = 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()) ```