class Sharepoint_API
A SharePoint API client class that provides methods for interacting with SharePoint sites, including folder navigation, file operations, and content management using Office365 REST API.
/tf/active/vicechatdev/resources/cpathapi.py
7 - 175
moderate
Purpose
This class serves as a wrapper around the Office365 SharePoint client library to simplify common SharePoint operations. It handles authentication, folder traversal, file listing, downloading files to memory, uploading files, and folder creation. The class is designed for programmatic access to SharePoint document libraries and is particularly useful for automation tasks involving SharePoint content management. Currently uses username/password authentication but is noted to transition to token-based authentication in the future.
Source Code
class Sharepoint_API():
"""
Set up a sharepoint API to a specific site.
Currently works with login info, but should move to token-based access once approved
Parameters
----------
client : str
The base web url for the specific sharepoint site
site : str
The specific site to connect to
usr : str
Username to connect with
pw : str
The password of the user
Attributes
----------
ctx : Client Context
The sharepoint client context
"""
def __init__(self, client, site, usr, pw):
self.ctx = ClientContext(client + '/sites/' + site)
self.ctx.with_user_credentials(usr, pw)
def set_root(self, path):
"""
Sets given directory as the root property
Paramaters
----------
path : str
A valid folder path for the current sharepoint site
"""
self.root = self.ctx.web.get_folder_by_server_relative_path(path)
self.load_and_execute_query(self.root)
def get_root(self, path):
"""
Returns the given directory
Parameters
----------
path : str
A valid folder path for the current sharepoint site
"""
root = self.ctx.web.get_folder_by_server_relative_path(path)
self.load_and_execute_query(root)
return root
def load_and_execute_query(self, obj):
"""
Loads and executes a query
Parameters
----------
obj : office365.sharepoint obj (i.e. folder or file list)
"""
self.ctx.load(obj)
self.ctx.execute_query()
def enum_folder(self, parent_folder):
"""
Enumerates the given folder in full depth, returns a json-like dictionary of the folder tree
Parameters
----------
parent_folder : office365.sharepoint.folders.folder.Folder
The root folder to look down from
returns
-------
dict
Nested dictionary of folder tree, returning files at the lowest level only.
"""
parent_folder.expand(["Folders"]).get().execute_query()
d={}
if parent_folder.folders:
for folder in parent_folder.folders:
d[folder.name] = self.enum_folder(folder)
# return d
# else:
# return self.list_files(parent_folder)
files = self.list_files(parent_folder)
if files:
d[parent_folder.name+'_files'] = files
return d
def list_files(self, folder):
"""
Lists all files present in the given folder
Parameters
----------
parent_folder : office365.sharepoint.folders.folder.Folder
The root folder to look in
returns
-------
list
list of all files
"""
libraryRoot = self.get_root(folder.serverRelativeUrl)
files = libraryRoot.files
self.load_and_execute_query(files)
files = [file.name for file in files]
return files
def download_file_to_memory(self, filepath):
"""
Download the given file to memory
Parameters
----------
folder : str
The relative filepath to a downloadable file
"""
file = io.BytesIO()
self.ctx.web.get_file_by_server_relative_path(filepath).download(file).execute_query()
file.seek(0)
return file
def try_get_folder(self, url):
"""
Check if folder exists, returns False of not
Parameters
----------
url : str
A complete folder url
"""
try:
return self.get_root(url)
except ClientRequestException as e:
if e.response.status_code == 404:
return False
else:
raise ValueError(e.response.text)
def create_folder(self, url, folder):
"""
Create a new folder at given url path
Parameters
----------
url : str
Destination folder of the new folder
folder : str
The name of the new folder
"""
parent_folder = self.get_root(url)
target_folder = parent_folder.folders.add(folder)
self.ctx.execute_query()
def upload_file(self, url, filename, file):
"""
Upload a file to the given destination
Parameters
----------
url : str
Destination folder of the new file
filename : str
The name of the new file including file extension
file : io.BytesIO
Virtual file to upload to sharepoint
"""
target_folder = self.get_root(url)
target_folder.upload_file(filename, file).execute_query()
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
- | - |
Parameter Details
client: The base web URL for the SharePoint site (e.g., 'https://company.sharepoint.com'). This is the root domain without the '/sites/' path.
site: The specific site name within the SharePoint tenant to connect to (e.g., 'TeamSite' or 'ProjectDocs'). This will be appended to the client URL as '/sites/{site}'.
usr: The username credential for SharePoint authentication. Should be a valid SharePoint user account with appropriate permissions to access the target site.
pw: The password for the specified username. Used for authentication with the SharePoint site.
Return Value
Instantiation returns a Sharepoint_API object with an authenticated client context. Methods return various types: set_root() returns None, get_root() returns a Folder object, enum_folder() returns a nested dictionary representing the folder structure, list_files() returns a list of file names, download_file_to_memory() returns a BytesIO object, try_get_folder() returns a Folder object or False, create_folder() returns None, and upload_file() returns None.
Class Interface
Methods
__init__(self, client: str, site: str, usr: str, pw: str)
Purpose: Initializes the SharePoint API client with authentication credentials and establishes a connection to the specified site
Parameters:
client: Base web URL for the SharePoint sitesite: Specific site name to connect tousr: Username for authenticationpw: Password for authentication
Returns: None (constructor)
set_root(self, path: str) -> None
Purpose: Sets a given directory as the root property for subsequent operations
Parameters:
path: A valid folder path for the current SharePoint site (server-relative URL)
Returns: None; sets self.root attribute as a side effect
get_root(self, path: str) -> Folder
Purpose: Retrieves and returns a folder object for the given directory path
Parameters:
path: A valid folder path for the current SharePoint site (server-relative URL)
Returns: office365.sharepoint.folders.folder.Folder object representing the requested folder
load_and_execute_query(self, obj) -> None
Purpose: Loads and executes a SharePoint query for the given object, fetching its data from the server
Parameters:
obj: An Office365 SharePoint object (e.g., folder or file list) to load and query
Returns: None; modifies the obj parameter in-place with loaded data
enum_folder(self, parent_folder: Folder) -> dict
Purpose: Recursively enumerates the entire folder structure starting from the given folder, returning a nested dictionary representation
Parameters:
parent_folder: office365.sharepoint.folders.folder.Folder object to enumerate from
Returns: Nested dictionary representing the folder tree structure, with files listed at each level under '{folder_name}_files' keys
list_files(self, folder: Folder) -> list
Purpose: Lists all files present in the specified folder (non-recursive)
Parameters:
folder: office365.sharepoint.folders.folder.Folder object to list files from
Returns: List of strings containing file names in the folder
download_file_to_memory(self, filepath: str) -> io.BytesIO
Purpose: Downloads a file from SharePoint directly into memory without saving to disk
Parameters:
filepath: The server-relative file path to the downloadable file
Returns: io.BytesIO object containing the file contents, with file pointer at position 0
try_get_folder(self, url: str) -> Folder | bool
Purpose: Attempts to retrieve a folder, returning False if it doesn't exist instead of raising an exception
Parameters:
url: Complete server-relative folder URL to check
Returns: Folder object if exists, False if not found (404), raises ValueError for other errors
create_folder(self, url: str, folder: str) -> None
Purpose: Creates a new folder at the specified location
Parameters:
url: Server-relative URL of the parent folder where the new folder will be createdfolder: Name of the new folder to create
Returns: None; creates the folder as a side effect
upload_file(self, url: str, filename: str, file: io.BytesIO) -> None
Purpose: Uploads a file from memory to the specified SharePoint location
Parameters:
url: Server-relative URL of the destination folderfilename: Name for the uploaded file including file extensionfile: io.BytesIO object containing the file content to upload
Returns: None; uploads the file as a side effect
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
ctx |
ClientContext | The authenticated SharePoint client context used for all API operations. Maintains the connection and authentication state. | instance |
root |
Folder | Optional attribute set by set_root() method. Stores a reference to a designated root folder for operations. Only exists after set_root() is called. | instance |
Dependencies
office365-rest-python-clientio
Required Imports
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
from office365.runtime.client_request_exception import ClientRequestException
import io
Usage Example
# Initialize the SharePoint API client
sp = Sharepoint_API(
client='https://company.sharepoint.com',
site='TeamSite',
usr='user@company.com',
pw='password123'
)
# Set a root folder for operations
sp.set_root('/sites/TeamSite/Shared Documents')
# List files in a folder
folder = sp.get_root('/sites/TeamSite/Shared Documents/Reports')
files = sp.list_files(folder)
print(files)
# Enumerate entire folder structure
folder_tree = sp.enum_folder(folder)
print(folder_tree)
# Download a file to memory
file_content = sp.download_file_to_memory('/sites/TeamSite/Shared Documents/report.pdf')
# Create a new folder
sp.create_folder('/sites/TeamSite/Shared Documents', 'NewFolder')
# Upload a file
with open('local_file.txt', 'rb') as f:
file_bytes = io.BytesIO(f.read())
sp.upload_file('/sites/TeamSite/Shared Documents/NewFolder', 'uploaded_file.txt', file_bytes)
Best Practices
- Always call set_root() or get_root() before performing folder operations to ensure you're working with the correct directory context
- Use try_get_folder() to check folder existence before attempting operations to avoid exceptions
- When downloading files, remember that download_file_to_memory() returns a BytesIO object with the file pointer at position 0 (already seeked)
- For file uploads, ensure the file parameter is a BytesIO object, not a file path string
- The ctx (ClientContext) attribute maintains the authenticated session; avoid modifying it directly
- Folder paths should use server-relative URLs (e.g., '/sites/SiteName/LibraryName/FolderName')
- The enum_folder() method recursively traverses all subfolders, which can be slow for large directory structures
- Handle ClientRequestException for robust error handling, especially for 404 errors when folders don't exist
- Consider implementing token-based authentication instead of username/password for production use
- The load_and_execute_query() method must be called after most operations to actually execute the SharePoint query
- File and folder names returned are just names, not full paths; use serverRelativeUrl for full paths
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class SharePointRestClient 62.7% similar
-
class SharePointClient 60.6% similar
-
class SharePointClient_v1 54.0% similar
-
class SharePointGraphClient 52.6% similar
-
function test_sharepoint_with_token 52.2% similar