To start writing code and making requests to the Microsoft Graph service, you need to set up an authentication provider. This object will authenticate your requests to Microsoft Graph. For authentication, the Microsoft Graph Python SDK supports both sync and async credential classes from Azure Identity. Which library to choose depends on the type of application you are building.
Note: For authentication we support both sync and async credential classes from azure.identity. Please see the azure identity docs for more information.
The easiest way to filter this decision is by looking at the permissions set you'd use. Microsoft Graph supports 2 different types of permissions: delegated and application permissions:
Application permissions are used when you don’t need a user to login to your app, but the app will perform tasks on its own and run in the background.
Delegated permissions, also called scopes, are used when your app requires a user to login and interact with data related to this user in a session.
The following table lists common libraries by permissions set.
Once you've picked an authentication library, we can initiate the authentication provider in your app. The following example uses ClientSecretCredential with application permissions.
You must create GraphServiceClient object to make requests against the service. To create a new instance of this class, you need to provide credentials and scopes, which can authenticate requests to Microsoft Graph.
# 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)
After you have a GraphServiceClient that is authenticated, you can begin making calls against the service. The requests against the service look like our REST API.
Note: This SDK offers an asynchronous API by default. Async is a concurrency model that is far more efficient than multi-threading, and can provide significant performance benefits and enable the use of long-lived network connections such as WebSockets. We support popular python async environments such as asyncio, anyio or trio.
The following is a complete example that shows how to fetch a user from Microsoft Graph.
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())
Note that to calling me requires a signed-in user and therefore delegated permissions. See Authenticating Users for more:
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())
3.1 Error Handling
Failed requests raise APIError exceptions. You can handle these exceptions using trycatch statements.
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())
3.2 Pagination
By default a maximum of 100 rows are returned but in the response if odata_next_link is present, it can be used to fetch the next batch of max 100 rows. Here's an example to fetch the initial rows of members in a group, then iterate over the pages of rows using the odata_next_link
# 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}")
Use together with msgraph-sdk: extensions, drivers, servers and companion tools.
msalPythie’s Index: 90The Microsoft Authentication Library (MSAL) for Python library enables your app to access the Microsoft Cloud by supporting authentication of users with Microsoft Azure Active Directory accounts (AAD) and Microsoft Accounts (MSA) using industry standard OAuth2 and OpenID Connect.177.3M downloads/mo