Skip to content

Instantly share code, notes, and snippets.

@robes7
Created February 15, 2025 12:24
Show Gist options
  • Select an option

  • Save robes7/5b8e8b63890cbe6d30a890efb59d2059 to your computer and use it in GitHub Desktop.

Select an option

Save robes7/5b8e8b63890cbe6d30a890efb59d2059 to your computer and use it in GitHub Desktop.
Upload file to a Sharepoint
import requests
import json
from requests_ntlm import HttpNtlmAuth
def upload_file_to_sharepoint():
# User-specific configurations (replace with actual values)
site_url = "https://yourcompany.sharepoint.com/sites/your-site"
folder_url = "/sites/your-site/your-folder-path"
file_path = r"C:\path\to\your\file.xlsx" # Replace with actual file path
file_name = file_path.split("\\")[-1]
username = "your-email@yourcompany.com"
password = "your-password" # Replace with actual password (consider using env variables)
# Authentication and headers
auth = HttpNtlmAuth(username, password)
headers = {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
}
try:
# Get the request digest
digest_url = f"{site_url}/_api/contextinfo"
digest_response = requests.post(digest_url, auth=auth, headers=headers)
# Debug: Print the response content
print(f"Digest Response Status Code: {digest_response.status_code}")
print(f"Digest Response Content: {digest_response.text}")
digest_response.raise_for_status() # Raises an error for non-200 status codes
digest_json = digest_response.json()
# Ensure the response contains the expected structure
if 'd' in digest_json and 'GetContextWebInformation' in digest_json['d']:
digest = digest_json['d']['GetContextWebInformation']['FormDigestValue']
else:
raise ValueError("Unexpected response structure for contextinfo.")
# Update headers to include digest
headers.update({
"X-RequestDigest": digest,
"X-HTTP-Method": "POST",
"If-Match": "*",
})
# Prepare upload URL
upload_url = f"{site_url}/_api/web/GetFolderByServerRelativeUrl('{folder_url}')/Files/add(url='{file_name}',overwrite=true)"
# Read the file content
with open(file_path, 'rb') as file_content:
response = requests.post(upload_url, headers=headers, data=file_content, auth=auth)
# Check if the upload was successful
if response.status_code == 200:
print(f"File '{file_name}' uploaded successfully to SharePoint.")
else:
print(f"Failed to upload file. Status code: {response.status_code}")
print(response.json())
except requests.exceptions.RequestException as req_error:
print(f"HTTP Request Error: {req_error}")
except ValueError as val_error:
print(f"Value Error: {val_error}")
except Exception as e:
print(f"An error occurred: {str(e)}")
if __name__ == "__main__":
upload_file_to_sharepoint()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment