How to Automate SharePoint File Upload, Search, and Download

 How to Automate SharePoint File Upload, Search, and Download

Summary

  • SharePoint file automation depends on resolving three IDs correctly: site_id, drive_id, and parentItemId; most failures originate in resolution or permissions rather than the upload API itself.
  • Use single PUT calls only for files under 4 MB, and upload sessions with sequential byte ranges for larger or reliability-critical files.
  • App-only automation requires tenant admin consent and Sites.ReadWrite.All; sensitivity-labelled files require delegated authentication and cannot be replaced with app-only access.
  • Validate chunking locally, set @microsoft.graph.conflictBehavior explicitly, and test the full sequence in one library before scaling to dynamic routing across sites.
  • For regulated teams that need to automate SharePoint document routing without building every Graph API workflow manually, Jinba Flow lets teams describe workflows in plain language and deploy them on-premise.

Uploading thousands of PDF files to specific SharePoint subfolders manually is a structural problem. Without automation, files land in the wrong library, searches return nothing useful, and downloads require navigating multiple menus; each failure compounds the cost of an unstructured approach.

A complete SharePoint file automation workflow depends on three Graph API capabilities: uploading files reliably, discovering where files live, and retrieving them programmatically. Each capability has prerequisites that must be resolved before any automation runs.

Understand the drive model before writing any automation

Every file in Microsoft 365 lives inside a drive. A personal drive is OneDrive (/me/drive). A shared drive is backed by a SharePoint document library (/sites/{id}/drive). The confusion between the two is common, but the Graph API treats them identically once a drive_id is available.

A SharePoint site's default document library is its drive. Sites can have multiple document libraries, each with its own drive_id. Automations that target the wrong drive succeed without error while placing files in unintended locations.

Resolve your site_id and drive_id first

Every API call requires two identifiers: the site and the drive within it.

To find a site's ID, call:

GET /sites/{hostname}:/sites/{site-path}

This returns a compound site ID in the format "hostname,siteGuid,webGuid". All three segments are required. Dropping any part of this ID is a common source of errors when building automation.

To retrieve the default document library's drive_id:

GET /sites/{site-id}/drive

To list all document libraries under a site and match a human-readable name to its drive_id:

GET /sites/{site-id}/drives

If this call returns an empty list, missing permission or absent admin consent is the usual cause; an incorrect endpoint is unlikely.

Permissions and tenant admin consent

Application permissions (app-only authentication) run with a service principal identity and operate tenant-wide. Only a Global Administrator or Privileged Role Administrator can grant consent for application permissions. This is a prerequisite for any unattended automation, and it cannot be delegated to a lower-privileged role.

The minimum permissions required:

  • Delegated (user signs in): Files.ReadWrite
  • Application (app-only): Sites.ReadWrite.All

Delegated permissions are bounded by the signed-in user's own access. Application permissions such as Files.ReadWrite.All or Sites.ReadWrite.All can read and write any file across the organisation. Microsoft recommends delegated permissions where possible for this reason. For security-conscious administrators, framing the request around least privilege and scoping to specific sites where the API supports it strengthens the case for consent.

Automate file uploads

Files under 4 MB

For small files, a single PUT request to the following endpoint is sufficient:

PUT /drives/{drive-id}/items/{parent-id}:/{filename}:/content

This method is simple and not resumable; a dropped connection requires restarting the upload.

Chunked uploads for files above 4 MB

For larger files, and for any upload where reliability matters, the Microsoft Graph upload session is the correct method. It is a two-step process.

Step 1: Create an upload session

POST /drives/{driveId}/items/{parentItemId}:/{fileName}:/createUploadSession

The {parentItemId} value is the item ID of the destination folder, not a path string. The response contains an uploadUrl and an expirationDateTime.

Step 2: Upload byte ranges sequentially

Send the file in chunks using PUT requests against the uploadUrl. Each successful chunk extends the session's expirationDateTime. If the connection drops, the session status can be queried to find the last acknowledged byte, and the upload can resume from that point.

Microsoft's canonical sample for this pattern uses PowerShell and the driveItem:createUploadSession endpoint. It is a reliable reference for implementation.

Handling conflicts

Control what happens when a file with the same name already exists by setting @microsoft.graph.conflictBehavior in the session creation request body:

  • fail: returns an error (default)
  • replace: overwrites the existing file
  • rename: creates a new file with a disambiguated name

Compliance constraint

Files protected with sensitivity labels cannot be replaced using app-only authentication. Attempting to do so returns an error. Regulated environments that use sensitivity labels must use delegated authentication for any operation that touches protected files.

File integrity

A consistent pattern in large-file automation work: when files arrive larger than their original size or fail to open after upload, the fault is in the chunking or reassembly logic rather than SharePoint itself. Test the chunking and reassembly steps against a local target first. Once the output is confirmed clean, point the same logic at SharePoint. This isolates the problem and avoids mistaking an implementation error for a platform issue.

Automate file discovery and search

List all sites and libraries

Start tenant-wide discovery at the root site:

GET /sites/root

Walk sub-sites from there:

GET /sites/{site-id}/sites

Then enumerate document libraries within each site:

GET /sites/{site-id}/drives

This sequence maps the full structure of a SharePoint tenant, which is useful for automations that need to operate across many libraries.

List documents in a specific library

GET /sites/{site-id}/lists/{list-id}/items

This returns all items in a document library. For libraries with high item counts, apply $filter and $select parameters to reduce response size and avoid timeouts.

Search across the tenant

The Microsoft Search API resolves the problem of locating a file when its exact location is unknown:

POST /search/query

Request body:

{
"requests": [
{
"entityTypes": ["driveItem"],
"query": {
"queryString": "search-term"
}
}
]
}

This returns matching driveItem results from across the entire tenant. The response includes driveId and itemId values that can be passed directly into a download or update call.

Automate file downloads

To retrieve file content, use the content endpoint on a known driveItem:

GET /drives/{drive-id}/items/{item-id}/content

This returns the raw file bytes. For Office files, the Graph API supports on-the-fly format conversion. To download a DOCX as a PDF without a separate conversion step:

GET /drives/{drive-id}/items/{item-id}/content?format=pdf

Supported conversion formats are documented in the SharePoint resources overview. The conversion happens server-side, and the response is the converted file's binary content.

A practical end-to-end workflow

The following sequence puts the individual API calls into a complete flow. The scenario: a new form submission includes a file attachment, and the file must land in a designated SharePoint folder with its URL logged for downstream use.

  1. Trigger on a new form submission.
  2. Retrieve the attachment content and original filename from the submission details.
  3. Resolve the target location by calling GET /sites/{hostname}:/sites/{site-path} for the site_id, then GET /sites/{site-id}/drives to match the target library name to its drive_id, then GET /drives/{drive-id}/items/{folder-path} to retrieve the destination folder's parentItemId.
  4. Create an upload session with POST /drives/{driveId}/items/{parentItemId}:/{fileName}:/createUploadSession. Set @microsoft.graph.conflictBehavior to rename to prevent failures if the file already exists.
  5. Upload the file by sending the content to the uploadUrl returned in step 4. For Power Automate, the built-in "Create upload session" action handles byte-range chunking automatically.
  6. Capture the webUrl from the completed upload response for logging or inclusion in a notification.

Steps 3 through 5 can be hardcoded once IDs are resolved, or kept dynamic if the destination varies by submission type.

What to verify before scaling

Before running this pattern against a production environment at scale, confirm:

  • Tenant admin consent has been granted for all required permissions.
  • The drive_id values in use match the intended document libraries, not the default drive.
  • Sensitivity labels are accounted for. Libraries with labelled content require delegated authentication.
  • Chunking logic has been validated locally, not just in the target SharePoint environment.
  • Conflict behavior is explicitly set. Relying on the default fail behavior in an automated flow will cause the workflow to stop on duplicate filenames.

SharePoint file automation at scale is largely a resolution and permissions problem. Once site_id, drive_id, and parentItemId values are confirmed and admin consent is in place, the upload, search, and download operations are straightforward API calls. Start with a single library and a fixed destination, verify the full sequence end to end, then extend the pattern to cover additional sites and dynamic routing.

Frequently asked questions: SharePoint file automation with Microsoft Graph

How do I upload a large file to SharePoint using the Microsoft Graph API?

Create an upload session, then send the file in sequential byte ranges. Call POST /drives/{driveId}/items/{parentItemId}:/{fileName}:/createUploadSession to get an uploadUrl and expirationDateTime, then PUT each chunk to that URL until the file is complete. Each acknowledged chunk extends the session's expiration, and if the connection drops the session status can be queried to find the last received byte and resume from that point rather than restarting. Files under 4 MB can be uploaded with a single PUT to /content, but the upload session is the correct choice for anything larger or any transfer where reliability matters.

What permissions do I need to automate SharePoint uploads with Microsoft Graph?

It depends on the authentication model: Files.ReadWrite for delegated (a user signs in) access, and Sites.ReadWrite.All for app-only (application) access. Both require tenant admin consent before any unattended automation will run, and for application permissions that consent can only be granted by a Global Administrator or Privileged Role Administrator; it cannot be delegated to a lower-privileged role. Because application permissions act tenant-wide and can read or write any file in the organisation, Microsoft recommends delegated permissions wherever the workflow allows it.

How do I find the drive ID of a SharePoint document library?

Call GET /sites/{site-id}/drive to get the default library, or GET /sites/{site-id}/drives to list every document library in the site alongside its drive_id. Match the human-readable library name to the required ID and store it, because drive_id values are what every upload, search, and download call ultimately depends on. If the list returns empty, missing permission or absent admin consent is the usual cause rather than an incorrect endpoint.

What is the difference between /me/drive and /sites/{id}/drive in Microsoft Graph?

They are both drives and Graph treats them identically once a drive_id is available. /me/drive addresses a personal OneDrive, while /sites/{id}/drive addresses a SharePoint document library backed by a site. The distinction matters only during ID resolution; the same upload session, search, and download calls work unchanged against either one.

How do I overwrite a file that already exists in SharePoint?

Set @microsoft.graph.conflictBehavior in the upload session request body. The default is fail, which returns an error and stops an automated flow when a duplicate filename appears; replace overwrites the existing file, and rename creates a new file with a disambiguated name. For most unattended workflows, rename is the safer default because it preserves the original file while letting the new upload complete.

Why does a file with a sensitivity label fail to upload using app-only authentication?

Files protected by sensitivity labels cannot be replaced using app-only authentication, and the request returns an error. This is a compliance constraint rather than a permissions bug, so raising permission scopes will not resolve it. Regulated environments that apply sensitivity labels must use delegated authentication for any operation that touches a protected file.

How do I search for a file across all SharePoint sites with Microsoft Graph?

Use the Microsoft Search API: POST /search/query with entityTypes set to ["driveItem"] and the search term in queryString. The response returns matching items from across the entire tenant, including the driveId and itemId values required for a download or update call. This is the right approach whenever the site or library holding the file is unknown, and it removes the need to enumerate sites and libraries one by one.

Can I convert a Word document to PDF with Microsoft Graph?

Yes. Append ?format=pdf to the content endpoint (GET /drives/{drive-id}/items/{item-id}/content?format=pdf), and the server returns the converted file's binary content. The conversion happens server-side, so there is no separate conversion step or third-party library to maintain. Other formats are also supported, and the full list is documented in the SharePoint resources overview.

How do I stop listing a large SharePoint library from timing out?

Apply $filter and $select parameters to GET /sites/{site-id}/lists/{list-id}/items to reduce the response payload and page through results instead of requesting everything at once. Large item counts, rather than API instability, are the usual cause of timeouts. Restricting the fields returned also reduces processing overhead in the automation that consumes the results.

Can I automate SharePoint uploads with Power Automate instead of writing code?

Yes. Power Automate's built-in "Create upload session" action handles byte-range chunking automatically, so a low-code flow can perform the same upload sequence as a custom script. The prerequisites do not change: admin consent must be in place, site_id and drive_id must resolve to the correct library, and conflict behavior must be set explicitly. Custom code becomes worthwhile when logic is required that a connector cannot express, such as validating chunks locally before sending.

Build your way.

The AI layer for your entire organization.

Get Started