Registry /
crm-productivity / office365-rest-python-client
Install & Compatibility
Where this runs
tested against v3.0.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 1.120s · 88.4MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 6.1s · import 1.054s · 89MB
88MB installed
● package 88MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
ClientContext
✓ from office365.sharepoint.client_context import ClientContext
Used for interacting with SharePoint (legacy REST API).
GraphClient
✓ from office365.graph_client import GraphClient
Used for interacting with Microsoft Graph API.
ClientCredential
✓ from office365.runtime.auth.client_credential import ClientCredential
Used for app-only authentication with client ID and client secret.
UserCredential
✓ from office365.runtime.auth.user_credential import UserCredential
Used for username/password authentication (note: less secure and often problematic with MFA).
AzureEnvironment
✓ from office365.azure_env import AzureEnvironment
Used to specify Azure cloud environments (e.g., US Government).
This quickstart demonstrates how to connect to a SharePoint site using application (client ID and secret) authentication via the `ClientContext`. It retrieves and prints the site's URL and title. Ensure your Azure AD application is registered with appropriate permissions (e.g., 'Sites.Read.All' or 'Sites.FullControl.All') and that admin consent is granted in the Azure Portal. It's recommended to use environment variables for sensitive credentials.
import os
from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.client_credential import ClientCredential
# --- Configuration (replace with your actual values or set as environment variables) ---
sharepoint_site_url = os.environ.get('SHAREPOINT_SITE_URL', 'https://yourtenant.sharepoint.com/sites/yoursite')
client_id = os.environ.get('M365_CLIENT_ID', '')
client_secret = os.environ.get('M365_CLIENT_SECRET', '')
if not all([sharepoint_site_url, client_id, client_secret]):
print("Error: Please set SHAREPOINT_SITE_URL, M365_CLIENT_ID, and M365_CLIENT_SECRET environment variables.")
exit(1)
try:
# Initialize ClientContext with app-only credentials
ctx = ClientContext(sharepoint_site_url).with_credentials(ClientCredential(client_id, client_secret))
# Load the web object and execute the query
ctx.load(ctx.web)
ctx.execute_query()
print(f"Successfully connected to SharePoint site: {ctx.web.url}")
print(f"Web title: {ctx.web.title}")
except Exception as e:
print(f"An error occurred: {e}")
print("Ensure your Azure AD application is registered, has the necessary API permissions (e.g., 'Sites.Read.All' or 'Sites.FullControl.All'), and admin consent has been granted.")
Debug
Known issues
breakingUsername and password authentication (with_user_credentials) may fail or require frequent re-authentication in MFA-enabled environments. In version 2.6.0, support for automatically renewing authentication cookies for `with_user_credentials` was added, which mitigates some issues but does not resolve all MFA challenges.fixFor unattended scripts, prefer Azure AD application-only authentication using client secrets or certificates (ClientContext.with_client_credentials or GraphClient.with_client_secret/with_certificate). For interactive scenarios, consider interactive authentication flows if supported by your organization's policies.
affects: All versions, especially with MFA.
gotchaAPI calls are often queued and not executed until `execute_query()` is explicitly called. Forgetting this can lead to unexpected behavior or no data being retrieved.fixAlways call `.execute_query()` after building your API requests (e.g., after loading properties or calling methods that interact with the server).
affects: All versions
gotchaIncorrect or insufficient Azure AD application permissions (e.g., 'Sites.Read.All', 'Mail.Send', 'Files.ReadWrite.All') or missing admin consent will result in 401 Unauthorized or 403 Forbidden errors when accessing resources.fixVerify that your Azure AD app registration has all necessary API permissions for Microsoft Graph or SharePoint, and ensure that 'Grant admin consent for [your tenant]' has been clicked in the Azure Portal for application permissions.
affects: All versions
gotchaWhen working with SharePoint, ensure the `sharepoint_site_url` points to the correct site collection or subsite. Using a generic tenant URL for operations on a specific subsite can lead to 'File Not Found' or permission-related errors.fixProvide the full and exact URL to the SharePoint site or subsite you intend to interact with in the `ClientContext` constructor.
affects: All versions
gotchaRetrieving items from large collections (e.g., lists, document libraries) may require explicit pagination handling. While the library offers `paged()` methods, older approaches or custom queries might miss items if the collection exceeds the default page size.fixFor large collections, use the `.paged()` method available on item collections or ensure your iteration logic correctly handles continuation tokens for full retrieval.
affects: <= 2.5.8 (improved in 2.5.9 for DriveItem.get_files/folders)
gotchaUpdating SharePoint lookup columns requires passing a `FieldLookupValue` object, not just the lookup item's ID directly. Direct assignment of an ID will fail.fixUse `from office365.sharepoint.field_value import FieldLookupValue` and set the property like `item_to_update.set_property('Department', FieldLookupValue(lookup_id=1)).update().execute_query()`. affects: All versions
breakingEssential environment variables (e.g., SHAREPOINT_SITE_URL, M365_CLIENT_ID, M365_CLIENT_SECRET) must be set for the library to initialize and authenticate successfully. Failure to set these will prevent any operations.fixEnsure that all required environment variables, such as SHAREPOINT_SITE_URL, M365_CLIENT_ID, and M365_CLIENT_SECRET, are correctly defined and accessible in the execution environment before running your script.
affects: All versions
breakingThe library requires specific environment variables (e.g., SHAREPOINT_SITE_URL, M365_CLIENT_ID, M365_CLIENT_SECRET) to be set for proper initialization and authentication. Failing to set these will prevent the library from operating.fixEnsure that all required environment variables, such as `SHAREPOINT_SITE_URL`, `M365_CLIENT_ID`, and `M365_CLIENT_SECRET`, are correctly set in your execution environment before running the application.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'office365'
This error often occurs because developers try to import a module named 'office365' directly, but the primary package is named `office365-REST-Python-Client`. While `office365` can be installed as a separate package, the core classes are typically imported from the `office365` namespace provided by `office365-REST-Python-Client` itself, and users may miss installing the correct or all necessary packages.
fixEnsure both `office365-REST-Python-Client` and potentially `office365` are installed, and use correct import statements. For example, `pip install office365-REST-Python-Client office365`. Then, import classes from `office365.sharepoint.client_context` or `office365.graph_client` as needed.
401 Client Error: Unauthorized
This is a common authentication or authorization failure, often stemming from incorrect client ID or client secret, expired credentials, insufficient API permissions for the registered application in Azure AD or SharePoint, or issues with multi-factor authentication (MFA) blocking automated access.
fixVerify that the `client_id` and `client_secret` are correct and unexpired, and that the Azure AD App Registration or SharePoint App-Only principal has the necessary API permissions (e.g., `Sites.FullControl.All`, `Sites.Read.All`). For SharePoint App-Only, ensure permissions are granted via `_layouts/15/appinv.aspx`. Ensure that any tenant-level restrictions or MFA policies are not preventing programmatic access.
AttributeError: 'ClientContext' object has no attribute '_auth_context' (or similar, e.g., 'connect_with_certificate')
This error typically indicates that the code is attempting to access an attribute or method that either does not exist in the current version of the `ClientContext` object or has been renamed due to API changes or refactoring in the library. For example, `connect_with_certificate` was renamed to `with_client_certificate`.
fixUpdate your code to use the current API methods as per the library's documentation or examples for your installed version. For the `_auth_context` issue, it usually points to an internal library bug that has been fixed in newer versions. For `connect_with_certificate`, use `ClientContext.with_client_certificate`. Upgrading the library to the latest version (`pip install --upgrade office365-REST-Python-Client`) often resolves such `AttributeError`s related to internal structure changes.
ModuleNotFoundError: No module named 'office365.runtime.auth.ClientCredential' (or 'AuthenticationContext', 'UserCredential')
This error occurs when the import path for certain authentication classes, like `ClientCredential` or `UserCredential`, has changed in newer versions of the library due to internal restructuring. Older code examples or outdated installations might reference the wrong path.
fixAdjust your import statements to reflect the current module structure. For `ClientCredential`, the correct import is often `from office365.runtime.auth.client_credential import ClientCredential`. Similarly, `UserCredential` is `from office365.runtime.auth.user_credential import UserCredential`. Also, ensure you have the latest version of the library installed.
File Not Found (or similar errors when accessing files/folders)
Even after successful authentication, developers may encounter 'File Not Found' or other access errors when trying to interact with specific files or folders. This can be due to an incorrect file path (relative vs. server-relative URL), a mismatch between the site URL used for `ClientContext` and the actual location of the resource, SharePoint list view threshold issues for large libraries, or insufficient permissions for the *specific* SharePoint site/document library despite having general access.
fixDouble-check the exact server-relative URL or guest URL of the file/folder. Ensure the `ClientContext` is initialized with the correct site URL that hosts the content. For large lists, consider if SharePoint's list view threshold is being hit and if indexing columns could help. Verify that the application's granted permissions extend to the specific document library or folder being accessed, not just the site collection.
Upgrade
Version history
3.0.0latest on PyPI · released Aug 2, 2026
Audit
Dependencies
requestsrequiredUsed for HTTP requests.
msalrequiredDefault library for obtaining tokens for Microsoft Graph API authentication.