Build Python apps with Microsoft Graph
This tutorial teaches you how to build a Python console app that uses the Microsoft Graph API.
Important
The Microsoft Graph Core Python Client Library is currently in preview and should not be used in production. During this period breaking changes are expected to happen. This tutorial was written with version 0.2.2.
Tip
If you prefer to just download the completed tutorial, you can download or clone the GitHub repository.
Prerequisites
Before you start this tutorial, you should have Python and pip installed on your development machine.
You should also have either a personal Microsoft account with a mailbox on Outlook.com, or a Microsoft work or school account. If you don't have a Microsoft account, there are a couple of options to get a free account:
- You can sign up for a new personal Microsoft account.
- You can sign up for the Microsoft 365 Developer Program to get a free Microsoft 365 subscription.
Note
This tutorial was written with Python version 3.10.4 and pip version 20.0.2. The steps in this guide may work with other versions, but that has not been tested.
Register the app in the portal
In this exercise you will register a new application in Azure Active Directory to enable user authentication. You can register an application using the Azure Active Directory admin center, or by using the Microsoft Graph PowerShell SDK.
Important
The Microsoft Graph Core Python Client Library is currently in preview and should not be used in production. During this period breaking changes are expected to happen. This tutorial was written with version 0.2.2.
Register application for user authentication
In this section you will register an application that will support user authentication using device code flow.
Open a browser and navigate to the Azure Active Directory admin center and login using a personal account (aka: Microsoft Account) or Work or School Account.
Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.

Select New registration. Enter a name for your application, for example,
Python Graph Tutorial.Set Supported account types as desired. The options are:
Option Who can sign in? Accounts in this organizational directory only Only users in your Microsoft 365 organization Accounts in any organizational directory Users in any Microsoft 365 organization (work or school accounts) Accounts in any organizational directory ... and personal Microsoft accounts Users in any Microsoft 365 organization (work or school accounts) and personal Microsoft accounts Leave Redirect URI empty.
Select Register. On the application's Overview page, copy the value of the Application (client) ID and save it, you will need it in the next step. If you chose Accounts in this organizational directory only for Supported account types, also copy the Directory (tenant) ID and save it.

Select Authentication under Manage. Locate the Advanced settings section and change the Allow public client flows toggle to Yes, then choose Save.

Note
Notice that you did not configure any Microsoft Graph permissions on the app registration. This is because the sample will use dynamic consent to request specific permissions for user authentication.
Create a Python console app
Begin by creating a new Python file.
Important
The Microsoft Graph Core Python Client Library is currently in preview and should not be used in production. During this period breaking changes are expected to happen. This tutorial was written with version 0.2.2.
Create a new file named main.py and add the following code.
print ('Hello world!')Save the file and use the following command to run the file.
python3 main.pyIf it works, the app should output
Hello world!.
Install dependencies
Before moving on, add some additional dependencies that you will use later.
- Azure Identity client library for Python to authenticate the user and acquire access tokens.
- Microsoft Graph Core Python Client Library (preview) to make calls to the Microsoft Graph.
Run the following commands in your CLI to install the dependencies.
python3 -m pip install azure-identity
python3 -m pip install msgraph-core
Load application settings
In this section you'll add the details of your app registration to the project.
Create a file in the same directory as main.py named config.cfg and add the following code.
[azure] clientId = YOUR_CLIENT_ID_HERE clientSecret = YOUR_CLIENT_SECRET_HERE_IF_USING_APP_ONLY tenantId = YOUR_TENANT_ID_HERE_IF_USING_APP_ONLY authTenant = common graphUserScopes = User.Read Mail.Read Mail.SendUpdate the values according to the following table.
Setting Value clientIdThe client ID of your app registration authTenantIf you chose the option to only allow users in your organization to sign in, change this value to your tenant ID. Otherwise leave as common.Tip
Optionally, you can set these values in a separate file named config.dev.cfg.
Design the app
In this section you will create a simple console-based menu.
Open main.py and replace its entire contents with the following code.
import configparser from graph import Graph def main(): print('Python Graph Tutorial\n') # Load settings config = configparser.ConfigParser() config.read(['config.cfg', 'config.dev.cfg']) azure_settings = config['azure'] graph: Graph = Graph(azure_settings) greet_user(graph) choice = -1 while choice != 0: print('Please choose one of the following options:') print('0. Exit') print('1. Display access token') print('2. List my inbox') print('3. Send mail') print('4. List users (requires app-only)') print('5. Make a Graph call') try: choice = int(input()) except ValueError: choice = -1 if choice == 0: print('Goodbye...') elif choice == 1: display_access_token(graph) elif choice == 2: list_inbox(graph) elif choice == 3: send_mail(graph) elif choice == 4: list_users(graph) elif choice == 5: make_graph_call(graph) else: print('Invalid choice!\n')Add the following placeholder methods at the end of the file. You'll implement them in later steps.
def greet_user(graph: Graph): # TODO return def display_access_token(graph: Graph): # TODO return 1 def list_inbox(graph: Graph): # TODO return def send_mail(graph: Graph): # TODO return def list_users(graph: Graph): # TODO return def make_graph_call(graph: Graph): # TODO returnAdd the following line to call
mainat the end of the file.# Run main main()
This implements a basic menu and reads the user's choice from the command line.
Add user authentication
In this section you will extend the application from the previous exercise to support authentication with Azure AD. This is required to obtain the necessary OAuth access token to call the Microsoft Graph. In this step you will integrate the Azure Identity client library for Python into the application and configure authentication for the Microsoft Graph Core Python Client Library (preview).
Important
The Microsoft Graph Core Python Client Library is currently in preview and should not be used in production. During this period breaking changes are expected to happen. This tutorial was written with version 0.2.2.
The Azure Identity library provides a number of TokenCredential classes that implement OAuth2 token flows. The Microsoft Graph client library uses those classes to authenticate calls to Microsoft Graph. In this example, we'll use the following TokenCredential classes.
DeviceCodeCredentialimplements the device code flow for user authentication.ClientSecretCredentialimplements the client credentials flow for app-only authentication. You will use this class in the optional app-only sections.
Configure Graph client for user authentication
In this section you will use the DeviceCodeCredential class to request an access token by using the device code flow.
Create a new file named graph.py and add the following code to that file.
import json from configparser import SectionProxy from azure.identity import DeviceCodeCredential, ClientSecretCredential from msgraph.core import GraphClient class Graph: settings: SectionProxy device_code_credential: DeviceCodeCredential user_client: GraphClient client_credential: ClientSecretCredential app_client: GraphClient def __init__(self, config: SectionProxy): self.settings = config client_id = self.settings['clientId'] tenant_id = self.settings['authTenant'] graph_scopes = self.settings['graphUserScopes'].split(' ') self.device_code_credential = DeviceCodeCredential(client_id, tenant_id = tenant_id) self.user_client = GraphClient(credential=self.device_code_credential, scopes=graph_scopes)This code declares two private properties, a
DeviceCodeCredentialobject and aGraphClientobject. Theinitialize_graph_for_user_authfunction creates a new instance ofDeviceCodeCredential, then uses that instance to create a new instance ofGraphClient. Every time an API call is made to Microsoft Graph through theuser_client, it will use the provided credential to get an access token.Add the following function to graph.py.
def get_user_token(self): graph_scopes = self.settings['graphUserScopes'] access_token = self.device_code_credential.get_token(graph_scopes) return access_token.tokenReplace the empty
display_access_tokenfunction in main.py with the following.def display_access_token(graph: Graph): token = graph.get_user_token() print('User token:', token, '\n')Build and run the app. Enter
1when prompted for an option. The application displays a URL and device code.Python Graph Tutorial Please choose one of the following options: 0. Exit 1. Display access token 2. List my inbox 3. Send mail 4. List users (requires app-only) 5. Make a Graph call 1 To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code RB2RUD56D to authenticate.Open a browser and browse to the URL displayed. Enter the provided code and sign in.
Important
Be mindful of any existing Microsoft 365 accounts that are logged into your browser when browsing to
https://microsoft.com/devicelogin. Use browser features such as profiles, guest mode, or private mode to ensure that you authenticate as the account you intend to use for testing.Once completed, return to the application to see the access token.
Tip
For validation and debugging purposes only, you can decode user access tokens (for work or school accounts only) using Microsoft's online token parser at https://jwt.ms. This can be useful if you encounter token errors when calling Microsoft Graph. For example, verifying that the
scpclaim in the token contains the expected Microsoft Graph permission scopes.
Get user
In this section you will incorporate the Microsoft Graph into the application. For this application, you will use the Microsoft Graph Core Python Client Library (preview) to make calls to Microsoft Graph.
Important
The Microsoft Graph Core Python Client Library is currently in preview and should not be used in production. During this period breaking changes are expected to happen. This tutorial was written with version 0.2.2.
Add the following function to graph.py.
def get_user(self): endpoint = '/me' # Only request specific properties select = 'displayName,mail,userPrincipalName' request_url = f'{endpoint}?$select={select}' user_response = self.user_client.get(request_url) return user_response.json()Replace the empty
greet_userfunction in main.py with the following.def greet_user(graph: Graph): user = graph.get_user() print('Hello,', user['displayName']) # For Work/school accounts, email is in mail property # Personal accounts, email is in userPrincipalName print('Email:', user['mail'] or user['userPrincipalName'], '\n')
If you run the app now, after you log in the app welcomes you by name.
Hello, Megan Bowen!
Email: MeganB@contoso.com
Code explained
Consider the code in the get_user function. It's only a few lines, but there are some key details to notice.
Accessing 'me'
The function builds a request to the Get user API. This API is accessible two ways:
GET /me
GET /users/{user-id}
In this case, the code will call the GET /me API endpoint. This is a shortcut method to get the authenticated user without knowing their user ID.
Note
Because the GET /me API endpoint gets the authenticated user, it is only available to apps that use user authentication. App-only authentication apps cannot access this endpoint.
Requesting specific properties
The function uses the $select query parameter to specify the set of properties it needs. Microsoft Graph will return only the requested properties in the response.
List inbox
In this section you will add the ability to list messages in the user's email inbox.
Important
The Microsoft Graph Core Python Client Library is currently in preview and should not be used in production. During this period breaking changes are expected to happen. This tutorial was written with version 0.2.2.
Add the following function to graph.py.
def get_inbox(self): endpoint = '/me/mailFolders/inbox/messages' # Only request specific properties select = 'from,isRead,receivedDateTime,subject' # Get at most 25 results top = 25 # Sort by received time, newest first order_by = 'receivedDateTime DESC' request_url = f'{endpoint}?$select={select}&$top={top}&$orderBy={order_by}' inbox_response = self.user_client.get(request_url) return inbox_response.json()Replace the empty
list_inboxfunction in main.py with the following.def list_inbox(graph: Graph): message_page = graph.get_inbox() # Output each message's details for message in message_page['value']: print('Message:', message['subject']) print(' From:', message['from']['emailAddress']['name']) print(' Status:', 'Read' if message['isRead'] else 'Unread') print(' Received:', message['receivedDateTime']) # If @odata.nextLink is present more_available = '@odata.nextLink' in message_page print('\nMore messages available?', more_available, '\n')Run the app, sign in, and choose option 2 to list your inbox.
Please choose one of the following options: 0. Exit 1. Display access token 2. List my inbox 3. Send mail 4. List users (requires app-only) 5. Make a Graph call 2 Message: Updates from Ask HR and other communities From: Contoso Demo on Yammer Status: Read Received: 2022-04-26T19:19:05Z Message: Employee Initiative Thoughts From: Patti Fernandez Status: Read Received: 2022-04-25T19:43:57Z Message: Voice Mail (11 seconds) From: Alex Wilber Status: Unread Received: 2022-04-22T19:43:23Z Message: Our Spring Blog Update From: Alex Wilber Status: Unread Received: 2022-04-19T22:19:02Z Message: Atlanta Flight Reservation From: Alex Wilber Status: Unread Received: 2022-04-19T15:15:56Z Message: Atlanta Trip Itinerary - down time From: Alex Wilber Status: Unread Received: 2022-04-18T14:24:16Z ... More messages available? True
Code explained
Consider the code in the get_inbox function.
Accessing well-known mail folders
The function builds a request to the List messages API. Because it includes the /mailFolders/inbox segment in the request URL, the API will only return messages in the requested mail folder. In this case, because the inbox is a default, well-known folder inside a user's mailbox, it's accessible via its well-known name. Non-default folders are accessed the same way, by replacing the well-known name with the mail folder's ID property. For details on the available well-known folder names, see mailFolder resource type.
Accessing a collection
Unlike the get_user function from the previous section, which returns a single object, this method returns a collection of messages. Most APIs in Microsoft Graph that return a collection do not return all available results in a single response. Instead, they use paging to return a portion of the results while providing a method for clients to request the next "page".
Default page sizes
APIs that use paging implement a default page size. For messages, the default value is 10. Clients can request more (or less) by using the $top query parameter.
Note
The value passed in $top is an upper-bound, not an explicit number. The API returns a number of messages up to the specified value.
Getting subsequent pages
If there are more results available on the server, collection responses include an @odata.nextLink property with an API URL to access the next page. If this property is present, there are more results available.
Sorting collections
The function uses the $orderby query parameter to request results sorted by the time the message is received (receivedDateTime property). It includes the DESC keyword so that messages received more recently are listed first.
Send mail
In this section you will add the ability to send an email message as the authenticated user.
Important
The Microsoft Graph Core Python Client Library is currently in preview and should not be used in production. During this period breaking changes are expected to happen. This tutorial was written with version 0.2.2.
Add the following function to graph.py.
def send_mail(self, subject: str, body: str, recipient: str): request_body = { 'message': { 'subject': subject, 'body': { 'contentType': 'text', 'content': body }, 'toRecipients': [ { 'emailAddress': { 'address': recipient } } ] } } request_url = '/me/sendmail' self.user_client.post(request_url, data=json.dumps(request_body), headers={'Content-Type': 'application/json'})Replace the empty
send_mailfunction in main.py with the following.def send_mail(graph: Graph): # Send mail to the signed-in user # Get the user for their email address user = graph.get_user() user_email = user['mail'] or user['userPrincipalName'] graph.send_mail('Testing Microsoft Graph', 'Hello world!', user_email) print('Mail sent.\n')Run the app, sign in, and choose option 3 to send an email to yourself.
Please choose one of the following options: 0. Exit 1. Display access token 2. List my inbox 3. Send mail 4. List users (requires app-only) 5. Make a Graph call 3 Mail sent.Note
If you are testing with a developer tenant from the Microsoft 365 Developer Program, the email you send may not be delivered, and you may receive a non-delivery report. If this happens to you, please contact support via the Microsoft 365 admin center.
Code explained
Consider the code in the send_mail function.
Sending mail
The function builds a request to the Send mail API.
Creating objects
Unlike the previous calls to Microsoft Graph that only read data, this call creates data. To do this with the client library you create a dictionary representing the request payload, set the desired properties, then send it in the API call. Because the call is sending data, the post method is used instead of get.
Optional: configure app-only authentication
In this section you will update the app registration from the previous section to support app-only authentication. App-only authentication is a good choice for background services, and there are also some APIs that only support app-only authentication. You only need to complete this section if you intend to use the app-only portions of this tutorial. If not, you can safely skip to the next step.
Important
The Microsoft Graph Core Python Client Library is currently in preview and should not be used in production. During this period breaking changes are expected to happen. This tutorial was written with version 0.2.2.
Important
The steps in this section require a work/school account with the Global administrator role.
Open the app registration from the previous section in the Azure AD admin center.
Select API permissions under Manage.
Remove the default User.Read permission under Configured permissions by selecting the ellipses (...) in its row and selecting Remove permission.
Select Add a permission, then Microsoft Graph.
Select Application permissions.
Select User.Read.All, then select Add permissions.
Select Grant admin consent for..., then select Yes to provide admin consent for the selected permission.

Select Certificates and secrets under Manage, then select New client secret.
Enter a description, choose a duration, and select Add.
Copy the secret from the Value column, you will need it in the next steps.
Important
This client secret is never shown again, so make sure you copy it now.
Note
Notice that, unlike the steps when registering for user authentication, in this section you did configure Microsoft Graph permissions on the app registration. This is because app-only auth uses the client credentials flow, which requires that permissions be configured on the app registration. See The .default scope for details.
Optional: add app-only authentication
In this section you will add app-only authentication to the application. This section is optional, and requires completion of Optional: configure app-only authentication. These steps can only be completed with a work or school account.
Important
The Microsoft Graph Core Python Client Library is currently in preview and should not be used in production. During this period breaking changes are expected to happen. This tutorial was written with version 0.2.2.
Configure Graph client for app-only authentication
In this section you will use the ClientSecretCredential class to request an access token by using the client credentials flow.
Update the values in config.cfg (or config.dev.cfg) according to the following table.
Setting Value tenantIdYour organization's tenant ID clientSecretThe client secret generated in the previous step Add the following function to graph.py.
def ensure_graph_for_app_only_auth(self): if not hasattr(self, 'client_credential'): client_id = self.settings['clientId'] tenant_id = self.settings['tenantId'] client_secret = self.settings['clientSecret'] self.client_credential = ClientSecretCredential(tenant_id, client_id, client_secret) if not hasattr(self, 'app_client'): self.app_client = GraphClient(credential=self.client_credential, scopes=['https://graph.microsoft.com/.default'])
Optional: list users
In this section you will add the ability to list all users in your Azure Active Directory using app-only authentication. This section is optional, and requires completion of Optional: configure app-only authentication and Optional: add app-only authentication. These steps can only be completed with a work or school account.
Important
The Microsoft Graph Core Python Client Library is currently in preview and should not be used in production. During this period breaking changes are expected to happen. This tutorial was written with version 0.2.2.
Add the following function to graph.py.
def get_users(self): self.ensure_graph_for_app_only_auth() endpoint = '/users' # Only request specific properties select = 'displayName,id,mail' # Get at most 25 results top = 25 # Sort by display name order_by = 'displayName' request_url = f'{endpoint}?$select={select}&$top={top}&$orderBy={order_by}' users_response = self.app_client.get(request_url) return users_response.json()Replace the empty
list_inboxfunction in main.py with the following.def list_users(graph: Graph): users_page = graph.get_users() # Output each users's details for user in users_page['value']: print('User:', user['displayName']) print(' ID:', user['id']) print(' Email:', user['mail']) # If @odata.nextLink is present more_available = '@odata.nextLink' in users_page print('\nMore users available?', more_available, '\n')Run the app, sign in, and choose option 4 to list users.
Please choose one of the following options: 0. Exit 1. Display access token 2. List my inbox 3. Send mail 4. List users (requires app-only) 5. Make a Graph call 4 User: Adele Vance ID: 05fb57bf-2653-4396-846d-2f210a91d9cf Email: AdeleV@contoso.com User: Alex Wilber ID: a36fe267-a437-4d24-b39e-7344774d606c Email: AlexW@contoso.com User: Allan Deyoung ID: 54cebbaa-2c56-47ec-b878-c8ff309746b0 Email: AllanD@contoso.com User: Bianca Pisani ID: 9a7dcbd0-72f0-48a9-a9fa-03cd46641d49 Email: None User: Brian Johnson (TAILSPIN) ID: a8989e40-be57-4c2e-bf0b-7cdc471e9cc4 Email: BrianJ@contoso.com ... More users available? True
Code explained
Consider the code in the get_users function. It is very similar to the code in get_inbox:
- It gets a collection of users
- It uses
$selectto request specific properties - It uses
$topto limit the number of users returned - It uses
$orderByto sort the response
The key difference is that this code uses the app_client, not the user_client. Both clients use the same syntax and request builders, but were configured with different credentials.
Optional: add your own code
In this section you will add your own Microsoft Graph capabilities to the application. This could be a code snippet from Microsoft Graph documentation or Graph Explorer, or code that you created. This section is optional.
Important
The Microsoft Graph Core Python Client Library is currently in preview and should not be used in production. During this period breaking changes are expected to happen. This tutorial was written with version 0.2.2.
Update the app
Add the following function to graph.py.
def make_graph_call(self): # INSERT YOUR CODE HERE # Note: if using app_client, be sure to call # ensure_graph_for_app_only_auth before using it # self.ensure_graph_for_app_only_auth() returnReplace the empty
list_inboxfunction in main.py with the following.def make_graph_call(graph: Graph): graph.make_graph_call()
Choose an API
Find an API in Microsoft Graph you'd like to try. For example, the Create event API. You can use one of the examples in the API documentation, or create your own API request.
Configure permissions
Check the Permissions section of the reference documentation for your chosen API to see which authentication methods are supported. Some APIs don't support app-only, or personal Microsoft accounts, for example.
- To call an API with user authentication (if the API supports user (delegated) authentication), add the required permission scope in config.cfg.
- To call an API with app-only authentication (if the API supports it), add the required permission scope in the Azure AD admin center.
Add your code
Copy your code into the make_graph_call function in graph.py.
Congratulations!
You've completed the Python Microsoft Graph tutorial. Now that you have a working app that calls Microsoft Graph, you can experiment and add new features. Visit the Overview of Microsoft Graph to see all of the data you can access with Microsoft Graph.
Python samples
Have an issue with this section? If so, please give us some feedback so we can improve this section.