Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This tutorial teaches you how to build a Python console app that uses the Microsoft Graph API to access data on behalf of a user.
Note
To learn how to use Microsoft Graph to access data using app-only authentication, see this app-only authentication tutorial.
In this tutorial, you will:
Tip
As an alternative to following this tutorial, you can download the completed code through the quick start tool, which automates app registration and configuration. The downloaded code works without any modifications required.
You can also download or clone the GitHub repository and follow the instructions in the README to register an application and configure the project.
Prerequisites
Before you start this tutorial, you should have Python and pip installed on your development machine.
You should also have a Microsoft work or school account with an Exchange Online mailbox. If you don't have a Microsoft 365 tenant, you might qualify for one through the Microsoft 365 Developer Program; for details, see the FAQ. Alternatively, you can sign up for a one-month free trial or purchase a Microsoft 365 plan.
Note
This tutorial was written with Python version 3.10.4 and pip version 20.0.2. The steps in this guide might work with other versions, but that hasn't been tested.
Register an application for user authentication
Register an application that supports user authentication using device code flow. You can register an application using the Microsoft Entra admin center, or by using the Microsoft Graph PowerShell SDK.
Open a browser and navigate to the Microsoft Entra admin center and sign in using a Global administrator account.
Select Microsoft Entra ID in the left-hand navigation, expand Identity, expand Applications, then select App registrations.
Select New registration. Enter a name for your application, for example,
Graph User Auth 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'll 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 didn't configure any Microsoft Graph permissions on the app registration. The sample uses dynamic consent to request specific permissions for user authentication.
Create a Python console app
Begin by creating a new Python file.
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.py
If it works, the app should output
Hello world!
.
Install dependencies
Before moving on, add dependencies that you use later.
- Azure Identity client library for Python to authenticate the user and acquire access tokens.
- Microsoft Graph SDK for Python (preview) to make calls to the Microsoft Graph.
To install the dependencies, run the following commands in your CLI.
python3 -m pip install azure-identity
python3 -m pip install msgraph-sdk
Load application settings
Next, 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 tenantId = common graphUserScopes = User.Read Mail.Read Mail.Send
Update the values according to the following table.
Setting Value clientId
The client ID of your app registration tenantId
If 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
Continue by creating a simple console-based menu.
Create a new file named graph.py and add the following code to that file.
# Temporary placeholder class Graph: def __init__(self, config): self.settings = config
This code is a placeholder. You implement the
Graph
class in the next article.Open main.py and replace its entire contents with the following code.
import asyncio import configparser from msgraph.generated.models.o_data_errors.o_data_error import ODataError from graph import Graph async 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) await 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. Make a Graph call') try: choice = int(input()) except ValueError: choice = -1 try: if choice == 0: print('Goodbye...') elif choice == 1: await display_access_token(graph) elif choice == 2: await list_inbox(graph) elif choice == 3: await send_mail(graph) elif choice == 4: await make_graph_call(graph) else: print('Invalid choice!\n') except ODataError as odata_error: print('Error:') if odata_error.error: print(odata_error.error.code, odata_error.error.message)
Add the following placeholder methods at the end of the file. You implement them in later steps.
async def greet_user(graph: Graph): # TODO return async def display_access_token(graph: Graph): # TODO return async def list_inbox(graph: Graph): # TODO return async def send_mail(graph: Graph): # TODO return async def make_graph_call(graph: Graph): # TODO return
Add the following line to call
main
at the end of the file.# Run main asyncio.run(main())
This implements a basic menu and reads the user's choice from the command line.