function check_all_libraries
Discovers and lists all document libraries in a SharePoint site using Microsoft Graph API, displaying their metadata and contents.
/tf/active/vicechatdev/SPFCsync/check_libraries.py
10 - 103
moderate
Purpose
This function connects to a SharePoint site via Microsoft Graph API to enumerate all available document libraries (drives). For each library, it displays metadata including name, ID, type, and URL. It also retrieves and displays the root-level contents (folders and files) of each library, providing a comprehensive overview of the SharePoint site's document structure. This is useful for SharePoint site auditing, discovery, and understanding the organization of document libraries.
Source Code
def check_all_libraries():
"""Check all document libraries in the SharePoint site"""
config = Config()
try:
client = SharePointGraphClient(
site_url=config.SHAREPOINT_SITE_URL,
client_id=config.AZURE_CLIENT_ID,
client_secret=config.AZURE_CLIENT_SECRET
)
print("✅ SharePoint Graph client initialized")
print(f"Site: {config.SHAREPOINT_SITE_URL}")
print()
except Exception as e:
print(f"❌ Failed to initialize client: {e}")
return
print("🔍 CHECKING ALL DOCUMENT LIBRARIES")
print("=" * 50)
# Get all drives/document libraries
headers = {
'Authorization': f'Bearer {client.access_token}',
'Accept': 'application/json'
}
try:
# Get all drives in the site
drives_url = f"https://graph.microsoft.com/v1.0/sites/{client.site_id}/drives"
response = requests.get(drives_url, headers=headers)
if response.status_code == 200:
drives_data = response.json()
if 'value' in drives_data:
print(f"Found {len(drives_data['value'])} document libraries:")
print()
for i, drive in enumerate(drives_data['value'], 1):
drive_name = drive.get('name', 'Unknown')
drive_id = drive.get('id', 'Unknown')
web_url = drive.get('webUrl', 'No URL')
drive_type = drive.get('driveType', 'unknown')
print(f"{i}. Library: {drive_name}")
print(f" ID: {drive_id}")
print(f" Type: {drive_type}")
print(f" URL: {web_url}")
# Get root contents of this library
if drive_id != client.drive_id: # Skip the one we already checked
print(f" 📁 Checking contents...")
root_url = f"https://graph.microsoft.com/v1.0/drives/{drive_id}/root/children"
try:
root_response = requests.get(root_url, headers=headers)
if root_response.status_code == 200:
root_data = root_response.json()
if 'value' in root_data:
folders = [item for item in root_data['value'] if 'folder' in item]
files = [item for item in root_data['value'] if 'file' in item]
print(f" 📁 {len(folders)} folders, 📄 {len(files)} files")
# List folder names
if folders:
print(" Folders:")
for folder in folders[:10]: # Show first 10
folder_name = folder.get('name', 'Unknown')
print(f" 📁 {folder_name}")
if len(folders) > 10:
print(f" ... and {len(folders) - 10} more folders")
else:
print(" 📁 No items found")
else:
print(f" ❌ Failed to access: {root_response.status_code}")
except Exception as e:
print(f" ❌ Error accessing library: {e}")
else:
print(f" 📁 This is our main library (already analyzed)")
print()
else:
print("No document libraries found")
else:
print(f"❌ Failed to get document libraries: {response.status_code}")
print(response.text)
except Exception as e:
print(f"❌ Error checking document libraries: {e}")
import traceback
traceback.print_exc()
Return Value
This function does not return any value (implicitly returns None). It outputs information directly to stdout using print statements, displaying formatted text about document libraries and their contents, or error messages if operations fail.
Dependencies
requestssharepoint_graph_clientconfigtraceback
Required Imports
import requests
from sharepoint_graph_client import SharePointGraphClient
from config import Config
Conditional/Optional Imports
These imports are only needed under specific conditions:
import traceback
Condition: only used when an exception occurs during document library checking to print detailed error information
OptionalUsage Example
# Ensure config.py exists with required settings
# config.py should contain:
# class Config:
# SHAREPOINT_SITE_URL = 'https://yourtenant.sharepoint.com/sites/yoursite'
# AZURE_CLIENT_ID = 'your-client-id'
# AZURE_CLIENT_SECRET = 'your-client-secret'
# Ensure sharepoint_graph_client.py exists with SharePointGraphClient class
# Run the function
check_all_libraries()
# Output will be printed to console showing:
# - Initialization status
# - List of all document libraries
# - For each library: name, ID, type, URL
# - Contents of each library (folders and files)
Best Practices
- Ensure Azure AD application has proper permissions (Sites.Read.All minimum) before running
- The function prints directly to stdout; consider redirecting output or modifying to return data structures for programmatic use
- Error handling is present but basic; consider enhancing for production use
- The function limits folder display to first 10 items per library to avoid overwhelming output
- Access tokens have expiration times; ensure the SharePointGraphClient handles token refresh appropriately
- The function makes multiple API calls; be aware of Microsoft Graph API throttling limits for high-volume scenarios
- Sensitive credentials (client_id, client_secret) should be stored securely, not hardcoded
- The function skips detailed analysis of the 'main library' (client.drive_id) assuming it was already analyzed elsewhere
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function explore_document_libraries 83.3% similar
-
function explore_all_drives 77.9% similar
-
function access_main_site_library 75.6% similar
-
function explore_site_structure 74.0% similar
-
function test_site_drive_access 71.6% similar