Microsoft Graph Core Library
The `msgraph-core` library is the foundational component for the Microsoft Graph Python SDK, providing core HTTP client capabilities and an abstraction layer for interacting with Microsoft Graph and other OData V4 services. It handles authentication integration, request building, and response parsing. Currently at version 1.3.8, it receives regular updates, typically aligning with the broader Microsoft Graph SDK release cadence.
Warnings
- breaking The `msgraph-core` library is part of the v2 Microsoft Graph Python SDK, which is a complete rewrite and entirely incompatible with the v1 SDK (e.g., `microsoftgraph.client` library). Migrating from v1 requires significant code changes and understanding of the new Kiota-based architecture.
- gotcha While `msgraph-core` provides `AzureIdentityAuthenticationProvider`, it does not bundle the `azure-identity` library. You must explicitly `pip install azure-identity` to use the convenient credential classes (e.g., `ClientSecretCredential`, `DefaultAzureCredential`).
- gotcha The `msgraph-core` library provides the low-level HTTP client adapter and authentication abstractions. For high-level, strongly-typed access to Microsoft Graph resources and their methods (e.g., `client.users.by_user_id('...').messages.get()`), most users should `pip install microsoftgraph-msgraph-sdk`, which is the generated client built on top of `msgraph-core`. Trying to manually build complex requests with `msgraph-core` can be cumbersome and error-prone.
Install
-
pip install msgraph-core -
pip install azure-identity
Imports
- GraphClientFactory
from msgraph_core import GraphClientFactory
- AzureIdentityAuthenticationProvider
from msgraph_core.authentication.azure_identity import AzureIdentityAuthenticationProvider
- ODataError
from msgraph_core.models import ODataError
Quickstart
import os
from msgraph_core import GraphClientFactory
from msgraph_core.authentication.azure_identity import AzureIdentityAuthenticationProvider
from azure.identity import ClientSecretCredential # Or any other credential
# 1. Get credentials (replace with your actual client_id, tenant_id, client_secret)
# For local testing, ensure these are set as environment variables or replace directly
tenant_id = os.environ.get("AZURE_TENANT_ID", "YOUR_TENANT_ID")
client_id = os.environ.get("AZURE_CLIENT_ID", "YOUR_CLIENT_ID")
client_secret = os.environ.get("AZURE_CLIENT_SECRET", "YOUR_CLIENT_SECRET")
# Scopes required for Microsoft Graph
scopes = ['https://graph.microsoft.com/.default']
# Basic check for credentials for a runnable example
if not all([tenant_id, client_id, client_secret]):
print("WARNING: Azure credentials not found in environment variables. Using placeholder values.")
print("Please set AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET for a real test.")
# Using placeholders for quickstart to be technically 'runnable' without env vars,
# but it will fail the auth handshake.
tenant_id = "_DUMMY_TENANT_ID_"
client_id = "_DUMMY_CLIENT_ID_"
client_secret = "_DUMMY_CLIENT_SECRET_"
try:
# 2. Create an authentication provider
credential = ClientSecretCredential(
tenant_id=tenant_id,
client_id=client_id,
client_secret=client_secret
)
auth_provider = AzureIdentityAuthenticationProvider(credential=credential, scopes=scopes)
# 3. Create a GraphClient instance using the factory
# The factory returns an instance of GraphClient which uses GraphRequestAdapter internally
# with default middleware, configured for Graph API requests.
graph_client = GraphClientFactory.create_with_default_middleware(auth_provider)
# 4. Make a request using the low-level client (part of msgraph-core)
print("Making a request to /me to demonstrate msgraph-core functionality...")
# Note: For real-world use with the full Graph API schema, consider msgraph-sdk.
response = graph_client.get('/me')
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
user_data = response.json()
print(f"Successfully fetched user data for: {user_data.get('displayName', 'Unknown User')}")
print(f"User ID: {user_data.get('id', 'N/A')}")
except Exception as e:
print(f"An error occurred: {e}")
if "AADSTS" in str(e):
print("Hint: This often indicates an issue with your Azure AD credentials or permissions.")
print("Check client ID, tenant ID, client secret, and API permissions (e.g., User.Read.All or User.Read).")