Skip to main content

The Microsoft Graph Python SDK

Project description

Microsoft Graph SDK for Python

Get started with the Microsoft Graph SDK for Python by integrating the Microsoft Graph API into your Python application.

Note:

  • This SDK allows you to build applications using the v1.0 of Microsoft Graph. If you want to try the latest Microsoft Graph APIs, try the beta SDK.

  • The Microsoft Graph Python SDK is currently in community preview. During this period we're expecting breaking changes to happen to the SDK as we make updates based on feedback. Don't use this SDK in production environments. For details see SDKs in preview or GA status.

1. Installation

pip install msgraph-sdk

Note: Enable long paths in your environment if you receive a Could not install packages due to an OSError. For details, see Enable Long Paths in Windows 10, Version 1607, and Later.

2. Getting started with Microsoft Graph

2.1 Register your application

Register your application by following the steps at Register your app with the Microsoft Identity Platform.

2.2 Select and create an authentication provider

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.

MSAL library Permissions set Common use case
ClientSecretCredential Application permissions Daemon apps or applications running in the background without a signed-in user.
DeviceCodeCredential Delegated permissions Enviroments where authentication is triggered in one machine and completed in another e.g in a cloud server.
InteractiveBrowserCredentials Delegated permissions Environments where a browser is available and the user wants to key in their username/password.
AuthorizationCodeCredentials Delegated permissions Usually for custom customer applications where the frontend calls the backend and waits for the authorization code at a particular url.

You can also use EnvironmentCredential, DefaultAzureCredential, OnBehalfOfCredential, or any other Azure Identity library.

Once you've picked an authentication library, we can initiate the authentication provider in your app. The following example uses ClientSecretCredential with application permissions.

import asyncio

from azure.identity.aio import ClientSecretCredential

credential = ClientSecretCredential("tenantID",
                                    "clientID",
                                    "clientSecret")
scopes = ['https://graph.microsoft.com/.default']

The following example uses DeviceCodeCredentials with delegated permissions.

import asyncio

from azure.identity import DeviceCodeCredential

credential = DeviceCodeCredential("client_id",
                                  "tenant_id")
graph_scopes = ['User.Read', 'Calendars.ReadWrite.Shared']

2.3 Initialize a GraphServiceClient object

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

credential = ClientSecretCredential(
    'TENANT_ID',
    'CLIENT_ID',
    'CLIENT_SECRET',
)
scopes = ['https://graph.microsoft.com/.default']
client = GraphServiceClient(credentials=credential, scopes=scopes)

The above example uses default scopes for app-only access. If using delegated access you can provide custom scopes:

# Example using sync credentials and delegated access.
from azure.identity import DeviceCodeCredential
from msgraph import GraphServiceClient

credential=DeviceCodeCredential(
    'CLIENT_ID',
    'TENANT_ID',
)
scopes = ['User.Read', 'Mail.Read']
client = GraphServiceClient(credentials=credential, scopes=scopes)

3. Make requests against the service

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 envronments 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()
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 try catch 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())

Documentation and resources

Upgrading

For detailed information on breaking changes, bug fixes and new functionality introduced during major upgrades, check out our Upgrade Guide

Issues

View or log issues on the Issues tab in the repo.

Contribute

Please read our Contributing guidelines carefully for advice on how to contribute to this repo.

Copyright and license

Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT license.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Third Party Notices

Third-party notices

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

msgraph-sdk-1.0.0a14.tar.gz (4.2 MB view details)

Uploaded Source

Built Distribution

msgraph_sdk-1.0.0a14-py3-none-any.whl (17.6 MB view details)

Uploaded Python 3

File details

Details for the file msgraph-sdk-1.0.0a14.tar.gz.

File metadata

  • Download URL: msgraph-sdk-1.0.0a14.tar.gz
  • Upload date:
  • Size: 4.2 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for msgraph-sdk-1.0.0a14.tar.gz
Algorithm Hash digest
SHA256 b0d3c7d6615fca967087e4261492bcac81cc0bb7f31662c818475c8ee767f991
MD5 b4085cb3d0a14d138708eca1ab53f0c2
BLAKE2b-256 afd2157f3409f4a41c263f8da0f12edb9224939691f7ab51cfc112dfe6e15bdc

See more details on using hashes here.

File details

Details for the file msgraph_sdk-1.0.0a14-py3-none-any.whl.

File metadata

File hashes

Hashes for msgraph_sdk-1.0.0a14-py3-none-any.whl
Algorithm Hash digest
SHA256 682013e3d490b8196eb57413f316d6187a5b8f98b0e3ddfa3d620d2fee16fdb1
MD5 11d45330b0f54c553fab93b0173da28f
BLAKE2b-256 26554063c1c4869c29b8b44911d37b8241f3bc38f47a1e4cd6a90d88619d90c0

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page