AI & Agents

OneDrive Search API: Microsoft Graph File Search Guide

The OneDrive Search API, exposed through Microsoft Graph, enables programmatic text searching, filename matching, and metadata filtering across personal and business OneDrive drives. Developers querying drive items often face rate throttling, complex OAuth permission scopes, and fragmented results across tenant libraries. Syncing files into an intelligent workspace lets AI agents search indexed content directly over MCP without recursive folder traversal.

Derek Labian 12 min read Updated
Querying files through Microsoft Graph and agent storage layers

How the OneDrive Search API Queries Files Across Drives

Developers connecting automated tools or autonomous agents to Microsoft OneDrive often assume a single search endpoint returns every relevant document across the organization. In practice, searching OneDrive via Microsoft Graph requires navigating distinct scopes between personal drives, enterprise OneDrive for Business accounts, and backing SharePoint site libraries, each with separate permission models and rate limits.

The OneDrive Search API, exposed through Microsoft Graph, enables programmatic text searching, filename matching, and metadata filtering across personal and business OneDrive drives. Instead of relying on a dedicated search server or third-party crawler, developers query the Microsoft Graph REST API using an OData function syntax attached to a specific drive or driveItem hierarchy. The official Microsoft Graph driveItem search documentation defines how queries evaluate folder trees and drive collections.

Understanding the endpoint landscape begins with how Microsoft Graph organizes storage containers:

  • Endpoint Syntax: GET https://graph.microsoft.com/v1.0/me/drive/root/search(q='{query}') searches within the root folder hierarchy of the signed-in user. The broader endpoint GET https://graph.microsoft.com/v1.0/me/drive/search(q='{query}') searches across the entire personal drive, including documents shared with the user.
  • Targeted Drive Syntax: GET https://graph.microsoft.com/v1.0/drives/{drive-id}/root/search(q='{query}') searches a specific drive container, such as a designated OneDrive for Business archive or an enterprise document repository.
  • SharePoint Site Library Syntax: GET https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root/search(q='{query}') addresses a document library associated with a specific SharePoint team site.
  • OAuth Permissions: Delegated operations require Files.Read or Files.Read.All. Background services, scheduled daemon processes, and autonomous agents executing without a signed-in user require application permissions such as Files.Read.All with tenant administrator consent.
  • Response Item Structure: The API returns an HTTP 200 response with a JSON object containing a value array of driveItem resources. Each item details core file properties (id, name, size, webUrl, lastModifiedDateTime), file or folder facets, and an @odata.nextLink property whenever result sets exceed the page size.

A frequent source of integration bugs is the architectural divide between personal OneDrive accounts and OneDrive for Business. Personal accounts authenticate consumer Microsoft identities through the Microsoft identity platform. In contrast, OneDrive for Business accounts are provisioned within an organization's Microsoft 365 tenant.

Under the hood, OneDrive for Business drives are personal SharePoint document libraries hosted at individual tenant URLs. While personal OneDrive drives allow simple delegated sign-ins, querying OneDrive for Business requires proper tenant scoping. Attempting to access personal drive endpoints using organization-scoped application tokens produces HTTP 400 Bad Request or HTTP 404 Not Found errors. Understanding which drive container holds the target documents determines which endpoint path you must call. For teams reviewing architectural alternatives, exploring a dedicated OneDrive alternative can clarify how different cloud platforms structure multi-tenant storage.

Hierarchical indexing structure across personal and business cloud drives

Microsoft Graph Search Syntax, Query Parameters, and Response Payloads

The search function in Microsoft Graph queries both document metadata and document bodies. When you issue a request to search(q='...'), the Microsoft search subsystem evaluates matches across filenames, custom metadata attributes, and the extracted text content of supported file formats. Supported file types include Microsoft Word documents, Excel workbooks, PowerPoint presentations, plain text files, CSV exports, and text-layer PDFs.

Constructing search queries requires adhering to specific URL formatting rules. The search string is passed inside parentheses following the q parameter key:

GET /v1.0/me/drive/root/search(q='annual%20financial%20review') HTTP/1.1
Host: graph.microsoft.com
Authorization: Bearer YOUR_MICROSOFT_GRAPH_ACCESS_TOKEN
Accept: application/json

Query values must be properly URL-encoded. Spaces become %20, and special characters must be escaped. When searching for multi-word phrases where order matters, enclose the search terms in escaped quotes within the query parameter.

To optimize performance and minimize network bandwidth, Microsoft Graph supports standard OData query parameters alongside the search function:

  • $select: Limits the properties returned for each item. By default, Microsoft Graph returns an extensive set of metadata properties. Requesting only $select=id,name,size,webUrl,file,lastModifiedDateTime significantly reduces response size and processing overhead.
  • $top: Specifies the maximum number of items returned in a single page. Setting $top=25 or $top=50 establishes predictable batch boundaries.
  • $skipToken: Powers pagination. When a search matches more items than the requested $top limit, Microsoft Graph appends an @odata.nextLink URL containing an opaque skip token to the response payload.
  • $orderby: Orders results based on specific fields, such as lastModifiedDateTime desc. Note that sorting capabilities depend on the indexing status of the target drive.

A typical response from the drive search endpoint returns a JSON payload structured around an array of driveItem objects:

{
  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(driveItem)",
  "value": [
    {
      "@odata.type": "#microsoft.graph.driveItem",
      "id": "01ABCD5678EFGH9012",
      "name": "Q3-Financial-Summary.docx",
      "size": 1048576,
      "webUrl": "https://tenant-my.sharepoint.com/personal/user/Documents/Q3-Financial-Summary.docx",
      "lastModifiedDateTime": "2026-09-15T14:30:00Z",
      "file": {
        "mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      },
      "parentReference": {
        "driveId": "b!1234abcd5678efgh",
        "id": "01ROOTFOLDERID",
        "path": "/drive/root:/Finance/Reports"
      },
      "searchResult": {
        "onClickTelemetryUrl": "https://bing.com/telemetry/01ABCD5678EFGH9012"
      }
    }
  ],
  "@odata.nextLink": "https://graph.microsoft.com/v1.0/me/drive/root/search(q='annual%20financial%20review')&$top=25&$skipToken=X'1234567890ABCDEF'"
}

When parsing this response, client applications inspect the item facets. The presence of a file facet indicates a downloadable document, whereas a folder facet indicates a directory container. The parentReference property provides the drive ID and folder path, which is critical when an agent needs to determine the context or provenance of a discovered document.

Calling the OneDrive Search API requires obtaining a valid OAuth 2.0 access token from Microsoft Entra ID. The exact authentication flow depends on whether your software operates interactively on behalf of an active user or autonomously as a background daemon.

Delegated permissions apply when a human user signs into the application:

  • Files.Read: The least privileged delegated scope for searching documents. It grants read access to files the signed-in user can access in their personal drive.
  • Files.Read.All: Allows the application to search all files across personal drives, shared drives, and SharePoint site document libraries that the signed-in user has permission to view.
  • Files.ReadWrite and Files.ReadWrite.All: Grant read and write permissions, necessary if the tool modifies, tags, or moves search results.

For autonomous agents, scheduled background jobs, or command-line scripts, delegated permissions introduce operational friction because they require periodic interactive browser sign-in or refresh token management. Background services rely instead on application permissions via the OAuth 2.0 client credentials grant.

In the client credentials flow, the service authenticates directly with its client ID, tenant ID, and client secret or certificate:

  • Files.Read.All: The minimum application permission required to execute searches across drives.
  • Files.ReadWrite.All: Full application-level write and read access across all drives in the tenant.

This is where enterprise teams hit administrative consent friction. In Microsoft Entra ID, application permissions like Files.Read.All cannot be granted by individual knowledge workers. They require tenant-wide administrator consent. Because granting Files.Read.All at the application level gives the agent read access to every OneDrive folder and SharePoint site across the entire company, enterprise IT administrators frequently reject or stall integration requests.

Beyond permissions, developers must account for service limits. Microsoft Graph enforces strict 429 throttling limits on high-frequency search requests. According to the Microsoft Graph throttling guidance, Microsoft Graph returns HTTP status code 429 when client requests exceed service rate limits.

When Microsoft Graph throttles a search request, the response includes an HTTP 429 status code and a Retry-After header specifying the exact number of seconds the client must wait:

HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 8

{
  "error": {
    "code": "activityLimitReached",
    "message": "The request has been throttled."
  }
}

Building reliable client software requires catching HTTP 429 errors, parsing the Retry-After header value, and pausing execution for the indicated duration. If an application retries immediately without honoring the delay, Microsoft Graph treats the subsequent request as continued activity and extends the throttling window. When the Retry-After header is absent, applications should fall back to an exponential backoff policy with randomized jitter.

Fastio features

Index and Search OneDrive Files for Autonomous Agents

Connect your existing OneDrive folders to Fast.io workspaces with Cloud Sync, letting AI agents search and retrieve indexed documents through a remote MCP server without complex Graph API queries. Start a 14-day free trial.

Operational Bottlenecks When Autonomous Agents Query OneDrive Directly

Modern software development increasingly relies on autonomous AI agents running in tools like Claude Code, Cursor, Codex, OpenClaw, or custom orchestration frameworks. When developers configure an agent to search and analyze enterprise files directly against the Microsoft Graph OneDrive API, several architectural friction points emerge.

The primary obstacle is context overhead and file retrieval latency. A search query to /drive/root/search returns metadata records, not file contents. When an agent searches for specific contract language or technical specifications, the API returns a list of candidate filenames and IDs. To read the actual text, the agent must issue secondary HTTP calls to /drive/items/{item-id}/content for each matched document.

Downloading raw documents in sequence creates significant performance bottlenecks:

  • Payload Bloat: Office documents and complex PDFs are binary packages. An agent cannot parse binary Office Open XML without extracting internal XML streams, consuming compute and local disk storage.
  • Token Consumption: If the agent downloads several large PDF files to inspect a few paragraphs, converting those documents into prompt context burns thousands of tokens. Context windows quickly saturate, inflating API inference costs and slowing response cycles.
  • Fragmented Drive Topologies: Corporate documents rarely live in a single folder. Files are scattered across personal OneDrive folders, department SharePoint document libraries, and Microsoft 365 group channels. An agent issuing direct Graph API calls must discover relevant site IDs, enumerate drive collections, and execute parallel search queries across disparate containers.
  • Rate Limit Compounding: An agent executing complex multi-step reasoning often performs iterative searches. Repeating search queries across multiple drive IDs rapidly triggers Microsoft Graph 429 throttling, causing execution timeouts in automated agent runs.

These constraints reveal a fundamental mismatch: Microsoft Graph was built for human-driven application interfaces and bulk enterprise sync, not for sub-second semantic retrieval during live AI reasoning loops. Developers seeking scalable storage for agents frequently separate long-term file archives from active reasoning context.

Bridging OneDrive Storage into Intelligent Workspaces with Fast.io

Rather than forcing AI agents to execute direct, brittle Microsoft Graph API calls, teams are adopting a hybrid architecture: keep your corporate files in Microsoft OneDrive and SharePoint, but bridge them into a workspace platform designed for agentic workflows.

In this model, your team continues using Microsoft OneDrive for everyday human document storage, collaboration, and enterprise governance. Through Fast.io Cloud Sync, designated OneDrive folders and SharePoint document libraries synchronize into a shared Fast.io workspace. Cloud Sync for Google Drive, OneDrive, Box, and Dropbox operates one-way or two-way, running on a schedule or on demand (never continuous, live, or real-time).

Once files synchronize into a Fast.io workspace, the system indexes them automatically:

  • Built-in Workspace Intelligence: Through Fast.io workspace intelligence, Intelligence Mode auto-indexes documents for full-text search and semantic retrieval. Files are queryable immediately without managing external vector databases, chunking pipelines, or embedding models.
  • Consolidated Remote MCP Tooling: AI agents connect to the Fast.io Model Context Protocol (MCP) server running remotely at https://mcp.fast.io/mcp/tools over Streamable HTTP. Interactive clients sign in with OAuth in the browser, while headless code sends Authorization: Bearer <api key> on the connection. Learn more in the Fast.io MCP server documentation.
  • Direct Excerpt Retrieval: Instead of downloading entire multi-megabyte documents to inspect text, the agent uses the unified workspace storage search action. The agent submits a query and receives relevant text excerpts, matching file metadata, and semantic citations directly in its context window.
  • Structured Data Extraction: With Fast.io Metadata Views, teams can describe the exact fields they need from unstructured documents in natural language. The extraction layer structures information (such as contract dates, counterparties, invoice totals, and project milestones) into typed schemas (Text, Integer, Decimal, Boolean, Date & Time, URL, JSON) across PDFs, Word docs, and scanned pages without rigid templates. Agents can query these structured views directly through MCP.

In benchmark testing across agent storage connectors, connector performance varies considerably. The connector comparison is published at https://fast.io/benchmarks/ and describes comparative retrieval latency and token efficiency across storage providers in Claude Cowork. Fastio was measured the fastest and the lowest cost of the providers tested.

Beyond search efficiency, Fast.io provides collaboration and control infrastructure: per-file version history preserves every revision during concurrent writes, a detailed activity log records file access, and advisory file locks allow agents to coordinate edits without overwriting human teammates.

Creating an account is free; doing real work requires an organization on a paid subscription. Monthly plans start with a 14-day free trial that requires a credit card. Paid subscription plans, detailed on the pricing page, are Starter at $9.99/mo (3 seats, 250 GB storage, 5 workspaces, 100,000 credits a month), Business at $49.99/mo (10 seats, 5 TB storage, 50 workspaces, 600,000 credits a month), and Enterprise at $199.99/mo (30 seats included with additional seats at $1 per seat up to 200, 25 TB storage, 200 workspaces, 3,000,000 credits a month). Annual plan billing is $99, $499, and $1,999 a year. Credits meter AI operations, with additional credit packs available at $10 per 100,000 credits.

Sources

References used to verify factual claims in this guide.

  1. Microsoft Graph returns HTTP status code 429 when client requests exceed service rate limits.

Frequently Asked Questions

How do I search OneDrive files using Microsoft Graph API?

You search OneDrive files by sending an authenticated GET request to the Microsoft Graph endpoint https://graph.microsoft.com/v1.0/me/drive/root/search(q='{search-text}'). This endpoint queries the signed-in user's drive hierarchy, matching the search term across filenames, system metadata, and indexed text contents of common document formats.

What permissions are needed to search OneDrive via API?

Delegated user applications require Files.Read as the least privileged permission, or Files.Read.All to search across all drives the user can access. Autonomous daemon services using application credentials require Files.Read.All, which must be consented to by an enterprise Microsoft Entra ID tenant administrator.

Can Microsoft Graph search within OneDrive file contents?

Yes. Microsoft Graph automatically indexes the text content of supported file types stored in OneDrive and SharePoint, including Microsoft Word (.docx), Excel (.xlsx), PowerPoint (.pptx), plain text, CSV, and text-based PDF documents. Search queries match both item titles and internal document text.

How does Microsoft Graph handle search rate limiting and 429 throttling?

When request volumes exceed service limits, Microsoft Graph responds with an HTTP 429 Too Many Requests status code and includes a Retry-After response header. The header specifies the exact number of seconds the client must pause before retrying the call. Applications must respect this delay to avoid prolonged throttling.

What is the difference between OneDrive search and Microsoft Search API?

The OneDrive search endpoint (/drive/root/search) is an OData function scoped directly to a specific drive or folder container. The Microsoft Search API (/search/query) is an enterprise-level POST endpoint that executes complex query strings across OneDrive, SharePoint, Exchange emails, and Teams chat history in a unified query.

How can AI agents search OneDrive files without downloading whole documents?

Teams can sync their existing OneDrive folders into a Fast.io workspace using Cloud Sync. The workspace indexes the documents for keyword and semantic search, allowing AI agents to connect via a remote MCP server and retrieve concise text excerpts and structured metadata views without downloading raw multi-megabyte files.

Related Resources

Fastio features

Index and Search OneDrive Files for Autonomous Agents

Connect your existing OneDrive folders to Fast.io workspaces with Cloud Sync, letting AI agents search and retrieve indexed documents through a remote MCP server without complex Graph API queries. Start a 14-day free trial.