npm 中文文档 npm 中文文档
指南
npmjs.com (opens new window)
指南
npmjs.com (opens new window)
  • 快速入门

    • npm 是什么?
    • npm 安装和更新
    • npm 防止权限错误
    • npm package.json 文件
    • npm 安装包
    • npm 更新包
    • npm 卸载包
    • npm 创建 Node.js 模块
    • npm 发布和更新包
    • npm 使用语义化版本
    • npm 使用 Dist-tags 标记包
    • npm 包和模块的了解
  • 命令行
  • 配置 npm

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:

  1. ``` sh
  2. pip install Office365-REST-Python-Client

  3. ```

Note


Alternatively the latestversion could be directly installed via GitHub:


  1. ``` sh
  2. pip install git+https://github.com/vgrem/Office365-REST-Python-Client.git

  3. ```

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:

  1. ``` sh
  2. client_credentials = ClientCredential('{client_id}','{client_secret}')
  3. ctx = ClientContext('{url}').with_credentials(client_credentials)

  4. ```

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:

  1. ``` sh
  2. user_credentials = UserCredential('{username}','{password}')
  3. ctx = ClientContext('{url}').with_credentials(user_credentials)

  4. ```

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 approachesavailable to perform API queries:

ClientContext class - where you target SharePoint resources such as Web, ListItem and etc (recommended)

  1. ``` python
  2. from office365.runtime.auth.user_credential import UserCredential
  3. from office365.sharepoint.client_context import ClientContext
  4. site_url = "https://{your-tenant-prefix}.sharepoint.com"
  5. ctx = ClientContext(site_url).with_credentials(UserCredential("{username}", "{password}"))
  6. web = ctx.web
  7. ctx.load(web)
  8. ctx.execute_query()
  9. print("Web title: {0}".format(web.properties['Title']))
  10. ```

or alternatively via method chaining (a.k.a Fluent Interface):

  1. ``` python
  2. from office365.runtime.auth.user_credential import UserCredential
  3. from office365.sharepoint.client_context import ClientContext
  4. site_url = "https://{your-tenant-prefix}.sharepoint.com"
  5. ctx = ClientContext(site_url).with_credentials(UserCredential("{username}", "{password}"))
  6. web = ctx.web.get().execute_query()
  7. print("Web title: {0}".format(web.properties['Title']))
  8. ```

RequestOptions class - where you construct REST queries (and no model is involved)

The example demonstrates how to read Web properties:

  1. ``` python
  2. import json
  3. from office365.runtime.auth.user_credential import UserCredential
  4. from office365.runtime.http.request_options import RequestOptions
  5. from office365.sharepoint.client_context import ClientContext
  6. site_url = "https://{your-tenant-prefix}.sharepoint.com"
  7. ctx = ClientContext(site_url).with_credentials(UserCredential("{username}", "{password}"))
  8. request = RequestOptions("{0}/_api/web/".format(site_url))
  9. response = ctx.pending_request().execute_request_direct(request)
  10. json = json.loads(response.content)
  11. web_title = json['d']['Title']
  12. print("Web title: {0}".format(web_title))
  13. ```

The list of examples:

Working with files

download a file
upload a file

Working with lists and list items

create a list item
read a list item
update a list item
delete a list item

Refer examples section for another scenarios

Working with Outlook API


The list of supported APIs:

Outlook Contacts REST API
Outlook Calendar REST API
Outlook Mail REST API

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 (preferablenowadays, 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.)

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/


  1. ``` python
  2. import msal
  3. from office365.graph_client import GraphClient

  4. def acquire_token():
  5.     """
  6.     Acquire token via MSAL
  7.     """
  8.     authority_url = 'https://login.microsoftonline.com/{tenant_id_or_name}'
  9.     app = msal.ConfidentialClientApplication(
  10.         authority=authority_url,
  11.         client_id='{client_id}',
  12.         client_credential='{client_secret}'
  13.     )
  14.     token = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
  15.     return token

  16. client = GraphClient(acquire_token)
  17. ```

But in terms of Microsoft Graph API authentication, another OAuth spec compliant libraries such as adal are supported as well.

Using ADAL Python

Usage

  1. ``` python
  2. import adal
  3. from office365.graph_client import GraphClient

  4. def acquire_token_func():
  5.     authority_url = 'https://login.microsoftonline.com/{tenant_id_or_name}'
  6.     auth_ctx = adal.AuthenticationContext(authority_url)
  7.     token = auth_ctx.acquire_token_with_client_credentials(
  8.         "https://graph.microsoft.com",
  9.         "{client_id}",
  10.         "{client_secret}")
  11.     return token

  12. client = GraphClient(acquire_token_func)
  13. ```

Example


The example demonstrates how to send an email via Microsoft Graph endpoint.

Note: access token is getting acquired via Client Credential flow


  1. ``` python
  2. from office365.graph_client import GraphClient

  3. client = GraphClient(acquire_token_func)

  4. client.me.send_mail(
  5.     subject="Meet for lunch?",
  6.     body="The new cafeteria is open.",
  7.     to_recipients=["fannyd@contoso.onmicrosoft.com"]
  8. ).execute_query()
  9. ```

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


OneDrive Graph API reference

Authentication


The Microsoft Authentication Library (MSAL) for Python which comes as a dependency is used to obtain token

  1. ``` python
  2. import msal

  3. def acquire_token_func():
  4.     """
  5.     Acquire token via MSAL
  6.     """
  7.     authority_url = 'https://login.microsoftonline.com/{tenant_id_or_name}'
  8.     app = msal.ConfidentialClientApplication(
  9.         authority=authority_url,
  10.         client_id='{client_id}',
  11.         client_credential='{client_secret}'
  12.     )
  13.     token = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
  14.     return token
  15. ```

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


  1. ``` python
  2. from office365.graph_client import GraphClient

  3. tenant_name = "contoso.onmicrosoft.com"
  4. client = GraphClient(acquire_token_func)
  5. drives = client.drives.get().execute_query()
  6. for drive in drives:
  7.     print("Drive url: {0}".format(drive.web_url))
  8. ```

Example: download the contents of a DriveItem(folder facet)

  1. ``` python
  2. from office365.graph_client import GraphClient
  3. client = GraphClient(acquire_token_func)
  4. # retrieve drive properties
  5. drive = client.users["{user_id_or_principal_name}"].drive.get().execute_query()
  6. # download files from OneDrive into local folder
  7. with tempfile.TemporaryDirectory() as path:
  8.     download_files(drive.root, path)
  9. ```

where

  1. ``` python
  2. def download_files(remote_folder, local_path):
  3.     drive_items = remote_folder.children.get().execute_query()
  4.     for drive_item in drive_items:
  5.         if drive_item.file is not None:  # is file?
  6.             # download file content
  7.             with open(os.path.join(local_path, drive_item.name), 'wb') as local_file:
  8.                 drive_item.download(local_file).execute_query()
  9. ```

Additional examples:

create list column
download file
export files
import files
list drives
list files

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

  1. ``` python
  2. from office365.graph_client import GraphClient
  3. client = GraphClient(acquire_token_func)
  4. new_team = client.groups["{group_id}"].add_team().execute_query_retry()
  5. ```

Additional examples:

create a team
create team from group
list all teams
list my teams
send messages

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

  1. ``` python
  2. from office365.graph_client import GraphClient
  3. client = GraphClient(acquire_token_func)

  4. files = {}
  5. with open("./MyPage.html", 'rb') as f, \
  6.     open("./MyImage.png", 'rb') as img_f, \
  7.     open("./MyDoc.pdf", 'rb') as pdf_f:
  8.     files["imageBlock1"] = img_f
  9.     files["fileBlock1"] = pdf_f
  10.     page = client.me.onenote.pages.add(presentation_file=f, attachment_files=files).execute_query()
  11. ```

Working with Microsoft Planner API


The example demonstrates how to create a new planner task which corresponds to Create plannerTask endpoint :

  1. ``` python
  2. from office365.graph_client import GraphClient

  3. client = GraphClient(acquire_token_func)
  4. task = client.planner.tasks.add(title="New task", planId="--plan id goes here--").execute_query()
  5. ```

Third Party Libraries and Dependencies


The following libraries will be installed when you install the client library:

requests
Microsoft Authentication Library (MSAL) for Python
Last Updated: 2023-06-17 09:27:21