如何通过Microsoft Graph API直接提取指定文件夹及子文件夹下的所有文件
解决方案
方法一:使用Microsoft Graph Search API直接搜索目标文件夹下的所有文件
由于children和delta端点本身不支持针对file属性的$filter(这是API的限制),你可以改用Search API实现跨子文件夹的文件批量检索,无需遍历所有文件夹,大幅减少请求次数。
请求构造
通过POST请求调用Search API,限定搜索范围为指定驱动器的/P文件夹,且仅返回文件:
- 请求URL:
https://graph.microsoft.com/v1.0/search/query - 请求头:需携带有效的Bearer Token,
Content-Type设为application/json - 请求体示例:
{ "requests": [ { "entityTypes": ["driveItem"], "query": { "queryString": "driveId:{drive_id} AND path:\"/P\" AND isDocument:true" }, "select": ["createdDateTime", "eTag", "lastModifiedDateTime", "name", "webUrl", "size"], "from": 0, "size": 250 } ] }
参数说明:
driveId:{drive_id}:限定搜索范围到目标驱动器,避免跨驱动器结果path:"/P":指定搜索根文件夹为/P(包含所有子文件夹)isDocument:true:确保仅返回文件(排除文件夹)select:指定需要返回的文件属性,和你之前需求一致size:单次请求最大返回250条结果,需分页处理
Python代码示例
import requests def get_all_files_via_search(drive_id, token): search_url = "https://graph.microsoft.com/v1.0/search/query" headers = { "Authorization": f"Bearer {token}", "Content-Type": "application/json" } all_files = [] current_offset = 0 page_size = 250 while True: payload = { "requests": [ { "entityTypes": ["driveItem"], "query": { "queryString": f"driveId:{drive_id} AND path:\"/P\" AND isDocument:true" }, "select": ["createdDateTime", "eTag", "lastModifiedDateTime", "name", "webUrl", "size"], "from": current_offset, "size": page_size } ] } response = requests.post(search_url, json=payload, headers=headers) response.raise_for_status() search_result = response.json() # 提取当前页的文件资源 hits_container = search_result["value"][0]["hitsContainers"][0] current_files = [hit["resource"] for hit in hits_container["hits"]] all_files.extend(current_files) # 判断是否还有下一页 total_hits = hits_container["totalHits"] if len(all_files) >= total_hits: break current_offset = len(all_files) return all_files
为什么之前的过滤方法无效?
Microsoft Graph的children端点和delta端点不支持针对file属性的$filter条件:
- 对
delta端点使用filter=file ne 'null'时,API不会解析该过滤规则,会返回所有项(包括文件夹) - 对
children端点使用同样的过滤条件,会直接返回"Operation not supported"错误,这是API的设计限制
内容的提问来源于stack exchange,提问作者María Casasola Calzadilla
相关产品推荐
相关产品推荐

