How to List Files with OneDrive API: Graph Endpoints and Agent Workspaces
The OneDrive API, integrated into Microsoft Graph, lists drive items using the /me/drive/root/children or /drives/{drive-id}/items/{item-id}/children endpoints. Large directories require following @odata.nextLink tokens across requests. While manual pagination works for scripts, autonomous agents face token bloat when crawling deep folder trees. Connecting OneDrive storage to Fast.io workspaces lets AI tools query indexed documents directly over MCP without traversing raw directories.
How to Use the OneDrive API to List Files with Microsoft Graph Endpoints
Querying Microsoft Graph to list OneDrive files recursively causes autonomous agents to burn through API quotas and context windows before inspecting a single document. Each folder level requires an extra HTTP round trip, and large directories trigger @odata.nextLink pagination loops that return repetitive JSON metadata. The architectural solution is keeping existing files in OneDrive while syncing target folders into an intelligent workspace where an agent searches indexed content directly over the Model Context Protocol.
The OneDrive API, integrated into Microsoft Graph, lists drive items using the /me/drive/root/children or /drives/{drive-id}/items/{item-id}/children endpoints.
To list drive items within Microsoft OneDrive, developers interact with the unified Microsoft Graph REST API. Under the Microsoft Graph resource model, both individual files and directories are represented as driveItem resources stored within a specific drive. For teams exploring alternatives or building custom integrations, Fast.io storage for agents provides dedicated endpoints designed for structured agent access.
Step-by-Step Instructions for Querying Root Versus Folder Children
Listing drive items follows a structured endpoint progression depending on whether you query the top-level root directory or a specific nested folder:
- Obtain Authentication Credentials: Register an application in Microsoft Entra ID and acquire an OAuth 2.0 access token with delegated
Files.Reador applicationFiles.Read.Allpermissions. - List Root Children: Send an HTTP
GETrequest tohttps://graph.microsoft.com/v1.0/me/drive/root/childrento retrieve all items located at the root of the authenticated user's personal or business drive. - List Children in a Specific Folder by ID: Extract the
idstring from any parent folder item, then issue aGETrequest tohttps://graph.microsoft.com/v1.0/me/drive/items/{item-id}/children(orhttps://graph.microsoft.com/v1.0/drives/{drive-id}/items/{item-id}/childrenwhen targeting a shared or enterprise drive). - Distinguish Files from Folders: Inspect the JSON objects in the returned
valuearray. Objects containing afolderkey represent directories, while objects containing afilekey represent downloadable documents.
Here is an example request targeting the root folder of the current user's personal or business drive:
curl -X GET "https://graph.microsoft.com/v1.0/me/drive/root/children" \
-H "Authorization: Bearer your-access-token" \
-H "Accept: application/json"
The response returns a JSON payload containing an array of driveItem resources:
{
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('user-id')/drive/root/children",
"value": [
{
"id": "01ABCDEXYZ1234567890",
"name": "Financial Reports",
"size": 409600,
"webUrl": "https://onedrive.live.com/?id=...",
"lastModifiedDateTime": "2026-09-18T14:22:10Z",
"folder": {
"childCount": 12
},
"parentReference": {
"driveId": "b!1234567890",
"id": "01ROOTITEMID",
"path": "/drive/root:"
}
},
{
"id": "01ABCDEXYZ0987654321",
"name": "q3-forecast.xlsx",
"size": 1048576,
"webUrl": "https://onedrive.live.com/?id=...",
"lastModifiedDateTime": "2026-09-29T10:15:00Z",
"file": {
"mimeType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"hashes": {
"quickXorHash": "aBcDeFgHiJkLmNoPqRsTuVwXyZ="
}
},
"parentReference": {
"driveId": "b!1234567890",
"id": "01ROOTITEMID",
"path": "/drive/root:"
}
}
]
}
Addressing Items by Path Versus Unique Identifier
Microsoft Graph allows developers to address folders by filesystem path or by immutable resource ID. While path-based addressing feels intuitive for file navigation, ID-based addressing is strictly more reliable for software pipelines and background services.
Path-based syntax requires colon separators around the relative path:
GET https://graph.microsoft.com/v1.0/me/drive/root:/Documents/Q3_Reports:/children
When using path-based addressing, all spaces and special characters must be percent-encoded (%20 for spaces). If a human user renames or relocates any parent directory in OneDrive, path-based requests immediately break and return HTTP 404 (itemNotFound).
ID-based addressing decouples your code from folder names:
GET https://graph.microsoft.com/v1.0/me/drive/items/01ABCDEXYZ1234567890/children
The item ID remains stable even when users rename the folder, move it to another parent directory, or alter folder hierarchies in the OneDrive web application. Production integrations should store the folder ID after the first discovery call and address all subsequent read operations using the ID endpoint.
Related guides
- How to List Files with SharePoint API: REST, Graph, and Agent WorkspacesListing files across SharePoint environments requires choosing between legacy REST endpoints and Microsoft Graph drive...
- How to Create Folders with SharePoint API: REST, Graph, and Agent WorkspacesCreating folders across SharePoint environments requires choosing between legacy REST endpoints and modern Microsoft...
- How to List Files with the Dropbox API: Pagination, Cursors, and Agent WorkspacesListing files through the Dropbox API requires managing cursor-based pagination across the /files/list_folder and...
- How to Download Files via OneDrive API: Microsoft Graph GuideDownloading a file via the OneDrive API requires requesting the binary stream from a driveItem content endpoint using...
- Can ChatGPT Upload Files to Google Drive? How to Save AI OutputsChatGPT cannot natively upload, write, or export files directly back to Google Drive; its native integration is...
- How to Give ChatGPT Access to Local Files and Synced FoldersConnecting ChatGPT to local files and synced cloud directories eliminates repetitive manual uploads and keeps document...
More on this subject: Agent File and Document Workflows (269 guides)
How to Handle Pagination and Large Directories with OData NextLink
Folders containing dozens or hundreds of documents cannot be retrieved in a single payload. OneDrive Graph pagination uses @odata.nextLink tokens for collections exceeding default limits.
When additional pages of data are available in Microsoft Graph, the service returns an @odata.nextLink property in the response that contains a URL to the next page of results.
By default, Microsoft Graph returns up to 200 items per response page when listing children of a OneDrive drive item. You can influence the page size by appending the $top query parameter (for example, $top=50), but the server retains authority over the actual number of items returned. Review the official Microsoft Graph paging documentation for full protocol details.
The @odata.nextLink URL contains pre-encoded state, including authentication context and internal continuation markers such as $skiptoken. The official Microsoft documentation requires client applications to treat this URL as opaque. You must never parse, strip, or alter query parameters from @odata.nextLink. Pass the complete URL directly into the next HTTP GET request.
When the final page of files is reached, the @odata.nextLink property is omitted from the response JSON. That missing key indicates that all children in the folder have been retrieved.
Production Python Script for Recursive Directory Pagination
The following Python script illustrates how to paginate through all drive items within a specific OneDrive folder and handle rate limits:
import time
import requests
def list_all_onedrive_files(access_token: str, folder_id: str = "root") -> list[dict]:
headers = {
"Authorization": f"Bearer {access_token}",
"Accept": "application/json"
}
if folder_id == "root":
url = "https://graph.microsoft.com/v1.0/me/drive/root/children?$top=100"
else:
url = f"https://graph.microsoft.com/v1.0/me/drive/items/{folder_id}/children?$top=100"
all_items = []
while url:
response = requests.get(url, headers=headers)
# Handle rate limiting backoff
if response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", 5))
time.sleep(retry_after)
continue
response.raise_for_status()
data = response.json()
items = data.get("value", [])
all_items.extend(items)
# Read the nextLink token for subsequent pages
url = data.get("@odata.nextLink")
return all_items
Notice the handling of HTTP status 429. Microsoft Graph enforces dynamic throttling based on tenant activity. When your script exceeds the allowed request volume, Microsoft Graph returns HTTP 429 along with a Retry-After response header indicating how many seconds to wait before retrying. Honoring this header prevents Entra ID from temporarily blocking the application.
Avoiding Token Expiration During Long Batch Operations
A common trap in directory crawling occurs when paginating massive corporate storage trees containing thousands of files. Entra ID OAuth 2.0 access tokens typically expire after 60 to 90 minutes.
If a recursive listing script crawls deeply nested directories, the access token can expire midway through pagination. Re-authenticating produces a new access token, but using a fresh token against an existing @odata.nextLink URL that contains a stale $skiptoken can cause a DirectoryPageTokenNotFoundException error.
To avoid broken pagination runs on large libraries:
- Check token expiration timestamps before initiating each batch of child queries.
- Persist the last valid
@odata.nextLinkURL along with folder identifiers so interrupted sync processes can resume without restarting from root. - Restrict directory queries using the
$selectquery parameter (such as$select=id,name,size,file,folder) to minimize response payload sizes and decrease transmission time.
Why Recursive Directory Scanning Fails for Autonomous Agents
Standard developer guides recommend writing recursive scripts that inspect each item, check for the folder facet, and call /items/{item-id}/children on every subfolder. While this approach works for scheduled data backup jobs, it fails when applied to autonomous AI agents like Claude, Codex, or OpenAI agent runtimes.
AI agents operate under finite context windows and pay per token for every input processed. Pointing an AI agent directly at Microsoft Graph creates severe operational bottlenecks:
- Token Consumption: A typical enterprise OneDrive folder tree with several hundred files generates hundreds of kilobytes of verbose JSON metadata. Ingesting raw directory trees consumes valuable context tokens before the model reads a single paragraph of substantive content.
- Context Dilution: File listings contain technical fields such as
eTag,cTag,hashes, and parent drive references. These strings provide no semantic value to the reasoning engine and distract attention mechanisms from the core objective. - Latency Multipliers: Traversing a four-level folder hierarchy requires four sequential round trips to Microsoft Graph. With pagination and throttling delays, an agent can spend thirty seconds wandering through folder structures before locating the document it needs.
- Incomplete Visibility: If an agent encounters a rate limit or stops paginating prematurely to conserve context, it misses critical documents buried in subdirectories.
The Limits of Native Storage Connectors
Native storage connectors attempt to bridge this divide by letting conversational interfaces search cloud storage directly. For example, Claude Cowork and native Microsoft 365 connectors connect directly to Microsoft Graph endpoints under delegated tenant permissions.
However, native connectors still perform on-demand API queries against the storage provider's raw directory structure. When processing queries across dense document collections, direct API traversal creates tool-call overhead and slows down agent execution.
In published connector benchmarks, Fastio was measured fastest and lowest cost among tested providers.
The benchmark measured provider native connectors in Claude Cowork across storage systems. Fastio achieved these performance results while maintaining parity on accuracy, demonstrating that intelligent workspace indexing solves the retrieval problem far more effectively than querying raw directory APIs on demand. For teams comparing storage architectures, see how Fast.io compares with OneDrive alternatives.
Index OneDrive Folders for AI Agent Workspaces
Connect your OneDrive storage to Fast.io workspaces with automated indexing and remote MCP retrieval. Start your 30-day trial with a credit card.
How to Connect OneDrive to Fastio Workspaces for Agent Access
The solution to agent retrieval bottlenecks is not abandoning your company's existing OneDrive storage. Teams already maintain established folder conventions, corporate access controls, and active collaboration inside Microsoft 365.
The practical architecture keeps files in OneDrive while linking relevant directories to an intelligent Fast.io workspace.
Cloud Sync: From Raw Files to Searchable Knowledge
Fast.io provides Cloud Sync for Dropbox, Box, and OneDrive. Cloud Sync runs one-way or two-way on a schedule or on demand. It is never continuous, live, or real-time. SharePoint document libraries can also be connected through the OneDrive connector. (For teams using Google Drive, Drive imports today with sync coming soon.)
When you connect a OneDrive folder to a Fast.io workspace:
- Files sync into the workspace according to your chosen schedule or on demand.
- Intelligence Mode automatically indexes incoming documents for full-text and semantic retrieval on arrival, unlocking built-in Fast.io AI capabilities.
- Documents become immediately queryable through vector search and structured metadata extraction without manual chunking or separate database configuration.
Your team continues working in OneDrive as usual. When updates sync into Fast.io, the workspace updates its semantic indexes, preparing the documents for immediate agent access.
Accessing the Workspace Over Remote MCP
Rather than teaching an AI agent to authenticate with Microsoft Graph and paginate through raw drive items, the agent connects directly to Fast.io using the Model Context Protocol (MCP).
Fast.io hosts a remote MCP server over Streamable HTTP. Depending on your agent runtime, configure the designated endpoint:
- Claude Applications and General MCP Clients: Connect to
https://mcp.fast.io/mcp/toolswith interactive OAuth sign-in. - ChatGPT and Codex: Install the Fastio plugin directly from the plugin directory. If custom server configuration is required, use
https://mcp.fast.io/mcp/operations. - Coding Agents (Claude Code, Cursor, Gemini CLI): Connect to
https://mcp.fast.io/mcp/code.
For headless bots, background workers, and automated scripts, authenticate by passing an API key in the connection header: Authorization: Bearer your-fastio-api-key. Setup instructions are documented at the Fast.io MCP setup guide.
When an agent needs information from your OneDrive files, it calls the MCP server's search actions. Instead of scanning hundreds of folder entries, the agent issues a single semantic query and receives relevant document excerpts with exact file citations.
Comparing Graph API Crawling to Semantic Workspace Retrieval
Choosing between raw Microsoft Graph crawling and intelligent workspace retrieval depends on the software executing the task. The two approaches serve different architectural roles.
In direct Microsoft Graph crawling, the client application authenticates with Entra ID, queries folder endpoints, and loops through nextLink tokens to traverse directory hierarchies. This pattern requires multiple network round trips and incurs high latency and token costs when inspected by an LLM.
In Fast.io workspace retrieval, the OneDrive folder synchronizes into the workspace via Cloud Sync on a schedule or on demand. The files are indexed on arrival. When an agent needs information, it executes a remote MCP search request against the workspace, returning instant semantic matches with precise citations.
Direct Graph API Crawling
Direct Graph API queries are ideal for deterministic backend scripts that manage file lifecycle operations. Use direct Graph API calls when:
- Writing automated data migration utilities that transfer raw file blobs between storage systems.
- Building compliance backup tools that verify folder hierarchies and export complete file inventories.
- Modifying file metadata, updating file permissions, or generating direct OneDrive download URLs.
In this pattern, your application assumes responsibility for handling OAuth token refreshes, following @odata.nextLink loops, managing directory pagination thresholds, and backing off during HTTP 429 throttling events.
MCP Workspace Retrieval
Intelligent workspace retrieval over MCP is designed for AI reasoning engines, automated researchers, coding agents, and conversational assistants. Use Fast.io workspace retrieval when:
- An AI agent needs to answer questions based on documents stored across nested folders.
- Token budgets and context windows must be protected from raw JSON metadata pollution.
- Multiple agents and human team members collaborate on shared files within the same workspace.
Here is an example showing how an agent on https://mcp.fast.io/mcp/code searches indexed OneDrive documents using the search tool:
{
"method": "tools/call",
"params": {
"name": "search",
"arguments": {
"query": "Q3 enterprise renewal revenue targets and risk factors",
"limit": 3
}
}
}
The Fast.io workspace processes the query across the indexed corpus and returns focused text extracts accompanied by document citations, file paths, and version identifiers. The agent receives the exact information required to complete its assignment without issuing a single directory listing call.
Governance, Permissions, and Plan Details
Fast.io provides granular access controls across organizations, workspaces, folders, and files. Every file maintains a complete version history, and an append-only audit log records document changes and agent access events.
Creating an account is free; running shared workspaces requires an organization subscription. Monthly plans start with a 30-day free trial that requires a credit card. Credits meter AI work. Storage and seats come with the plan. Detailed plan specifications and credit allowances are documented on the Fast.io pricing page:
Sources
References used to verify factual claims in this guide.
-
Microsoft Graph returns an @odata.nextLink property containing a URL to the next page of results when additional pages are available.
Frequently Asked Questions
How do I get a list of files from OneDrive using API?
In Microsoft Graph, list files in the root folder by sending an HTTP GET request to https://graph.microsoft.com/v1.0/me/drive/root/children with a valid Entra ID bearer token. To list items in a specific subfolder, send a GET request to https://graph.microsoft.com/v1.0/drives/{drive-id}/items/{item-id}/children using the target folder's unique item ID.
How do I paginate through OneDrive files in Microsoft Graph?
When a folder contains more items than the page limit, Microsoft Graph returns an @odata.nextLink property in the response body. Your application must issue a new GET request to the exact URL specified in @odata.nextLink without altering its encoded query parameters. Continue fetching subsequent pages until the @odata.nextLink property is omitted.
How can AI agents connect to OneDrive without slow directory scans?
Instead of having AI agents recursively call Microsoft Graph to crawl folder hierarchies, connect the OneDrive folder to a Fast.io workspace using Cloud Sync on a schedule or on demand. Fast.io automatically indexes documents for semantic search. The agent connects to the remote Fast.io MCP server over Streamable HTTP and queries indexed content directly, avoiding token-heavy directory crawls.
What Microsoft Graph permissions are required to list OneDrive files?
To list files in a user's personal or business OneDrive, your application requires the delegated Files.Read or Files.Read.All permission. For background daemon scripts running without an interactive user login, register the application in Microsoft Entra ID and assign the application permission Files.Read.All with administrator consent.
Can I query SharePoint document libraries using the OneDrive API endpoints?
Yes. In Microsoft Graph, SharePoint document libraries are exposed as drives. You can query a SharePoint library by first retrieving the site and drive identifiers via GET /sites/{site-id}/drives, and then listing the library items using GET /drives/{drive-id}/root/children or GET /drives/{drive-id}/items/{item-id}/children.
Related Resources
Index OneDrive Folders for AI Agent Workspaces
Connect your OneDrive storage to Fast.io workspaces with automated indexing and remote MCP retrieval. Start your 30-day trial with a credit card.