Microsoft 365 & Microsoft Graph Library for Python
Project description
About
Office 365 & Microsoft Graph library for Python
Usage
- Installation
- Working with SharePoint API
- Working with Outlook API
- Working with OneDrive API
- Working with Teams API
- Working with OneNote API
- Working with Planner API
Status
Installation
Use pip:
pip install Office365-REST-Python-Client
Note
Alternatively the latest version could be directly installed via GitHub:
pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git
Authentication Credentials
For the following examples, relevant credentials can be found in the Azure Portal.
Steps to access:
- Login to the home page of the Azure Portal
- Navigate to "Azure Active Directory" using the three bars in the top right corner of the portal
- Select "App registrations" in the navigation panel on the left
- Search for and select your relevant application
- In the application's "Overview" page, the client id can be found under "Application (client) id"
- In the application's "Certificates & Secrets" page, the client secret can be found under the "Value" of the "Client Secrets." If there is no client secret yet, create one here.
Working with SharePoint API
The list of supported API versions:
- SharePoint 2013 REST API and above
- SharePoint Online & OneDrive for Business REST API
Authentication
The following auth flows are supported:
-
app principals flow:
ClientContext.with_credentials(client_credentials)
Usage:
client_credentials = ClientCredential('{client_id}','{client_secret}') ctx = ClientContext('{url}').with_credentials(client_credentials)
Documentation: refer Granting access using SharePoint App-Only for a details
Example: connect_with_app_principal.py
-
user credentials flow:
ClientContext.with_credentials(user_credentials)
Usage:
user_credentials = UserCredential('{username}','{password}') ctx = ClientContext('{url}').with_credentials(user_credentials)
Example: connect_with_user_credential.py
-
certificate credentials flow:
ClientContext.with_certificate(tenant, client_id, thumbprint, cert_path)
Documentation: Granting access via Azure AD App-Only
Example: connect_with_client_certificate.py
Examples
There are two approaches available to perform API queries:
ClientContext class
- where you target SharePoint resources such asWeb
,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']))
-
RequestOptions 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.runtime.http.request_options import RequestOptions
from office365.sharepoint.client_context import ClientContext
site_url = "https://{your-tenant-prefix}.sharepoint.com"
ctx = ClientContext(site_url).with_credentials(UserCredential("{username}", "{password}"))
request = RequestOptions("{0}/_api/web/".format(site_url))
response = ctx.pending_request().execute_request_direct(request)
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
Working with Outlook API
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 APIv2.0
version (preferable nowadays, refer transition to Microsoft Graph-based Outlook REST API for a details)
-OutlookClient
which targets Outlook APIv1.0
version (not recommended for usage sincev1.0
version is being deprecated.)
Authentication
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/
import msal
from office365.graph_client import GraphClient
def acquire_token():
"""
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
client = GraphClient(acquire_token)
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)
Example
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(acquire_token_func)
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:
- download a message
- list messages
- move messages to a different folder
- search messages
- send messages
- send messages with attachments
- enable sending emails on behalf of another user in your organization
Refer to examples section for other scenarios
Working with OneDrive API
Documentation
Authentication
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
Examples
Example: list available drives
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(acquire_token_func)
drives = client.drives.get().execute_query()
for drive in drives:
print("Drive url: {0}".format(drive.web_url))
Example: download the contents of a DriveItem(folder facet)
from office365.graph_client import GraphClient
client = GraphClient(acquire_token_func)
# 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.
Working with Microsoft Teams API
Authentication
The Microsoft Authentication Library (MSAL) for Python which comes as a dependency is used to obtain token
Examples
Example: create a new team under a group
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
Working with Microsoft Onenote API
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(acquire_token_func)
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()
Working with Microsoft Planner API
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()
Third Party Libraries and Dependencies
The following libraries will be installed when you install the client library:
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file Office365-REST-Python-Client-2.4.1.tar.gz
.
File metadata
- Download URL: Office365-REST-Python-Client-2.4.1.tar.gz
- Upload date:
- Size: 435.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.0 CPython/3.10.6
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8e561bb0f20ba3b27e0d3b365d6bcd00a8eb928b11f013aa813f1d146cf29402 |
|
MD5 | b7e39e6d61d19098198637c42aef9bde |
|
BLAKE2b-256 | 4036654255a941246916a91887a14b8f34d1c5249e3a67c80f390d8eabf320d6 |
File details
Details for the file Office365_REST_Python_Client-2.4.1-py3-none-any.whl
.
File metadata
- Download URL: Office365_REST_Python_Client-2.4.1-py3-none-any.whl
- Upload date:
- Size: 857.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.0 CPython/3.10.6
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 58cfed83c9e8f44fcbbd7404422467d6ad2e0a58d242f676cf727e148e3055de |
|
MD5 | d376470ee53bc1bdd8ad2fffa79f196e |
|
BLAKE2b-256 | 1d590d27a7b7a14ecb05c3dc018167774f27aa33283e141b3bd1157dd9fe437a |