Productivity
Microsoft 365 & Microsoft Graph library for Python
Use pip:
pip install Office365-REST-Python-Client
Alternatively the latest version could be directly installed via GitHub:
pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git
For the following examples, relevant credentials can be found in the Azure Portal.
Steps to access:
The ClientContext
client provides the support for a legacy SharePoint REST and OneDrive for Business REST APIs,
the list of supported versions:
The following auth flows are supported:
This auth method is compatible with SharePoint on-premises and still relevant model in both SharePoint on-premises as SharePoint Online, the following methods are available:
ClientContext.with_credentials(client_credentials)
ClientContext.with_client_credentials(client_id, client_secret)
Usage:
client_credentials = ClientCredential('{client_id}','{client_secret}')
ctx = ClientContext('{url}').with_credentials(client_credentials)
Documentation:
Example: connect_with_app_principal.py
Usage:
user_credentials = UserCredential('{username}','{password}')
ctx = ClientContext('{url}').with_credentials(user_credentials)
Example: connect_with_user_credential.py
Documentation:
Example: with_certificate.py
to login interactively i.e. via a local browser
Prerequisite:
In Azure Portal, configure the Redirect URI of your "Mobile and Desktop application" as
http://localhost
.
Example: connect_interactive.py
Usage:
from office365.sharepoint.client_context import ClientContext
ctx = ClientContext("{site-url}").with_interactive("{tenant-name-or-id}", "{client-id}")
me = ctx.web.current_user.get().execute_query()
print(me.login_name)
There are two approaches available to perform API queries:
ClientContext class
- where you target SharePoint resources such as Web
, ListItem
and etc (recommended)from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext
site_url = "https://{your-tenant-prefix}.sharepoint.com"
ctx = ClientContext(site_url).with_credentials(UserCredential("{username}", "{password}"))
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Web title: {0}".format(web.properties['Title']))
or alternatively via method chaining (a.k.a Fluent Interface):
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.client_context import ClientContext
site_url = "https://{your-tenant-prefix}.sharepoint.com"
ctx = ClientContext(site_url).with_credentials(UserCredential("{username}", "{password}"))
web = ctx.web.get().execute_query()
print("Web title: {0}".format(web.properties['Title']))
SharePointRequest class
- where you construct REST queries (and no model is involved)
The example demonstrates how to read Web
properties:
import json
from office365.runtime.auth.user_credential import UserCredential
from office365.sharepoint.request import SharePointRequest
site_url = "https://{your-tenant-prefix}.sharepoint.com"
request = SharePointRequest(site_url).with_credentials(UserCredential("{username}", "{password}"))
response = request.execute_request("web")
json = json.loads(response.content)
web_title = json['d']['Title']
print("Web title: {0}".format(web_title))
The list of examples:
Working with files
Working with lists and list items
Refer examples section for another scenarios
To enable authentication to specific Azure environment endpoints, add the environment
parameter when calling the
ClientContext class
with .with_user_credentials
, .with_client_credentials
, or .with_credentials
Example:
from office365.azure_env import AzureEnvironment
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.client_credential import ClientCredential
client_credentials = ClientCredential('{client_id}','{client_secret}')
ctx = ClientContext('{site-url}', environment=AzureEnvironment.USGovernmentHigh).with_credentials(client_credentials)
The list of supported APIs:
Since Outlook REST APIs are available in both Microsoft Graph and the Outlook API endpoint, the following clients are available:
GraphClient
which targets Outlook API v2.0
version (preferable nowadays, refer transition to Microsoft Graph-based Outlook REST API for a details)OutlookClient
which targets Outlook API v1.0
version (not recommended for usage since v1.0
version is being deprecated.)The Microsoft Authentication Library (MSAL) for Python which comes as a dependency is used as a default library to obtain tokens to call Microsoft Graph API.
Using Microsoft Authentication Library (MSAL) for Python
Note: access token is getting acquired via Client Credential flow in the provided examples. Other forms of token acquisition can be found here: https://msal-python.readthedocs.io/en/latest/
from office365.graph_client import GraphClient
client = GraphClient(tenant='{tenant_name_or_id}').with_client_secret(
client_id='{client_id}',
client_secret='{client_secret}'
)
Example: with_client_secret
But in terms of Microsoft Graph API authentication, another OAuth spec compliant libraries such as adal are supported as well.
Using ADAL Python
Usage
import adal
from office365.graph_client import GraphClient
def acquire_token_func():
authority_url = 'https://login.microsoftonline.com/{tenant_id_or_name}'
auth_ctx = adal.AuthenticationContext(authority_url)
token = auth_ctx.acquire_token_with_client_credentials(
"https://graph.microsoft.com",
"{client_id}",
"{client_secret}")
return token
client = GraphClient(acquire_token_func)
The example demonstrates how to send an email via Microsoft Graph endpoint.
Note: access token is getting acquired via Client Credential flow
from office365.graph_client import GraphClient
client = GraphClient(tenant='{tenant_name_or_id}').with_username_and_password(
'{client_id}', '{username}', '{password}'
)
client.me.send_mail(
subject="Meet for lunch?",
body="The new cafeteria is open.",
to_recipients=["fannyd@contoso.onmicrosoft.com"]
).execute_query()
Additional examples & scenarios:
Refer to examples section for other scenarios
The Microsoft Authentication Library (MSAL) for Python which comes as a dependency is used to obtain token
import msal
def acquire_token_func():
"""
Acquire token via MSAL
"""
authority_url = 'https://login.microsoftonline.com/{tenant_id_or_name}'
app = msal.ConfidentialClientApplication(
authority=authority_url,
client_id='{client_id}',
client_credential='{client_secret}'
)
token = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
return token
The example demonstrates how to enumerate and print drive's url
which corresponds to list available drives
endpoint
Note: access token is getting acquired via Client Credential flow
from office365.graph_client import GraphClient
tenant_name = "contoso.onmicrosoft.com"
client = GraphClient(tenant=tenant_name)
drives = client.drives.get().execute_query()
for drive in drives:
print("Drive url: {0}".format(drive.web_url))
from office365.graph_client import GraphClient
client = GraphClient(tenant="contoso.onmicrosoft.com")
# retrieve drive properties
drive = client.users["{user_id_or_principal_name}"].drive.get().execute_query()
# download files from OneDrive into local folder
with tempfile.TemporaryDirectory() as path:
download_files(drive.root, path)
where
def download_files(remote_folder, local_path):
drive_items = remote_folder.children.get().execute_query()
for drive_item in drive_items:
if drive_item.file is not None: # is file?
# download file content
with open(os.path.join(local_path, drive_item.name), 'wb') as local_file:
drive_item.download(local_file).execute_query()
Additional examples:
Refer to OneDrive examples section for more examples.
The Microsoft Authentication Library (MSAL) for Python which comes as a dependency is used to obtain token
The example demonstrates how create a new team under a group
which corresponds to Create team
endpoint
from office365.graph_client import GraphClient
client = GraphClient(acquire_token_func)
new_team = client.groups["{group-id}"].add_team().execute_query_retry()
Additional examples:
Refer to examples section for other scenarios
The library supports OneNote API in terms of calls to a user's OneNote notebooks, sections, and pages in a personal or organization account
Example: Create a new page
from office365.graph_client import GraphClient
client = GraphClient(tenant='{tenant_name_or_id}').with_username_and_password(
'{client_id}', '{username}', '{password}'
)
files = {}
with open("./MyPage.html", 'rb') as f, \
open("./MyImage.png", 'rb') as img_f, \
open("./MyDoc.pdf", 'rb') as pdf_f:
files["imageBlock1"] = img_f
files["fileBlock1"] = pdf_f
page = client.me.onenote.pages.add(presentation_file=f, attachment_files=files).execute_query()
The example demonstrates how to create a new planner task
which corresponds to Create plannerTask
endpoint:
from office365.graph_client import GraphClient
client = GraphClient(acquire_token_func)
task = client.planner.tasks.add(title="New task", planId="--plan id goes here--").execute_query()
The following libraries will be installed when you install the client library: