{"id":1845,"library":"msgraph-sdk","title":"Microsoft Graph Python SDK","description":"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.","status":"active","version":"1.55.0","language":"en","source_language":"en","source_url":"https://github.com/microsoftgraph/msgraph-sdk-python","tags":["microsoft graph","sdk","azure","api client","async","microsoft 365"],"install":[{"cmd":"pip install msgraph-sdk","lang":"bash","label":"Install stable version"},{"cmd":"pip install msgraph-beta-sdk","lang":"bash","label":"Install beta version (for latest APIs)"}],"dependencies":[{"reason":"Required for authentication with Microsoft identity platform credentials (e.g., ClientSecretCredential, EnvironmentCredential).","package":"azure-identity","optional":false},{"reason":"Core client library underlying the SDK, providing HTTP request handling. Installed transitively.","package":"msgraph-core","optional":false},{"reason":"Provides the AzureIdentityAuthenticationProvider for integrating Azure Identity credentials with the SDK. Installed transitively.","package":"kiota-authentication-azure","optional":false},{"reason":"Used as the default HTTP client internally.","package":"httpx","optional":false}],"imports":[{"symbol":"GraphServiceClient","correct":"from msgraph import GraphServiceClient"},{"note":"The authentication provider moved from 'msgraph.core' to 'kiota_authentication_azure' in major versions.","wrong":"from msgraph.core.authentication import AzureIdentityAuthenticationProvider","symbol":"AzureIdentityAuthenticationProvider","correct":"from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider"},{"note":"The SDK is asynchronous by default, requiring async credential classes from 'azure.identity.aio'.","wrong":"from azure.identity import ClientSecretCredential","symbol":"ClientSecretCredential","correct":"from azure.identity.aio import ClientSecretCredential"}],"quickstart":{"code":"import asyncio\nimport os\nfrom azure.identity.aio import ClientSecretCredential\nfrom kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider\nfrom msgraph import GraphServiceClient\nfrom msgraph.generated.models.message import Message\n\nasync def main():\n    # Environment variables for client credentials flow\n    tenant_id = os.environ.get('TENANT_ID', 'YOUR_TENANT_ID')\n    client_id = os.environ.get('CLIENT_ID', 'YOUR_CLIENT_ID')\n    client_secret = os.environ.get('CLIENT_SECRET', 'YOUR_CLIENT_SECRET')\n    user_id = os.environ.get('USER_ID', 'YOUR_USER_ID') # User to fetch messages from\n\n    # Ensure required environment variables are set\n    if not all([tenant_id, client_id, client_secret, user_id]):\n        print(\"Please set TENANT_ID, CLIENT_ID, CLIENT_SECRET, and USER_ID environment variables.\")\n        return\n\n    # For app-only permissions, use the .default scope\n    scopes = ['https://graph.microsoft.com/.default']\n\n    # Create a credential object\n    credential = ClientSecretCredential(\n        tenant_id=tenant_id,\n        client_id=client_id,\n        client_secret=client_secret\n    )\n\n    # Create an authentication provider\n    auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes)\n\n    # Create a GraphServiceClient\n    client = GraphServiceClient(auth_provider)\n\n    try:\n        # Fetch messages for a specific user\n        # Note: This requires Mail.Read.All application permission or Mail.Read delegated permission for the user_id\n        # if using delegated flow.\n        messages_collection = await client.users.by_user_id(user_id).messages.get()\n\n        if messages_collection and messages_collection.value:\n            print(f\"Successfully fetched {len(messages_collection.value)} messages for user {user_id}:\")\n            for msg in messages_collection.value:\n                print(f\"  Subject: {msg.subject}, From: {msg.sender.email_address.address}\")\n        else:\n            print(f\"No messages found for user {user_id}.\")\n\n    except Exception as e:\n        print(f\"Error fetching messages: {e}\")\n\nif __name__ == '__main__':\n    asyncio.run(main())","lang":"python","description":"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."},"warnings":[{"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`.","message":"Major 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'.","severity":"breaking","affected_versions":"Upgrading from pre-1.0.0 versions (e.g., msgraph-core==0.2.2) to msgraph-sdk>=1.0.0."},{"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.","message":"The 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`).","severity":"gotcha","affected_versions":"All versions >=1.0.0."},{"fix":"Pass the raw byte content of the file directly to `content_bytes`. Do not manually base64 encode the content before assigning it.","message":"When 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.","severity":"gotcha","affected_versions":"All versions."},{"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'.","message":"The `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.","severity":"gotcha","affected_versions":"All versions."},{"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.","message":"There 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.","severity":"gotcha","affected_versions":"All versions."},{"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.","message":"The 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.","severity":"gotcha","affected_versions":"All versions."}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}