function test_graph_sites_api
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.
/tf/active/vicechatdev/SPFCsync/check_tenant_config.py
69 - 108
moderate
Purpose
This function validates that an application has proper permissions and access to SharePoint sites via Microsoft Graph API. It performs a diagnostic check by listing all accessible sites, searching for a specific target site containing 'vicebio.com', and if found, delegates to another function to test drive access. The function provides detailed console output for troubleshooting authentication and permission issues, particularly identifying missing Sites.Read.All permissions.
Source Code
def test_graph_sites_api(access_token, tenant):
"""Test Graph API to access SharePoint sites."""
headers = {
'Authorization': f'Bearer {access_token}',
'Accept': 'application/json'
}
# Try to list sites via Graph API
try:
sites_url = "https://graph.microsoft.com/v1.0/sites"
response = requests.get(sites_url, headers=headers)
if response.status_code == 200:
print("✅ Microsoft Graph Sites API accessible")
sites_data = response.json()
if 'value' in sites_data and sites_data['value']:
print(f" Found {len(sites_data['value'])} sites")
# Look for our specific site
target_site = f"{tenant}.sharepoint.com,sites,vicebio.com"
for site in sites_data['value']:
if 'vicebio.com' in site.get('name', '').lower():
print(f" ✅ Found target site: {site.get('name')}")
return test_site_drive_access(access_token, site.get('id'))
print(" ⚠️ Target site not found in sites list")
return False
else:
print(" ⚠️ No sites found via Graph API")
return False
else:
print(f"❌ Graph Sites API failed: {response.status_code}")
if response.status_code == 403:
print(" 💡 This suggests the app lacks Sites.Read.All permission")
return False
except Exception as e:
print(f"❌ Exception testing Graph Sites API: {e}")
return False
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
access_token |
- | - | positional_or_keyword |
tenant |
- | - | positional_or_keyword |
Parameter Details
access_token: A valid OAuth 2.0 bearer access token for Microsoft Graph API authentication. This token must have appropriate permissions (Sites.Read.All or similar) to access SharePoint sites. Expected as a string value obtained from Azure AD authentication flow.
tenant: The Microsoft 365 tenant identifier, typically in the format 'tenantname' (without .onmicrosoft.com suffix). Used to construct the expected SharePoint site URL pattern (e.g., 'tenantname.sharepoint.com'). Expected as a string value.
Return Value
Returns a boolean value. Returns True if the target site containing 'vicebio.com' is found and the subsequent drive access test (via test_site_drive_access function) succeeds. Returns False if: the Graph API call fails, no sites are found, the target site is not located, or any exception occurs during execution. The function also prints diagnostic messages to console indicating success/failure states.
Dependencies
requests
Required Imports
import requests
Usage Example
# Assuming you have obtained an access token and know your tenant name
access_token = "eyJ0eXAiOiJKV1QiLCJhbGc..."
tenant = "contoso"
# Define the test_site_drive_access function that this function calls
def test_site_drive_access(token, site_id):
# Implementation for testing drive access
return True
# Call the function to test Graph Sites API access
result = test_graph_sites_api(access_token, tenant)
if result:
print("Successfully accessed target site and drives")
else:
print("Failed to access target site or drives")
Best Practices
- Ensure the access token is fresh and not expired before calling this function
- The access token must have Sites.Read.All or Sites.ReadWrite.All permissions granted in Azure AD
- Handle the boolean return value appropriately in calling code for error handling
- The function depends on test_site_drive_access being defined; ensure this dependency is available
- Consider implementing retry logic for transient network failures
- The function prints directly to console; consider refactoring to use logging for production use
- The hardcoded site name 'vicebio.com' should be parameterized for reusability
- Error responses from the API should be logged with full details for debugging
- Consider adding timeout parameters to the requests.get call to prevent hanging
- The function performs synchronous HTTP requests; consider async alternatives for better performance in concurrent scenarios
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function test_site_drive_access 80.9% similar
-
function test_graph_api_access 79.6% similar
-
function access_main_site_library 77.1% similar
-
function quick_test 76.9% similar
-
function test_graph_client 76.5% similar