October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
curl

How to Download Files from SharePoint with Microsoft Graph API

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To download a SharePoint file with Microsoft Graph, address the file as a driveItem, call its /content endpoint with a bearer token, and follow the temporary URL returned in the redirect. A typical request is GET /sites/{site-id}/drive/items/{item-id}/content. Microsoft Graph documentation states that “Only driveItem objects with the file property can be downloaded.” Folders and other non-file drive items are not downloadable through this operation.

This guide shows how to find the item, select least-privileged permissions, handle redirects and browser CORS, resume large transfers, and diagnose common failures.

How the download flow works

  1. Resolve the SharePoint site, document library (drive), and file’s driveItem ID, either by metadata lookup or a supported path.
  2. Acquire a Microsoft Graph access token appropriate to your access model.
  3. Request the item’s /content endpoint.
  4. Follow the 302 Found Location header to a preauthenticated download URL, or read the equivalent @microsoft.graph.downloadUrl property from metadata.
  5. Stream the response to disk. The preauthenticated URL normally expires within minutes, so do not store it as a permanent link.

Most HTTP clients follow the redirect automatically. If your client does not, make a second request to the URL in Location. The second request does not need an Authorization header.

Choose an address for the file

You can use the route that matches the information your application already has.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Microsoft Surface Pro Keyboard with Pen Storage, Compatible with Copilot+ (11th Edition), Surface 9 and 8, Alcantara Material, Black
  • Instant Copilot. Unlock new possibilities with the dedicated Copilot key, which gives you instant access to experiences that can enhance your productivity¹.
  • Enhance your experience With the new microphone mute key and snipping key
  • Full keyboard experience. Features a full mechanical keyset, backlit keys, and a large trackpad for precise navigation and control. Optimal key spacing allows fast, fluid typing.
  • Slim and compact Performs like a traditional, full-size keyboard.
  • Clicks in place instantly Use in combination with the Surface Pro (11th Edition), Pro 9 and Pro 8* kickstand for a perfect laptop experience anywhere.
Addressing style Example shape When to use it
Drive and item ID /drives/{drive-id}/items/{item-id}/content You already know the document library and stable item ID.
Site and item ID /sites/{site-id}/drive/items/{item-id}/content The file belongs to the site’s default document library.
Signed-in user’s drive /me/drive/items/{item-id}/content Delegated access to the current user’s OneDrive or SharePoint context.
Path /me/drive/root:/{item-path}:/content You have a path but not an item ID; URL-encode spaces and reserved characters.
Shared item Shared-item route The file was shared with the user rather than discovered through a site drive.

For reliable automation, resolve a path once and retain the returned item ID. Names and folders can change; an item ID is the better handle for subsequent downloads.

Resolve metadata before downloading

Metadata requests can retrieve a driveItem by ID or filesystem path. Ask for the id, name, size, file, and @microsoft.graph.downloadUrl fields when you need to inspect the item or implement browser JavaScript. Check that the response contains a file property before attempting a download.

Permissions and tokens

Use the narrowest permission that matches your application.

Access model Least-privileged permission documented for the content endpoint Notes
Delegated work or school account Files.Read The signed-in user must be able to read the file.
Application-only access Files.Read.All Runs without a user; tenant administrators generally grant consent.
SharePoint Embedded FileStorageContainer.Selected plus the required container-type permission Container permissions are additional requirements, not substitutes for ordinary Graph permissions.

Delegated access is usually the safer default for an interactive tool because Graph evaluates the user’s SharePoint access. Application permissions are useful for background jobs, but scope them carefully and protect the client secret or certificate. Personal-account permission variants and the complete permission matrix depend on the route and account type; verify the current Microsoft Graph v1.0 permission table before requesting consent.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

cURL: download by site and item ID

Replace the placeholders with a real token, site ID, and file item ID. The -L option follows Graph’s redirect and writes the bytes to a file.

Rank #2
Sale
Microsoft Type Cover for Surface Pro - Black (Renewed)
  • Surface Pro Type Cover has a new improved design with slightly spread out keys for a more familiar and efficient typing experience that feels like a traditional laptop
  • The two button trackpad is now larger for precision control and navigation
  • The keyboard is sturdy with enhanced magnetic stability along the fold so you can adjust it to the right angle and work on your lap, on the plane, or at your desk. Since it's designed just for Surface, Surface Pro Type Cover easily clicks into place to go from tablet to laptop instantly
  • Protects and shields the screen from bumps and scratches
curl -L 
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" 
  "https://graph.microsoft.com/v1.0/sites/SITE_ID/drive/items/ITEM_ID/content" 
  -o report.xlsx

For a path-based request, encode the path as required by the Graph URL syntax:

curl -L 
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" 
  "https://graph.microsoft.com/v1.0/me/drive/root:/Shared%20Documents/report.xlsx:/content" 
  -o report.xlsx

Use -D headers.txt when troubleshooting. You should see a 302 response and a Location header before the final file response.

Python: stream the response safely

This example disables automatic redirects so you can see the handoff, then streams the preauthenticated URL to disk. Streaming avoids loading a large file into memory.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import sys
import requests

GRAPH = "https://graph.microsoft.com/v1.0"
token = "YOUR_ACCESS_TOKEN"
site_id = "SITE_ID"
item_id = "ITEM_ID"
out_path = "report.xlsx"

r = requests.get(
    f"{GRAPH}/sites/{site_id}/drive/items/{item_id}/content",
    headers={"Authorization": f"Bearer {token}"},
    allow_redirects=False,
    timeout=30,
)

if r.status_code not in (302, 303, 307, 308):
    r.raise_for_status()
download_url = r.headers.get("Location")
if not download_url:
    raise RuntimeError("Graph returned a redirect without Location")

with requests.get(download_url, stream=True, timeout=90) as file_response:
    file_response.raise_for_status()
    with open(out_path, "wb") as output:
        for chunk in file_response.iter_content(chunk_size=1024 * 1024):
            if chunk:
                output.write(chunk)

print(f"Saved {out_path}")

For production code, add retry handling for transient 5xx responses, validate the expected content type and size when known, and write to a temporary filename before renaming it so an interrupted transfer is not mistaken for a complete file.

Node.js: follow the redirect explicitly

Node’s built-in fetch can follow redirects, but explicit handling lets you inspect Graph errors and refresh an expired preauthenticated URL.

Rank #3
Sale
Microsoft Surface Pro Keyboard for Surface Pro Copilot+ (11th Edition), Pro 9 and 8 with Pen Storage, Alcantara Material, Platinum
  • Instant Copilot. Unlock new possibilities with the dedicated Copilot key, which gives you instant access to experiences that can enhance your productivity¹.
  • Enhance your experience With the new microphone mute key and snipping key
  • Full keyboard experience. Features a full mechanical keyset, backlit keys, and a large trackpad for precise navigation and control. Optimal key spacing allows fast, fluid typing.
  • Slim and compact Performs like a traditional, full-size keyboard.
  • Clicks in place instantly Use in combination with the Surface Pro (11th Edition), Pro 9 and Pro 8* kickstand for a perfect laptop experience anywhere.
import { createWriteStream } from "node:fs";
import { once } from "node:events";

const token = "YOUR_ACCESS_TOKEN";
const siteId = "SITE_ID";
const itemId = "ITEM_ID";
const graphUrl = `https://graph.microsoft.com/v1.0/sites/${siteId}/drive/items/${itemId}/content`;

const first = await fetch(graphUrl, {
  headers: { Authorization: `Bearer ${token}` },
  redirect: "manual"
});
if (![302, 303, 307, 308].includes(first.status)) {
  throw new Error(`Graph returned ${first.status}: ${await first.text()}`);
}
const location = first.headers.get("location");
if (!location) throw new Error("Missing redirect location");

const file = await fetch(location);
if (!file.ok || !file.body) throw new Error(`Download failed: ${file.status}`);
const output = createWriteStream("report.xlsx");
for await (const chunk of file.body) output.write(chunk);
output.end();
await once(output, "finish");

Browser JavaScript and CORS

A browser request that adds an Authorization header can trigger a CORS preflight. Microsoft’s recommended path is to request metadata from Graph, obtain @microsoft.graph.downloadUrl, and then request that URL directly. The preauthenticated URL is designed for the file request and does not require the bearer token.

const metadata = await fetch(
  `https://graph.microsoft.com/v1.0/sites/${siteId}/drive/items/${itemId}?$select=id,name,size,file,@microsoft.graph.downloadUrl`,
  { headers: { Authorization: `Bearer ${accessToken}` } }
);
if (!metadata.ok) throw new Error(await metadata.text());
const item = await metadata.json();
if (!item.file || !item["@microsoft.graph.downloadUrl"]) {
  throw new Error("The item is not a downloadable file");
}
const fileResponse = await fetch(item["@microsoft.graph.downloadUrl"]);
const blob = await fileResponse.blob();

For sensitive files, keep token acquisition and metadata calls on your server when possible. Never expose application credentials in browser code.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Partial downloads and resume support

Send a byte-range header to the preauthenticated download URL, not to the Graph /content endpoint:

curl -L 
  -H "Range: bytes=0-1048575" 
  "PASTE_THE_PREAUTHENTICATED_URL_HERE" 
  -o first-megabyte.bin

A supported range returns 206 Partial Content and normally includes Content-Range. If Graph or the storage service cannot generate the requested range, it may ignore Range and return the complete file with 200 OK. Your downloader must check the status and avoid appending a full response to a partial file. If a preauthenticated URL expires during a retry, request a new metadata URL or repeat the /content call.

Failure modes and fixes

401 Unauthorized

The token is missing, expired, issued for the wrong tenant, or lacks the required audience. Acquire a fresh Microsoft Graph token and send it as Authorization: Bearer ... only on the Graph request.

Rank #4
Sale
Microsoft Surface Pro Keyboard for Surface Pro 12" Device, Keyboard Only, Alcantara Material, Slate
  • [Expand Your Possibilities] – Instantly turn Surface Pro[1] into a full laptop with the Surface Pro Keyboard, giving you more ways to work, create, and stay productive anywhere.
  • [Comfortable, Precise Typing] – Designed for Surface Pro 12”, this premium keyboard offers a responsive, laptop-like typing experience so you can work comfortably on the go.
  • [Flexible Hinge for Any Angle] – The new dynamic hinge flexes a full 360°, letting you type, draw, or stream from virtually any position.
  • [Stable on Lap or Desk] – A web-style internal structure adds support and balance, keeping your keyboard steady whether you're at a desk or on your lap.
  • [Premium Feel, Built-in Convenience] – Includes a backlit keyboard and large precision touchpad for effortless typing, navigation, and control — day or night.

403 Forbidden

The app or user lacks access, admin consent is missing for an application permission, or a SharePoint Embedded container permission was omitted. Confirm the signed-in user can open the file and reduce or correct the permission configuration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

404 Not Found

The site, drive, item ID, or path is wrong, or the caller cannot discover the resource. Resolve metadata first and verify the exact drive and item IDs. A path with spaces or reserved characters must be encoded correctly.

The response is 200 but the file is not usable

You may have saved an error payload as a file, followed an unexpected proxy response, or appended a complete response to a partial file. Check status, Content-Type, and response size before committing the output.

Browser CORS errors

Do not fetch /content from the browser with an Authorization header and assume the redirect will be permitted. Use the metadata request to obtain @microsoft.graph.downloadUrl, then fetch that URL directly, or proxy the download through your server.

Range requests return the whole file

Ranges are sent to the preauthenticated URL. Even then, the service may return 200 when it cannot produce the requested range. Detect that case and restart or discard the response rather than treating it as a partial segment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
WirelessFinest Microsoft Surface Pro Keyboard 3/4/5/6/7/7+ Bluetooth
  • EXCLUSIVE sophisticated look design for Microsoft Surface Pro 7 Plus (2021) / Surface Pro 7 (2019) / Surface Pro 6 (2018) / Surface Pro 5th Gen (2017) / Surface Pro 4 / Surface Pro 3 12.3 inch tablet. ** PLEASE MAKE SURE YOUR SURFACE PRO VERSION BEFORE MAKE PURCHASE !! NOT fit for Pro 2, not fit Pro 8, not fit Pro 9 **
  • RESPONSIVE TRACKPAD - Built-in with a responsive trackpad, scrolling & multi-touch gesture, conveniently using like a mouse, navigate and control your tablet precisely, gives you the touch screen experience, without having to take your hands off the keyboard.
  • MAGNETIC removable attach or detach, The keyboard is sturdy with enhanced magnetic stability along the fold so you can adjust it to the right angle and work on your lap, on the plane, or at your desk. When you don't need to use the keyboard, you can always detach it from the surface pro and easily switch between surface pro tablet and laptop.(NOT CHARGING VIA MAGNET ATTACH, CHARGE WITH USB CABLE INCLUDED).
  • SLIM and LIGHTWEIGHT - Compact size and light weight allows easily be carried and packed in backpack, message bag or case. Comfortable, quiet typing with sturdy ergonomic design could make your hands feel more comfortable when typing, reducing the burden of your hands. Auto-sleep for scientific power saving and extended battery life.
  • 7-COLOR BACKLIT - Special 7 colors elegant LED backlights. Ideal for typing freely even in low light conditions or at night.

Redirect URL stops working

Preauthenticated URLs are temporary and can expire within minutes. Never persist them as durable sharing links; obtain a fresh one for each job or retry.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Reliability, performance, and security checklist

  • Resolve and cache item IDs, but request a fresh download URL for each transfer.
  • Stream large files and use a temporary output followed by an atomic rename.
  • Set separate timeouts for the Graph request and the file transfer.
  • Retry only transient network and server failures; reacquire the redirect URL after an expiration.
  • For resumable transfers, verify 206, Content-Range, and the byte count.
  • Log Graph status codes and request identifiers, but never log access tokens or preauthenticated URLs.
  • Keep delegated permissions or application scopes as narrow as the access model permits.

Or skip the browser setup

If your goal is to create clean images or PDFs of web pages rather than download SharePoint file bytes, ScreenshotNeo provides a one-call screenshot API and an MCP server for AI agents. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and each response reports the page verdict and billing status.

Use the ScreenshotNeo API documentation for all options. A basic request is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The service supports full-page captures, CSS-element targeting, device presets, custom headers and cookies, waiting conditions, PDFs, HTML/CSS rendering, signed links, asynchronous webhooks, bulk capture, and an MCP server with take_screenshot, get_page_info, and capture_pdf. The Free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can I download a SharePoint folder with the content endpoint?

No. The content operation downloads a driveItem whose response has a file property. Enumerate a folder’s children and download each file separately.

Is the @microsoft.graph.downloadUrl a permanent sharing link?

No. It is a temporary preauthenticated URL intended for prompt use and may expire within minutes.

Should I use delegated or application permissions?

Use delegated access when a signed-in user is present and application access for unattended jobs, always selecting the least-privileged permission that meets the requirement.

The Bottom Line

Find the file’s driveItem ID, call its /content endpoint with an appropriately scoped Graph token, follow the temporary redirect, and treat browser, range, and expiry behavior explicitly. That pattern works across the documented SharePoint and OneDrive route families without exposing durable download URLs.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quick Recap

SaleBestseller No. 1
Microsoft Surface Pro Keyboard with Pen Storage, Compatible with Copilot+ (11th Edition), Surface 9 and 8, Alcantara Material, Black
Microsoft Surface Pro Keyboard with Pen Storage, Compatible with Copilot+ (11th Edition), Surface 9 and 8, Alcantara Material, Black
Enhance your experience With the new microphone mute key and snipping key; Slim and compact Performs like a traditional, full-size keyboard.
$128.99
SaleBestseller No. 2
Microsoft Type Cover for Surface Pro - Black (Renewed)
Microsoft Type Cover for Surface Pro - Black (Renewed)
The two button trackpad is now larger for precision control and navigation; Protects and shields the screen from bumps and scratches
$69.88
SaleBestseller No. 3
Microsoft Surface Pro Keyboard for Surface Pro Copilot+ (11th Edition), Pro 9 and 8 with Pen Storage, Alcantara Material, Platinum
Microsoft Surface Pro Keyboard for Surface Pro Copilot+ (11th Edition), Pro 9 and 8 with Pen Storage, Alcantara Material, Platinum
Enhance your experience With the new microphone mute key and snipping key; Slim and compact Performs like a traditional, full-size keyboard.
$128.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.