Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To transfer files to SharePoint using Python, you can use the SharePoint REST API. Follow the steps below:

  1. Authenticate with SharePoint: To authenticate with SharePoint, you can use the requests library in Python. The SharePoint REST API requires a token to authenticate the API request. The token can be obtained by using the client ID, client secret, and tenant ID values.

  2. Create a SharePoint folder: To upload a file to SharePoint, you first need to create a folder in SharePoint. You can use the SharePoint REST API to create a folder in SharePoint. Specify the folder name in the URL and set the folder metadata in the request body.

  3. Upload the file: After creating the folder, you can use the requests library to upload the file to SharePoint. Use the "PUT" method to upload the file and set the file content in the request body.

  4. Set file permissions: To set file permissions, you can use the SharePoint REST API. You can set the file permissions using the unique ID of the file.

Here is an example code snippet:

import requests
import json

# Authenticate with SharePoint
url = "https://your-tenant.sharepoint.com/sites/<site>/_api/token"
data = { 'grant_type': 'client_credentials', 'client_id': '<client-id>', 'client_secret': '<client-secret>', 'resource': 'https://your-tenant.sharepoint.com/' }
response = requests.post(url, data=data)
token = json.loads(response.content)['access_token']

# Create a SharePoint folder
url = "https://your-tenant.sharepoint.com/sites/<site>/_api/web/folders"
data = {
    '__metadata': { 'type': 'SP.Folder' },
    'ServerRelativeUrl': '/sites/<site>/Shared Documents/test_folder'
}
headers = { 'Authorization': 'Bearer ' + token }
response = requests.post(url, headers=headers, data=json.dumps(data))

# Upload the file
url = "https://your-tenant.sharepoint.com/sites/<site>/_api/web/GetFolderByServerRelativeUrl('/sites/<site>/Shared Documents/test_folder')/Files/add(url='test.txt', overwrite=true)"
data = open('test.txt', 'rb')
headers = { 'Authorization': 'Bearer ' + token }
response = requests.put(url, headers=headers, data=data)

# Set file permissions
url = "https://your-tenant.sharepoint.com/sites/<site>/_api/web/GetFolderByServerRelativeUrl('/sites/<site>/Shared Documents/test_folder')/Files/getbyurl('test.txt')/ListItemAllFields/roleassignments/addroleassignment(principalid=<principalid>, roledefid=<roledefid>)"
headers = { 'Authorization': 'Bearer ' + token }
response = requests.post(url, headers=headers)

print("File uploaded successfully")

Note: Replace the placeholders <site>, <client-id>, <client-secret>, <principalid>, and <roledefid> with the actual values.