OneDrive API Guide

Microsoft Graph provides REST endpoints for files and folders in personal OneDrive, OneDrive for Business, and SharePoint document libraries. Applications can list, upload, download, organize, share, and synchronize this content. This guide links to 30 complete examples using direct Chilkat.Http calls.

A drive is a container such as a user's OneDrive or a SharePoint document library. A driveItem is a file, folder, or other item within that drive. Most operations identify a drive and an item. A SharePoint site can contain several drives. These requests access online storage directly; the OneDrive desktop application does not need to be running. Microsoft's file API overview.

Use an unlocked Chilkat library, version 11.6.0 or later. The examples target https://graph.microsoft.com/v1.0 in the global Microsoft cloud. National clouds require their own identity and Graph endpoints. Start with authorization, discover a drive, and then list its contents or address a known path.

Making Graph requests with Chilkat
Request or responseChilkat operation
Bearer authenticationSet Http.AuthToken to the access token, without the Bearer prefix.
GET, DELETE, or a bodyless actionUse Http.HttpNoBody with the verb, URL, and HttpResponse.
POST or PATCH with JSONBuild a JsonObject and pass it to Http.HttpJson.
Upload text or bytesUse Http.HttpStr for explicitly encoded text or Http.HttpBd for a BinData payload.
Stream a local fileConfigure a HttpRequest to stream the file and submit it with Http.HttpReq.
Read a responseCheck StatusCode before parsing JSON or using binary content. Enable JsonObject.Strict when loading JSON.

A false method result can still contain an HTTP error response; status zero means no response arrived. Check the status expected by the operation. Typical successes include 200 for reads and updates, 201 for creation, 202 for accepted asynchronous work, and 204 for deletion or version restoration. Empty responses do not need JSON parsing.

Authentication

Register an application in Microsoft Entra and choose the supported account types. Delegated access acts with a signed-in user's permissions and works with personal or organizational accounts supported by the registration. Application access is for administrator-authorized Microsoft 365 operations; it does not provide unattended access to personal OneDrive accounts.

Choose the access model
ModelTypical addressingPermission considerations
Delegated user access/me/drives or an authorized /drives/{driveId}Files.Read for ordinary reads; Files.ReadWrite for ordinary file changes. Specific operations can require additional permissions.
Application access/users/{id-or-UPN}/drives, /sites/{siteId}/drives, or a known driveAdministrator-consented application permissions. The two application examples use Files.Read.All for drive discovery. Check each operation before extending access.

/me requires a signed-in user. Changing an endpoint to /users or /drives does not itself grant access. A token's scopes, the user's actual access, and tenant policy all matter. The SharePoint site lookup needs Sites.Read.All; resolving a sharing URL requires Files.ReadWrite despite being a GET. Use each example's permission notes and the Graph permissions reference.

Interactive sign-in and delegated refresh

The authorization example uses PKCE with S256 and a system browser. Register http://localhost:3017/ as a Mobile and desktop applications redirect URI. Chilkat receives that loopback callback; a hosted web server is unnecessary. A public desktop application uses its client ID without a client secret. Choose common, consumers, organizations, or a tenant-specific authority consistently for the intended account types. Web and mobile applications need appropriate redirect handling. Authorization-code flow.

The example requests Files.ReadWrite and offline_access and saves a private qa_data/tokens/oneDrive.json cache. Narrow scopes for read-only applications. Use a distinct cache per app and account, refresh before expiration, and save rotated refresh tokens. The refresh example retains the previous refresh token if no replacement arrives. Revocation or an interaction requirement means signing in again. Protect the cache and use atomic storage with a single refresh writer in production.

Application credentials for Microsoft 365

The client-secret example loads private onedrive-app.json configuration and lets Http acquire and cache an application token from credential JSON assigned to AuthToken. Reuse that Http object. The certificate example instead loads onedrive-certificate-app.json, signs a short-lived PS256 client assertion, and explicitly requests a Graph token. Upload the public certificate to the Entra app and protect its private key. Certificate credential format.

Both use a tenant-specific authority and configured application permissions with administrator consent. Application tokens have no refresh token; acquire another access token when needed. Keep secrets and private keys in an application environment you control. Consent does not provision a user's OneDrive. Where appropriate, consider selected-resource permissions with explicit resource grants instead of broad tenant access.

Listing Drives, Folders and Files

List available drives with /me/drives, or resolve a SharePoint site by hostname and path and list its document libraries. Save the returned drive ID. The site lookup is for Microsoft 365 SharePoint and requires additional consent beyond the collection's default Files.ReadWrite grant. A site ID and a drive ID identify different resources.

Use IDs or a known path

Keep drive IDs, item IDs, permission IDs, and version IDs as opaque strings. Retain the drive context with every item ID. An item ID stays stable across renames and moves within the same drive; a name-based path changes. OneDrive does not use Outlook's ImmutableId preference.

For a known name hierarchy, address /drives/{driveId}/root:/Documents/sample.txt directly. For a known item, use /drives/{driveId}/items/{itemId}. Encode each name or ID segment with Http.UrlEncode; keep the route's colon and slash syntax intact. Do not encode a complete URL or a slash-separated path in one call. ID and path addressing.

Read the complete result set

Listing children returns only the immediate contents of a folder. Inspect file, folder, package, and remoteItem facets rather than assuming every item is a file. File MIME type is in file.mimeType. Sizes and quotas can exceed a 32-bit integer; the examples retain their decimal text. Use $select to limit the response to needed fields.

Follow each complete @odata.nextLink unchanged, even after an empty page. $top controls page size, not the total count. Examples validate continuation URLs and stop explicitly at their demonstration bounds. The resumable listing example saves a private checkpoint. A listing can change while pages are read; use delta synchronization when maintaining a local view. List folder children.

Search finds matching items within a drive, including descendants. Search results are not an exhaustive change log or a unique-name guarantee. Escape search text for the API's query syntax before URL encoding it. Retrieve the selected item's metadata when its current properties are needed.

Uploading

A simple content PUT creates or replaces a file in one request, with a documented maximum of 250 MB. The examples demonstrate a local file streamed from disk, UTF-8 text, and binary bytes from memory. Send raw content, not base64 JSON. Select the parent folder and filename deliberately; these examples request fail-on-conflict to avoid an unintended replacement. Save the DriveItem ID returned after success. Simple upload API.

For resumable transfers, create an upload session and send sequential byte ranges. The session example uses 10 MiB chunks, a multiple of the required 320 KiB, with a smaller final remainder. Requests must remain below the service's 60 MiB chunk limit. Intermediate responses are 202; completion returns 200 or 201. Follow the service's nextExpectedRanges rather than assuming it accepted every byte. Upload sessions.

The session receipt binds the target and file hash. Keep the local file unchanged, query the saved session after interruption, and reconcile expired or uncertain sessions before starting another upload. This particular example handles one open-ended remaining range and limits files to 999,999,999 bytes to keep arithmetic within int. That is a sample limit, not OneDrive's maximum. Larger implementations need exact offset arithmetic; IDs still remain strings.

The upload-session example now supports authenticated SharePoint URLs as well as legacy preauthenticated URLs. It selects credentials once per run and uses them for the status GET and every chunk PUT. A 401 or 403 preserves the receipt and stops; renew the appropriate token or resolve permissions, then resume the saved session rather than creating another upload. See transfer authentication below.

Downloading

The file-content endpoint retrieves bytes, while ordinary item metadata returns JSON. The download examples save a file to disk, load binary data into BinData, or decode known UTF-8 text into a StringBuilder. Choose text decoding only when the content's encoding is known; arbitrary files must remain binary. A webUrl or sharing URL is a viewing link, not a direct file-content response.

All three download examples accept HTTP 200 content directly from Graph or HTTP 302 with a returned service URL. Automatic redirects stay disabled so each service receives only its intended credentials. The disk example streams both response paths to a generated .part file and renames it only after a complete HTTP 200 transfer. Binary and text variants buffer the final response; the text example explicitly decodes the known file encoding. Empty files are valid, and truncated responses are not accepted even if their headers reported 200. Download file content.

Returned URLs and Microsoft's authentication transition. Microsoft has announced changes beginning April 1, 2027 that remove embedded authorization from affected OneDrive/SharePoint URLs. Depending on the operation and tenant behavior, callers may receive content directly, a Graph URL requiring a Graph token, or a SharePoint URL requiring a SharePoint-audience token. Do not assume every returned URL is anonymous, and never forward a Graph token to a different service. Microsoft's migration guidance.

Choose credentials for the returned URL

The three basic downloads and upload-session example use the Graph token only for graph.microsoft.com on HTTPS port 443. A separate SharePoint token is attached only when the returned hostname exactly matches a trusted configured host on port 443. A URL carrying a nonempty tempauth parameter is requested without a bearer token; other unmatched content hosts also receive no bearer token. Secondary redirects stop instead of forwarding credentials automatically. The version-download and copy-monitor examples also separate Graph and SharePoint token audiences.

Create the SharePoint token cache: use Obtain and Refresh a SharePoint Transfer Token in the Authentication examples. Run its authorize action once for PKCE browser sign-in, then its refresh action before the access token expires. It writes the cache below, including host and access_token, and keeps rotated refresh tokens and acquisition metadata.

Authenticated SharePoint transfers read the private file qa_data/tokens/oneDrive-sharepoint.json. Its minimal configuration is shown below. This is JSON configuration, independent of the example language selected above.

{
  "host": "your-tenant.sharepoint.com",
  "access_token": "SHAREPOINT_ACCESS_TOKEN"
}

Set host from trusted application configuration, not from an arbitrary response. Use the exact service hostname and an access token issued for the corresponding SharePoint resource. Keep this cache separate from oneDrive.json, which contains the Graph token. The transfer examples read the supplied token. Run the separate authorization/refresh example to obtain or renew it; transfer requests do not open a browser or refresh it automatically.

Obtain the token through Microsoft Entra for the SharePoint resource with appropriate SharePoint permissions. For delegated access, authorize the SharePoint scopes needed by the user and refresh that resource's token as needed; Graph consent alone is not a substitute. For app-only SharePoint REST access, use a certificate assertion and request the configured resource's https://your-tenant.sharepoint.com/.default scope. The Graph client-secret example does not establish certificate-based SharePoint access. SharePoint application authentication requirements.

Refresh credentials before expiry and reload them when resuming an interrupted transfer. On 401, check expiry and audience; on 403, check the actual grants and policy. Do not switch audiences based on an untrusted challenge or automatically restart an uncertain write. Tenant configuration determines the returned-URL behavior; see Microsoft's operation-by-operation compatibility table.

Managing Files and Folders

Create a folder under a chosen parent and select an explicit conflict policy. Rename or move an existing item with a minimal PATCH containing name and/or parentReference.id. A move must stay within the same drive. Moving to the root requires the root folder's actual ID in parentReference, not the literal root alias. Update and move an item.

The rename/move and delete examples read eTag first and send If-Match. A 412 means the item changed; read it again and reconcile. Deleting a folder also affects its contents. Ordinary deletion and permanent erasure are different operations; recovery depends on the service and retention policy. Review the target before running a modifying example.

Copying is asynchronous

A copy request returns 202 and a monitor URL. The example saves an operation receipt, then polls once on each subsequent run. Schedule checks with backoff and Retry-After. Completed or failed receipts prevent automatic resubmission. A lost response leaves a pending operation that must be reconciled; repeating POST could create another copy.

The copied item has a new ID and inherits destination permissions. Source metadata and version history are not all copied by default. The sample copies current content. For all versions, Microsoft documents includeAllVersionHistory=true and a known issue when name is supplied at the same time; copy first, then rename for that workflow. Folder copies include descendants, have a 30,000-item limit, and app-only cross-geo copying is unsupported. Copy behavior and limits.

Sharing

A sharing link, a recipient grant, and a driveItem ID serve different purposes. The link example creates a view link with organization scope for OneDrive for Business or SharePoint. Anonymous links deliberately allow anyone holding the link and may be disabled by policy. Organization scope is not for personal OneDrive. A view link does not remove other permissions that allow editing. Retain the returned permission ID for later management. Create a sharing link.

The recipient example grants read access to named recipients, requires sign-in, and preserves inherited permissions. It defaults to sendInvitation=false, which still changes access but sends no invitation email. Setting it to true sends invitations. Inspect each result, including a 207 partial response; notification failure can occur after access was granted. New guests cannot be invited using app-only access. Share with recipients.

The permissions example defaults to inspection only. Set a selected permission ID to revoke that direct grant. Owners and nonowners can see different subsets, and inheritedFrom is not consistently exposed by every service. Missing inheritance metadata is not proof that a grant can be removed. The server enforces the restriction on deleting inherited permissions, and other grants can still provide access. Delete a permission.

To resolve an existing sharing URL, encode its UTF-8 bytes as unpadded base64url and prefix u!. The example requests /shares/{encodedUrl}/driveItem and returns the owning drive and item IDs, including remoteItem handling. Its redeemSharingLinkIfNecessary preference may redeem access for that request; it does not guarantee lasting access. Authentication and sharing policy still apply. Keep both the link and its reversible encoding private. Resolve shared content.

Versions

List a file's available versions and choose one explicitly. A version ID such as 1.0 is a string, not a decimal number to sort or increment. History availability depends on the service and retention settings. The version-download example defaults to listing only; setting versionId downloads that older version without changing the current file. The version-content endpoint does not download the current version; use the ordinary item-content endpoint instead. Download previous version content.

Restoring is a separate write: the selected content becomes a new current version while existing versions are preserved. The restore example expects 204 and no JSON response. Coordinate with other writers and inspect history before retrying an uncertain restore. Restore a version.

Synchronization

Use /drives/{driveId}/root/delta to maintain a local metadata index. Follow nextLink through the initial baseline until deltaLink is returned, then save that exact URL for the next round. Empty pages can still have continuation links. Keep separate state for each account, drive, and field selection. Drive delta queries.

The example applies records by string ID, lets later occurrences win, preserves omitted fields, and retains deletion tombstones. OneDrive uses the deleted facet. Parent IDs help track moves without depending on a path. Only remove a deleted folder locally after the full round and when it is empty.

Data and its cursor are saved together, with a matching backup and an explicit roundComplete marker. The 100-page execution bound preserves progress for the next run. Use atomic durable storage and one writer in production. A 410 requires reconciliation and a fresh baseline. This example maintains metadata; a full file synchronizer must also transfer changed content and resolve local edits. No webhook receiver is needed.

Handling failures: renew authorization after 401; check consent, actual access, and policy for 403; honor Retry-After for 429. Reconcile uncertain creates, uploads, copies, grants, and restores before retrying. Keep token caches, temporary service URLs, synchronization state, file contents, and detailed diagnostics private.