Connecting to SharePoint with Python Using Service Principal

waragorn boonpanya
2 min readOct 10, 2023

This guide provides step-by-step instructions on how to connect to SharePoint using Python and a Service Principal. The provided Python code demonstrates how to authenticate, access SharePoint folders, list files, and download files using Azure Active Directory (Azure AD) App Registrations.

Prerequisites

Before you begin, ensure you have the following:

  1. SharePoint Site: Have access to a SharePoint site with the necessary permissions.
  2. Azure AD Application: Register an application in Azure Active Directory (Azure AD) and note down the Application (client) ID, Directory (tenant) ID, and the Secret (client secret) key.
  3. SharePoint API Endpoint: Identify the SharePoint API endpoint URL you want to interact with.

Steps to Connect to SharePoint with Python Using Service Principal

1. Install Required Libraries

Ensure you have the required Python libraries installed. Use pip to install the necessary modules:

pip install Office365-REST-Python-Client

2. Authentication with service principal and connecting to SharePoint with Python

Here’s a Python script that demonstrates how to connect to SharePoint using a Service Principal:

# Import Libraries
from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
import pandas as pd
import io

# Azure AD Application Details
site_url = 'https://sharepoint.sharepoint.com/sites/YOUR_SITE'
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
folder_relative_path = '/sites/YOUR_FOLDER'

# Function to Get SharePoint Context Using App Principal
def get_sharepoint_context_using_app():
client_credentials = ClientCredential(client_id, client_secret)
ctx = ClientContext(site_url).with_credentials(client_credentials)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print('Authenticated into SharePoint as:', web.properties['Title'])
return ctx

# Function to Get Folder Details
def folder_details(ctx, folder_relative_path):
folder = ctx.web.get_folder_by_server_relative_url(folder_relative_path)
fold_names = []
sub_folders = folder.files
ctx.load(sub_folders)
ctx.execute_query()
for s_folder in sub_folders:
fold_names.append(s_folder.properties['Name'])
return fold_names

# Function to Download File from SharePoint
def download_file_from_sharepoint(ctx, file_relative_path):
file_name = file_relative_path.split('/')[-1]
response = File.open_binary(ctx, file_relative_path)
df = pd.read_csv(io.BytesIO(response.content))
download_path = f'/path/to/your/local/folder/{file_name}'
df.to_csv(download_path, index=False)
print(f'File "{file_name}" downloaded to: {download_path}')

# Main Execution
ctx = get_sharepoint_context_using_app()
file_list = folder_details(ctx, folder_relative_path)
if file_list:
file_relative_path = f'{folder_relative_path}/{file_list[0]}' # Choose the first file
download_file_from_sharepoint(ctx, file_relative_path)
else:
print('No files found in the specified folder.')

Make sure to replace 'YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET', 'https://sharepoint.sharepoint.com/sites/YOUR_SITE', and '/sites/YOUR_FOLDER' with your actual Azure AD application credentials, SharePoint site URL, and the specific SharePoint list you want to interact with.

Explanation

  • Establishes the SharePoint context using get_sharepoint_context_using_app().
  • Retrieves the list of files from the specified folder using folder_details(ctx, folder_relative_path).
  • Checks if files are found in the folder.
  • If files are found, chooses the first file from the list and downloads it to the specified local path using download_file_from_sharepoint(ctx, file_relative_path).
  • If no files are found, prints a message indicating that no files were found in the specified folder.

This script provides a structured approach to authenticate, access, and download files from SharePoint using Python and a Service Principal.

--

--

waragorn boonpanya

Hello, everyone! My name is Waragorn. Thanks for following. Let's build a community where knowledge knows no bounds! Enjoy learning and sharing knowledge! 🚀