Registry / azure / msgraph-sdk

msgraph-sdk

JSON →
library1.61.0pypypi✓ verified 25d ago

The Microsoft Graph Python SDK is a client library for interacting with the Microsoft Graph API, enabling Python applications to access data across Microsoft 365, Windows, and Enterprise Mobility + Security. It supports the v1.0 of Microsoft Graph and is asynchronous by default, designed for modern Python applications. The library is actively maintained with frequent releases, currently at version 1.55.0, and leverages the underlying `msgraph-core` library and `kiota-authentication-azure` for core functionalities and authentication.

pip install msgraph-sdk
INSTALL
IMPORT
SIG · MSGRAPH-SDK
M
msgraph-sdk
azurepythonv1.61.0
Install
32.0s avg
Import
916ms
Disk
848MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.61.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.910 runs
installs and imports cleanly · install 0.0s · import 0.944s · 796MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 32.0s · import 0.888s · 869MB
848MB installed
● package 848MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

GraphServiceClient
from msgraph import GraphServiceClient
AzureIdentityAuthenticationProvider
from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
from msgraph.core.authentication import AzureIdentityAuthenticationProvider
The authentication provider moved from 'msgraph.core' to 'kiota_authentication_azure' in major versions.
ClientSecretCredential
from azure.identity.aio import ClientSecretCredential
from azure.identity import ClientSecretCredential
The SDK is asynchronous by default, requiring async credential classes from 'azure.identity.aio'.

This quickstart demonstrates how to initialize the `GraphServiceClient` using `ClientSecretCredential` for app-only authentication (daemon app scenario) and fetch messages for a specific user. It highlights the asynchronous nature of the SDK and the use of environment variables for sensitive credentials. Remember to replace placeholder values and ensure your application registration has the necessary API permissions (e.g., `Mail.Read.All`) and admin consent.

import asyncio import os from azure.identity.aio import ClientSecretCredential from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider from msgraph import GraphServiceClient from msgraph.generated.models.message import Message async def main(): # Environment variables for client credentials flow tenant_id = os.environ.get('TENANT_ID', 'YOUR_TENANT_ID') client_id = os.environ.get('CLIENT_ID', 'YOUR_CLIENT_ID') client_secret = os.environ.get('CLIENT_SECRET', 'YOUR_CLIENT_SECRET') user_id = os.environ.get('USER_ID', 'YOUR_USER_ID') # User to fetch messages from # Ensure required environment variables are set if not all([tenant_id, client_id, client_secret, user_id]): print("Please set TENANT_ID, CLIENT_ID, CLIENT_SECRET, and USER_ID environment variables.") return # For app-only permissions, use the .default scope scopes = ['https://graph.microsoft.com/.default'] # Create a credential object credential = ClientSecretCredential( tenant_id=tenant_id, client_id=client_id, client_secret=client_secret ) # Create an authentication provider auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes) # Create a GraphServiceClient client = GraphServiceClient(auth_provider) try: # Fetch messages for a specific user # Note: This requires Mail.Read.All application permission or Mail.Read delegated permission for the user_id # if using delegated flow. messages_collection = await client.users.by_user_id(user_id).messages.get() if messages_collection and messages_collection.value: print(f"Successfully fetched {len(messages_collection.value)} messages for user {user_id}:") for msg in messages_collection.value: print(f" Subject: {msg.subject}, From: {msg.sender.email_address.address}") else: print(f"No messages found for user {user_id}.") except Exception as e: print(f"Error fetching messages: {e}") if __name__ == '__main__': asyncio.run(main())
Debug
Known issues
breakingMajor breaking changes were introduced with version 1.0.0, specifically in how authentication providers are configured and the client is instantiated. The 'GraphClient' from 'msgraph.core' was replaced by 'GraphServiceClient' from 'msgraph', and authentication moved to 'AzureIdentityAuthenticationProvider' from 'kiota_authentication_azure'.
fix
Review the official documentation for the latest authentication and client construction patterns. Update imports and client instantiation to use `GraphServiceClient` and `AzureIdentityAuthenticationProvider` with async credentials from `azure.identity.aio`.
affects: Upgrading from pre-1.0.0 versions (e.g., msgraph-core==0.2.2) to msgraph-sdk>=1.0.0.
gotchaThe SDK is asynchronous by default, meaning all API calls return coroutines. You must use `await` and run your code within an `asyncio` event loop or similar async framework (`anyio`, `trio`).
fix
Wrap your SDK calls in an `async def` function and execute it using `asyncio.run()` or integrate it into your existing asynchronous application framework.
affects: All versions >=1.0.0.
gotchaWhen sending attachments, the `content_bytes` field in attachment models (e.g., `FileAttachment`) expects raw bytes, not a base64 encoded string. The SDK handles the base64 encoding internally.
fix
Pass the raw byte content of the file directly to `content_bytes`. Do not manually base64 encode the content before assigning it.
affects: All versions.
gotchaThe `msgraph-sdk` package is large, and its initial installation might take a few minutes. On Windows, users might encounter `OSError` related to long paths, requiring enabling long path support.
fix
For Windows, enable long paths in your environment. Instructions are typically available in Microsoft documentation or by searching for 'Enable Long Paths Windows 10'.
affects: All versions.
gotchaThere are two separate SDKs: `msgraph-sdk` for the v1.0 Microsoft Graph API endpoint and `msgraph-beta-sdk` for the latest beta endpoint. Mixing them or using the wrong one can lead to unexpected behavior or missing functionalities.
fix
Ensure you install and import from the correct SDK (`msgraph` vs `msgraph_beta`) based on whether you intend to target the stable v1.0 API or the experimental beta API.
affects: All versions.
gotchaThe Microsoft Graph API itself can return 5xx status codes (e.g., 500 Internal Server Error, 503 Service Unavailable, 504 Gateway Timeout) which indicate server-side issues. While the SDK has a built-in retry-handler, these errors can still occur and may require application-level retry logic.
fix
Implement robust error handling, including retries with exponential backoff, in your application logic to gracefully handle transient 5xx errors from the Graph API. The SDK's built-in retry handler is configurable.
affects: All versions.
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'msgraph.generated.users'
This typically occurs if the 'msgraph-sdk' package was not installed correctly, the expected generated module path does not exist in the installed version, or if there's a conflict with your Python environment.
fix
Ensure 'msgraph-sdk' is properly installed in your active Python environment using `pip install msgraph-sdk`. If the issue persists, try reinstalling with `pip install --upgrade --force-reinstall msgraph-sdk`. On Windows, enabling long paths in your environment might be necessary during installation.
400: Bad Request error, specifically stating that the /me request is only valid with a delegated authentication flow.
This error arises when you attempt to access the `/me` endpoint, which represents the currently signed-in user, using an application-only (client credentials) authentication flow. The `/me` endpoint requires a delegated authentication flow where a user's identity is established.
fix
If you need to retrieve information about the currently authenticated user, switch to a delegated authentication flow (e.g., Device Code Flow, Interactive Browser Flow). If you intend to access user data with application permissions, replace `/me` with `/users/{user-id}` and provide the specific user's ID.
AttributeError: type object 'GroupsRequestBuilder' has no attribute 'GroupsRequestBuilderGetRequestConfiguration'
This `AttributeError` suggests that the method or object used for configuring requests (e.g., adding query parameters like `$select`, `$filter`, `$count`) has changed in the `msgraph-sdk` version you are using, often due to a major SDK update.
fix
Consult the official `msgraph-sdk` documentation or the upgrade guide for your specific version (e.g., from v1.2.0 to v1.3.0) to understand the correct way to pass request configuration options. This often involves creating a specific request configuration object or using a lambda function as per the current SDK design.
Error code: ResourceNotFound. Error message: Resource could not be discovered.
This Microsoft Graph API error indicates that the requested resource (e.g., a user, their mailbox, or a specific file) does not exist, the provided ID is incorrect, or the authenticated identity (user or application) lacks the necessary permissions or licenses to access that resource. For mailbox-related operations, the target user might not have an active Exchange Online mailbox.
fix
Verify the resource ID for correctness. Ensure your application has the appropriate Microsoft Graph API permissions (delegated or application) and that these permissions have been granted admin consent in Azure AD. For mailbox issues, confirm the user has an active Exchange Online license and a provisioned mailbox.
ImportError: cannot import name 'GraphServiceClient' from partially initialized module 'msgraph' (most likely due to a circular import)
This Python `ImportError` typically occurs due to a circular import. This can happen if your own Python script is named `msgraph.py` or `graph.py`, causing a conflict with the `msgraph-sdk` library itself when attempting to import `GraphServiceClient`.
fix
Rename your Python script to avoid naming conflicts with the 'msgraph-sdk' library or its internal modules (e.g., rename `msgraph.py` to `my_graph_app.py`). Additionally, review your project for other potential circular dependencies in import statements.
Upgrade
Version history
1.61.0latest on PyPI · released Aug 5, 2026
Audit
Dependencies
azure-identityrequiredRequired for authentication with Microsoft identity platform credentials (e.g., ClientSecretCredential, EnvironmentCredential).
msgraph-corerequiredCore client library underlying the SDK, providing HTTP request handling. Installed transitively.
kiota-authentication-azurerequiredProvides the AzureIdentityAuthenticationProvider for integrating Azure Identity credentials with the SDK. Installed transitively.
httpxrequiredUsed as the default HTTP client internally.
Agent activity
25 hits · last 30 days
node
22
OpenAI (training)
1
Resources
msgraph-sdk — pip install msgraph-sdk · libregistry