šŸ” Code Extractor

function test_sharepoint_api_call

Maturity: 46

Tests SharePoint REST API connectivity by making an authenticated GET request to retrieve basic site information and validates the access token and permissions.

File:
/tf/active/vicechatdev/SPFCsync/diagnose_sharepoint.py
Lines:
145 - 187
Complexity:
simple

Purpose

This function serves as a diagnostic tool to verify that an OAuth access token is valid and has the necessary permissions to access a SharePoint site. It attempts to retrieve basic site metadata (title and URL) and provides detailed error messages with troubleshooting guidance for common authentication and authorization issues (401, 403 errors). This is typically used during setup, debugging, or validation of SharePoint API integrations.

Source Code

def test_sharepoint_api_call(access_token, site_url):
    """Test a simple SharePoint API call."""
    print("\nTesting SharePoint API call...")
    
    api_url = f"{site_url}/_api/web"
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
    
    try:
        response = requests.get(api_url, headers=headers)
        
        if response.status_code == 200:
            print("āœ… SharePoint API call successful!")
            try:
                data = response.json()
                print(f"   Site title: {data.get('Title', 'Unknown')}")
                print(f"   Site URL: {data.get('Url', 'Unknown')}")
                return True
            except:
                print("   (Could not parse response JSON)")
                return True
        else:
            print(f"āŒ SharePoint API call failed. Status: {response.status_code}")
            print(f"   Response: {response.text[:200]}...")
            
            if response.status_code == 401:
                print("\nšŸ’” 401 Unauthorized usually means:")
                print("   - Token is valid but app lacks permissions to this site")
                print("   - Site URL might be incorrect")
                print("   - App needs Sites.Read.All permission with admin consent")
            elif response.status_code == 403:
                print("\nšŸ’” 403 Forbidden usually means:")
                print("   - App has token but no permission to access this resource")
                print("   - Need to grant app access to the SharePoint site")
            
            return False
            
    except Exception as e:
        print(f"āŒ Exception during API call: {e}")
        return False

Parameters

Name Type Default Kind
access_token - - positional_or_keyword
site_url - - positional_or_keyword

Parameter Details

access_token: A valid OAuth 2.0 bearer token string obtained from Microsoft Identity Platform (Azure AD) with appropriate SharePoint permissions (e.g., Sites.Read.All). This token is used to authenticate the API request.

site_url: The full URL of the SharePoint site to test against (e.g., 'https://contoso.sharepoint.com/sites/mysite'). This should be the base URL without any API path segments.

Return Value

Returns a boolean value: True if the API call succeeds (status code 200) regardless of whether the JSON response can be parsed, False if the API call fails (non-200 status code) or if an exception occurs during the request. The function also prints detailed status messages and diagnostic information to stdout.

Dependencies

  • requests

Required Imports

import requests

Usage Example

import requests

# Obtain access token (example using client credentials flow)
access_token = "eyJ0eXAiOiJKV1QiLCJhbGc..."
site_url = "https://contoso.sharepoint.com/sites/mysite"

# Test the SharePoint API connection
success = test_sharepoint_api_call(access_token, site_url)

if success:
    print("SharePoint connection verified")
else:
    print("SharePoint connection failed - check permissions and site URL")

Best Practices

  • Ensure the access token is fresh and not expired before calling this function
  • Verify that the Azure AD app has Sites.Read.All or Sites.FullControl.All permissions with admin consent granted
  • Use the exact base URL of the SharePoint site without trailing slashes or API paths
  • Handle the boolean return value to implement appropriate error handling in production code
  • Consider implementing token refresh logic if the function returns False with a 401 error
  • The function prints diagnostic information to stdout, so redirect or capture output if needed in production environments
  • For security, avoid logging the full access token in production environments
  • The function catches all exceptions broadly - consider more specific exception handling for production use

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_sharepoint_with_token 92.0% similar

    Tests SharePoint REST API connectivity and authentication by making a GET request to retrieve site information using a provided access token.

    From: /tf/active/vicechatdev/SPFCsync/diagnose_permissions.py
  • function test_sharepoint_token 83.9% similar

    Tests SharePoint OAuth2 authentication by acquiring an access token using client credentials flow and validates it with a SharePoint API call.

    From: /tf/active/vicechatdev/SPFCsync/diagnose_sharepoint.py
  • function test_rest_client 78.1% similar

    A test function that validates the SharePoint REST API client by testing authentication, document listing, and file download capabilities.

    From: /tf/active/vicechatdev/SPFCsync/test_rest_client.py
  • function test_graph_api_access 77.6% similar

    Tests Microsoft Graph API access by obtaining an OAuth2 token and verifying connectivity to check tenant settings for SharePoint integration.

    From: /tf/active/vicechatdev/SPFCsync/check_tenant_config.py
  • function test_azure_token 76.5% similar

    Tests Azure AD authentication by attempting to acquire an OAuth2 access token using client credentials flow for Microsoft Graph API access.

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