Office365-REST-Python-Client

2.6.2 · active · verified Mon Apr 06

The Office365-REST-Python-Client is a comprehensive Python library for interacting with Microsoft 365 and Microsoft Graph APIs. It provides a unified interface for both legacy SharePoint REST APIs and modern Microsoft Graph endpoints, supporting services like SharePoint, Outlook, OneDrive, Teams, OneNote, and Planner. The library is actively maintained, with frequent releases, and is currently at version 2.6.2.

Warnings

Install

Imports

Quickstart

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.")

view raw JSON →