🔍 Code Extractor

function test_site_drive_access

Maturity: 49

Tests access to a SharePoint site's document library (drives) via Microsoft Graph API and attempts to access the first drive's root items.

File:
/tf/active/vicechatdev/SPFCsync/check_tenant_config.py
Lines:
110 - 141
Complexity:
moderate

Purpose

This function is designed to validate permissions and connectivity to SharePoint site drives through the Microsoft Graph API. It retrieves all drives associated with a given site, verifies successful API access, and if drives are found, attempts to access the first drive's items by calling test_drive_items(). This is typically used in authentication testing, permission validation, or SharePoint integration diagnostics.

Source Code

def test_site_drive_access(access_token, site_id):
    """Test accessing the site's drive (document library)."""
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Accept': 'application/json'
    }
    
    try:
        # Get drives for the site
        drives_url = f"https://graph.microsoft.com/v1.0/sites/{site_id}/drives"
        response = requests.get(drives_url, headers=headers)
        
        if response.status_code == 200:
            print("✅ Site drives accessible via Graph API")
            drives_data = response.json()
            
            if 'value' in drives_data and drives_data['value']:
                print(f"   Found {len(drives_data['value'])} drives")
                
                # Try to access the first drive's root
                drive_id = drives_data['value'][0]['id']
                return test_drive_items(access_token, site_id, drive_id)
            else:
                print("   ⚠️  No drives found")
                return False
        else:
            print(f"❌ Site drives API failed: {response.status_code}")
            return False
            
    except Exception as e:
        print(f"❌ Exception testing site drives: {e}")
        return False

Parameters

Name Type Default Kind
access_token - - positional_or_keyword
site_id - - positional_or_keyword

Parameter Details

access_token: A valid OAuth 2.0 bearer token with appropriate Microsoft Graph API permissions (e.g., Sites.Read.All, Files.Read.All) to access SharePoint site drives. This token is used in the Authorization header for API requests.

site_id: The unique identifier of the SharePoint site whose drives should be accessed. This can be obtained from Microsoft Graph API site discovery endpoints or SharePoint admin center. Format is typically a GUID or site URL-based identifier.

Return Value

Returns a boolean value. Returns True if drives are successfully accessed and the first drive's items can be accessed (delegated to test_drive_items function). Returns False if the API call fails (non-200 status), no drives are found, or an exception occurs during execution. The function also prints status messages to console indicating success (✅), warnings (⚠️), or errors (❌).

Dependencies

  • requests

Required Imports

import requests

Usage Example

# Assuming you have obtained an access token and site_id
access_token = "eyJ0eXAiOiJKV1QiLCJhbGc..."
site_id = "contoso.sharepoint.com,abc123-def456-ghi789,xyz987-uvw654-rst321"

# Test site drive access
result = test_site_drive_access(access_token, site_id)

if result:
    print("Successfully accessed site drives and drive items")
else:
    print("Failed to access site drives or no drives found")

Best Practices

  • Ensure the access token has not expired before calling this function
  • Handle the boolean return value appropriately in calling code to determine next steps
  • The function depends on test_drive_items() which must be defined elsewhere in the codebase
  • Consider implementing retry logic for transient network failures
  • Monitor console output for diagnostic information about API responses
  • Validate that the site_id format matches Microsoft Graph API requirements
  • Be aware that this function only tests the first drive if multiple drives exist
  • Implement proper token refresh mechanisms in production environments
  • Consider adding logging instead of print statements for production use

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_drive_items 89.1% similar

    Tests access to items in a Microsoft SharePoint drive by querying the Microsoft Graph API and verifying the response.

    From: /tf/active/vicechatdev/SPFCsync/check_tenant_config.py
  • function test_graph_sites_api 80.9% similar

    Tests Microsoft Graph API access to SharePoint sites by attempting to list available sites and locate a specific target site (vicebio.com), then tests drive access if found.

    From: /tf/active/vicechatdev/SPFCsync/check_tenant_config.py
  • function explore_all_drives 79.2% similar

    Retrieves and displays all document drives from a SharePoint site using Microsoft Graph API, then explores the root folder of each drive.

    From: /tf/active/vicechatdev/SPFCsync/diagnostic_comprehensive.py
  • function access_main_site_library 75.4% similar

    Authenticates with Microsoft Graph API and attempts to locate and access the main SharePoint site library using multiple discovery approaches, displaying detailed information about sites, drives, and folder structures.

    From: /tf/active/vicechatdev/SPFCsync/find_main_library.py
  • function explore_drive_root 74.0% similar

    Retrieves and displays the contents of a SharePoint drive's root directory, showing folders and files with their counts and names.

    From: /tf/active/vicechatdev/SPFCsync/diagnostic_comprehensive.py
← Back to Browse