I try to upload a csv file to a Sharepoint.
I came so far with my script:
from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext
import msal
import os
import requests
sharepoint_site_url = "https://companyname.sharepoint.com/sites/PowerBILookUp"
document_library_url = "Shared Documents" # Adjust as necessary
# Azure AD App Registration details
client_id = "client_id"
client_secret = "client_secret"
tenant_id = "tenant_id"
# Path to the CSV file you want to upload
local_csv_path = "C:\Users\Administrator\Downloads\orders.csv"
# Destination file name on SharePoint (including any folders within the document library)
destination_file_name = "SubFolder/orders2.csv" # Adjust the path as necessary
# Authentication authority URL
authority_url = f"https://login.microsoftonline.com/{tenant_id}"
# Initialize MSAL confidential client application
app = msal.ConfidentialClientApplication(
client_id,
authority=authority_url,
client_credential=client_secret,
)
# Acquire a token for SharePoint
token_response = app.acquire_token_for_client(scopes=["https://companyname.sharepoint.com/.default"])
# Check if the token was acquired successfully
if "access_token" in token_response:
access_token = token_response["access_token"]
print(f"Access token acquired: {access_token[:30]}...")
try:
# Create the SharePoint client context with the acquired token
ctx = ClientContext(sharepoint_site_url).with_access_token(access_token)
# Ensure the folder can be accessed
target_folder = ctx.web.get_folder_by_server_relative_url(document_library_url)
ctx.execute_query()
print(f"Folder accessed successfully: {document_library_url}")
# Prepare the file upload URL
upload_url = f"{sharepoint_site_url}/_api/web/GetFolderByServerRelativeUrl('{document_library_url}')/Files/add(url='{destination_file_name}', overwrite=true)"
print(f"Upload URL: {upload_url}")
# Read the CSV file content
with open(local_csv_path, 'rb') as file_content:
file_data = file_content.read()
# Perform the upload using REST API
headers = {
"Authorization": f"Bearer {access_token}",
"Accept": "application/json;odata=verbose",
"Content-Type": "application/octet-stream"
}
print(f"Headers: {headers}")
print(f"Uploading file {local_csv_path} to {upload_url}...")
response = requests.post(upload_url, headers=headers, data=file_data)
if response.status_code == 200:
print(f"File '{destination_file_name}' uploaded to SharePoint successfully.")
else:
print(f"File upload failed: {response.status_code} - {response.text}")
except Exception as e:
print(f"An error occurred during the SharePoint operation: {e}")
else:
print(f"Error acquiring token: {token_response.get('error_description')}")
but I get this error:
Access token acquired: xxxx… Folder accessed successfully: Shared
Documents Upload URL:
https://companyname.sharepoint.com/sites/PowerBILookUp/_api/web/GetFolderByServerRelativeUrl(‘Shared
Documents’)/Files/add(url=’SubFolder/orders2.csv’, overwrite=true)
Headers: {‘Authorization’: ‘Bearer
eyJ0eXAiOiJKV1VcFphP_tgxJA-BwQ-qXCX7z_FC7jfJLNr4j03GEDw’,
‘Accept’: ‘application/json;odata=verbose’, ‘Content-Type’:
‘application/octet-stream’} Uploading file
C:UsersAdministratorDownloadsorders.csv to
https://companyname.sharepoint.com/sites/PowerBILookUp/_api/web/GetFolderByServerRelativeUrl(‘Shared
Documents’)/Files/add(url=’SubFolder/orders2.csv’, overwrite=true)…
File upload failed: 401 – {“error_description”:”ID3035: The request
was not valid or is malformed.”}
any body any idea? I try to upload to https://companyname.sharepoint.com/sites/PowerBILookUp/subFolder/
thanks