Upload Files to SharePoint with Python: Step-by-Step Guide (2026)
Learn how to authenticate and upload files to SharePoint Online using Python. This step-by-step guide covers MSAL authentication for seamless integration.
Upload Files to SharePoint with Python: Step-by-Step Guide (2026)
In today's digital age, integrating different platforms and automating workflows is crucial for efficiency. One common task is uploading files from a local or network drive to SharePoint Online (SPO). With recent changes in Microsoft's authentication methods, understanding the correct approach is essential for seamless integration.
Key Takeaways
- Learn how to authenticate with SharePoint Online using Python.
- Understand the role of the Microsoft Authentication Library (MSAL).
- Implement a script to upload files to SharePoint Online.
- Troubleshoot common authentication errors.
This tutorial will guide you through setting up a Python script that uploads files to SharePoint Online. We will leverage the Microsoft Authentication Library (MSAL) for authentication, which is now the preferred method due to recent changes in Microsoft's security protocols. You'll also learn how to navigate SharePoint's API to upload files efficiently.
Prerequisites
- Basic knowledge of Python programming.
- Python 3.x installed on your machine.
- Access to a SharePoint Online account with permissions to upload files.
- Azure app registration completed with the necessary permissions.
- MSAL Python library installed.
Step 1: Install Dependencies
First, ensure you have the necessary Python packages installed. We'll primarily use the MSAL library for authentication and the 'requests' library for HTTP requests.
pip install msal requestsThis installs MSAL for handling authentication and the requests library for making HTTP requests to SharePoint.
Step 2: Set Up Azure App Registration
Before interacting with SharePoint, you need to register an application in Azure AD and configure it to authenticate against SharePoint. This involves setting up client credentials and assigning the app the necessary permissions.
- Login to the Azure Portal.
- Navigate to Azure Active Directory > App registrations > New registration.
- Enter a name for your app (e.g., 'SharePointUploader').
- Set the Redirect URI to
http://localhost(for testing purposes). - Once registered, note down the Client ID and Tenant ID.
- Under 'Certificates & Secrets', create a new client secret and note it down.
- Assign the application permissions for 'Microsoft Graph' > 'Files.ReadWrite.All'.
These credentials will be used by your script to authenticate requests to SharePoint.
Step 3: Authenticate with SharePoint Online
Using the credentials from your Azure app registration, authenticate and obtain an access token to interact with SharePoint Online.
import msal
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
tenant_id = 'YOUR_TENANT_ID'
authority_url = f'https://login.microsoftonline.com/{tenant_id}'
app = msal.ConfidentialClientApplication(
client_id,
authority=authority_url,
client_credential=client_secret
)
scope = ['https://graph.microsoft.com/.default']
result = app.acquire_token_for_client(scopes=scope)
if 'access_token' in result:
print('Authentication successful!')
else:
print('Error obtaining token:', result.get('error_description'))This script authenticates your app and retrieves an access token. If successful, you'll see a confirmation message.
Step 4: Upload File to SharePoint
With an access token, you can now upload files to your desired SharePoint path. Replace the target URL with your SharePoint path.
import requests
access_token = result['access_token']
file_path = 'path/to/your/file.txt'
sharepoint_site = 'https://cbxmx.sharepoint.com'
sharepoint_folder = '/sites/MySite/Shared Documents/Reports'
headers = {
'Authorization': f'Bearer {access_token}',
'Accept': 'application/json;odata=verbose'
}
with open(file_path, 'rb') as file_data:
response = requests.post(
f'{sharepoint_site}/_api/web/GetFolderByServerRelativeUrl({sharepoint_folder})/Files/add(url={file_path},overwrite=true)',
headers=headers,
data=file_data
)
if response.status_code == 200:
print('File uploaded successfully!')
else:
print('Failed to upload file:', response.content)This code uploads a file to the specified SharePoint folder. Adjust the path and folder names as needed.
Common Errors/Troubleshooting
- Authentication Errors: Ensure your Azure app has the correct permissions and that your client credentials are accurate.
- File Path Issues: Verify that the file path and SharePoint folder path are correct and accessible.
- API Errors: Review the response content for specific SharePoint API error messages.
Conclusion
Uploading files to SharePoint Online using Python can significantly streamline your workflows, especially with the right authentication setup. By leveraging MSAL and REST API calls, you can automate this process efficiently. Understanding the authentication flow and API interaction is key to integrating Python with SharePoint effectively.
Frequently Asked Questions
What is MSAL and why is it used?
MSAL (Microsoft Authentication Library) is used to handle authentication with Microsoft services, providing a seamless way to manage access tokens.
Can I use this script for other SharePoint sites?
Yes, you can adapt the script for different SharePoint sites by adjusting the site URLs and folder paths accordingly.
What permissions are needed for the Azure app?
The Azure app requires 'Files.ReadWrite.All' permission on Microsoft Graph to upload files to SharePoint.