SharePy - Simple SharePoint Online authentication for Python

2.0.0 · maintenance · verified Mon Apr 13

SharePy is a Python library designed for simple authentication with SharePoint Online (Office 365) sites, enabling straightforward HTTP requests. It extends the popular Requests library, providing a familiar interface for interacting with SharePoint APIs. The current stable version is 2.0.0, released on February 4, 2022. The library has a slow release cadence, with major updates being infrequent, and there are growing concerns about its compatibility with modern Microsoft 365 authentication flows.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to SharePoint Online using `sharepy.connect()` and make a simple API call to retrieve the site's lists. It's crucial to provide the SharePoint site URL, username, and password, preferably via environment variables for security. The library handles token management and digest token refreshing automatically.

import os
import sharepy

SHAREPOINT_SITE = os.environ.get('SHAREPOINT_SITE', 'example.sharepoint.com')
SHAREPOINT_USERNAME = os.environ.get('SHAREPOINT_USERNAME', 'user@example.com')
SHAREPOINT_PASSWORD = os.environ.get('SHAREPOINT_PASSWORD', 'your_password')

if not all([SHAREPOINT_SITE, SHAREPOINT_USERNAME, SHAREPOINT_PASSWORD]):
    print("Please set SHAREPOINT_SITE, SHAREPOINT_USERNAME, and SHAREPOINT_PASSWORD environment variables.")
    exit(1)

try:
    # Establish a connection to SharePoint Online
    # Note: For MFA-enabled accounts, username/password might not work reliably.
    # See warnings for more details.
    s = sharepy.connect(SHAREPOINT_SITE, username=SHAREPOINT_USERNAME, password=SHAREPOINT_PASSWORD)
    print(f"Successfully connected to {SHAREPOINT_SITE}")

    # Example: Make an API call to get lists from the site
    response = s.get(f'https://{SHAREPOINT_SITE}/_api/web/lists')
    response.raise_for_status() # Raise an exception for bad status codes

    print("SharePoint Lists:")
    for item in response.json()['d']['results']:
        print(f"- {item['Title']}")

    # Example: Download a file (replace with a real URL)
    # file_url = f'https://{SHAREPOINT_SITE}/Shared Documents/MyDocument.pdf'
    # s.getfile(file_url, 'downloaded_file.pdf')
    # print(f"Downloaded {file_url} to downloaded_file.pdf")

except sharepy.errors.AuthError as e:
    print(f"Authentication failed: {e}")
except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →