function get_root_folders
Retrieves all folders at the root level of a SharePoint drive using Microsoft Graph API, returning their metadata including name, ID, item count, timestamps, and web URL.
/tf/active/vicechatdev/SPFCsync/test_folder_structure.py
83 - 123
moderate
Purpose
This function queries the Microsoft Graph API to fetch all folders located at the root level of a specified SharePoint drive. It filters out files and returns only folder items with comprehensive metadata. The results are sorted alphabetically by folder name for consistent display. This is useful for building SharePoint navigation interfaces, folder browsers, or inventory systems that need to display root-level folder structures.
Source Code
def get_root_folders(client):
"""Get all folders at the root level with their metadata."""
headers = {
'Authorization': f'Bearer {client.access_token}',
'Accept': 'application/json'
}
folders = []
try:
# Get root level items
items_url = f"https://graph.microsoft.com/v1.0/sites/{client.site_id}/drives/{client.drive_id}/root/children"
import requests
response = requests.get(items_url, headers=headers)
if response.status_code == 200:
items_data = response.json()
for item in items_data.get('value', []):
if 'folder' in item: # It's a folder
folder_info = {
'name': item.get('name', ''),
'id': item.get('id', ''),
'item_count': item.get('folder', {}).get('childCount', 0),
'modified': item.get('lastModifiedDateTime', ''),
'created': item.get('createdDateTime', ''),
'web_url': item.get('webUrl', '')
}
folders.append(folder_info)
# Sort folders by name for consistent display
folders.sort(key=lambda x: x['name'])
else:
print(f"Failed to get root items: {response.status_code}")
except Exception as e:
print(f"Error getting root folders: {e}")
return folders
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
client |
- | - | positional_or_keyword |
Parameter Details
client: A SharePointGraphClient object (or similar client) that must have three attributes: 'access_token' (valid OAuth bearer token for Microsoft Graph API authentication), 'site_id' (the SharePoint site identifier), and 'drive_id' (the specific drive identifier within the site). This client object provides the necessary credentials and context for API calls.
Return Value
Returns a list of dictionaries, where each dictionary represents a folder at the root level. Each dictionary contains: 'name' (string: folder name), 'id' (string: unique folder identifier), 'item_count' (integer: number of child items), 'modified' (string: ISO 8601 datetime of last modification), 'created' (string: ISO 8601 datetime of creation), 'web_url' (string: direct web link to the folder). Returns an empty list if no folders exist, if the API call fails, or if an exception occurs. The list is sorted alphabetically by folder name.
Dependencies
requests
Required Imports
import requests
Conditional/Optional Imports
These imports are only needed under specific conditions:
import requests
Condition: imported inside the function body, required for making HTTP requests to Microsoft Graph API
Required (conditional)Usage Example
from sharepoint_graph_client import SharePointGraphClient
from config import Config
# Initialize the SharePoint client
config = Config()
client = SharePointGraphClient(
tenant_id=config.TENANT_ID,
client_id=config.CLIENT_ID,
client_secret=config.CLIENT_SECRET,
site_id=config.SITE_ID,
drive_id=config.DRIVE_ID
)
# Authenticate and get access token
client.authenticate()
# Get all root folders
root_folders = get_root_folders(client)
# Display folder information
for folder in root_folders:
print(f"Folder: {folder['name']}")
print(f" ID: {folder['id']}")
print(f" Items: {folder['item_count']}")
print(f" Modified: {folder['modified']}")
print(f" URL: {folder['web_url']}")
print()
Best Practices
- Ensure the client object has a valid, non-expired access token before calling this function
- Handle the returned empty list appropriately - it could indicate no folders, API failure, or an error condition
- Check console output for error messages as the function prints errors but doesn't raise exceptions
- The function silently catches all exceptions and returns an empty list - consider adding logging or re-raising exceptions for production use
- Be aware that the function only retrieves folders, not files, from the root level
- The childCount in item_count may not reflect deeply nested items, only immediate children
- Consider implementing pagination if dealing with drives that may have more than 200 root folders (Graph API default page size)
- The lazy import of 'requests' inside the function may cause issues in some environments - consider moving it to module level
- Validate that client.site_id and client.drive_id are properly formatted GUIDs before calling
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function explore_drive_root 80.4% similar
-
function explore_all_drives 76.1% similar
-
function test_folder_structure 73.3% similar
-
function search_for_folders 73.1% similar
-
function analyze_structure 69.2% similar