🔍 Code Extractor

function search_for_folders

Maturity: 46

Searches for specific predefined folders in a SharePoint site using Microsoft Graph API and prints the search results with their locations.

File:
/tf/active/vicechatdev/SPFCsync/diagnostic_comprehensive.py
Lines:
224 - 246
Complexity:
moderate

Purpose

This function is designed to verify the existence of specific regulatory document folders (UCJ Research, Toxicology, CMC, Quality) in a SharePoint drive. It uses the Microsoft Graph API search endpoint to locate folders by name and displays detailed information about each match, including the folder's parent path. This is useful for validating SharePoint site structure or discovering folder locations in document management systems.

Source Code

def search_for_folders(client, headers):
    """Search for specific folders that should exist."""
    expected_folders = ["01 UCJ Research", "02 Toxicology", "03 CMC", "04 Quality"]
    
    try:
        for folder_name in expected_folders:
            # Try search API
            search_url = f"https://graph.microsoft.com/v1.0/sites/{client.site_id}/drives/{client.drive_id}/root/search(q='{folder_name}')"
            response = requests.get(search_url, headers=headers)
            
            if response.status_code == 200:
                search_data = response.json()
                results = search_data.get('value', [])
                print(f"📁 '{folder_name}': {len(results)} search results")
                
                for result in results:
                    if 'folder' in result:
                        print(f"   ✅ Found folder: {result.get('name')} at {result.get('parentReference', {}).get('path', 'Unknown')}")
            else:
                print(f"📁 '{folder_name}': Search failed ({response.status_code})")
                
    except Exception as e:
        print(f"Error searching for folders: {e}")

Parameters

Name Type Default Kind
client - - positional_or_keyword
headers - - positional_or_keyword

Parameter Details

client: An instance of SharePointGraphClient that contains site_id and drive_id properties. These properties are used to construct the Microsoft Graph API URL for searching within a specific SharePoint site and drive.

headers: A dictionary containing HTTP headers required for Microsoft Graph API authentication, typically including an 'Authorization' header with a Bearer token. Example: {'Authorization': 'Bearer <access_token>', 'Content-Type': 'application/json'}

Return Value

This function does not return any value (implicitly returns None). It performs side effects by printing search results to stdout. For each folder searched, it prints the number of results found and details about matching folders including their names and parent paths.

Dependencies

  • requests

Required Imports

import requests

Usage Example

from sharepoint_graph_client import SharePointGraphClient
import requests

# Initialize client with site and drive IDs
client = SharePointGraphClient()
client.site_id = 'your-site-id'
client.drive_id = 'your-drive-id'

# Prepare headers with authentication token
headers = {
    'Authorization': 'Bearer your-access-token',
    'Content-Type': 'application/json'
}

# Search for folders
search_for_folders(client, headers)

# Output example:
# 📁 '01 UCJ Research': 2 search results
#    ✅ Found folder: 01 UCJ Research at /sites/MySite/Shared Documents
# 📁 '02 Toxicology': 1 search results
#    ✅ Found folder: 02 Toxicology at /sites/MySite/Shared Documents

Best Practices

  • Ensure the access token in headers is valid and not expired before calling this function
  • The client object must have both site_id and drive_id attributes properly set
  • Consider adding rate limiting if calling this function repeatedly to avoid Microsoft Graph API throttling
  • The function prints to stdout; consider modifying to return results if you need programmatic access to search data
  • Handle authentication errors by checking response status codes before calling this function
  • The expected_folders list is hardcoded; consider making it a parameter for reusability
  • Error handling catches all exceptions broadly; consider more specific exception handling for production use
  • The search query uses simple string matching; folder names with special characters may need URL encoding

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function search_and_locate 80.4% similar

    Searches for specific numbered folders (01-08) in a SharePoint site and traces their locations, contents, and file distributions by type.

    From: /tf/active/vicechatdev/SPFCsync/search_detailed.py
  • function analyze_structure 74.8% similar

    Analyzes and reports on the folder structure of a SharePoint site, displaying folder paths, file counts, and searching for expected folder patterns.

    From: /tf/active/vicechatdev/SPFCsync/analyze_structure.py
  • function compare_with_expected_folders 73.5% similar

    Compares SharePoint folders found via Microsoft Graph API against a predefined list of expected folder names from a reference screenshot, reporting matches, missing folders, and additional folders.

    From: /tf/active/vicechatdev/SPFCsync/test_folder_structure.py
  • function get_root_folders 73.1% similar

    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.

    From: /tf/active/vicechatdev/SPFCsync/test_folder_structure.py
  • function explore_alternative_endpoints 73.1% similar

    Tests multiple Microsoft Graph API endpoints to locate missing folders in a SharePoint drive by trying different URL patterns and searching for expected folders.

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