Created
March 27, 2025 21:39
-
-
Save mirontoli/a995cced0aed7d63f3ef00e28bb19df7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import urllib | |
graph_base_url = 'https://graph.microsoft.com/v1.0' | |
sharepoint_domain = 'takana17.sharepoint.com' | |
directory = 'DOWNLOAD-PATH' | |
bearer_token = '<BEARER-TOKEN-HERE>' | |
doc_abs_url = 'FILE-LINK' | |
doc_abs_url_clean = doc_abs_url.split('?')[0] | |
stripped_url = doc_abs_url_clean.split('/sites/')[1] | |
site_slug_split = stripped_url.split('/',2) | |
site_slug = site_slug_split[0] | |
drive_path = site_slug_split[1] | |
item_path = site_slug_split[2] | |
file_name = item_path.split('/')[-1] | |
file_name_unquoted = urllib.parse.unquote(file_name) | |
graph_url_site_id = f'{graph_base_url}/sites/{sharepoint_domain}:/sites/{site_slug}?select=id' | |
response = requests.get(graph_url_site_id, headers={'Authorization': f'Bearer {bearer_token}'}) | |
site_id = response.json().get('id') | |
site_id_short = site_id.split(',')[1] | |
graph_url_drives = f'{graph_base_url}/sites/{site_id_short}/drives?select=id,webUrl' | |
response = requests.get(graph_url_drives, headers={'Authorization': f'Bearer {bearer_token}'}) | |
drives = response.json().get('value') | |
drive_info = next((item for item in drives if item["webUrl"].endswith(drive_path)), None) | |
drive_id = drive_info.get('id') | |
graph_url_item = f'{graph_base_url}/drives/{drive_id}/root:/{item_path}' | |
response_item = requests.get(graph_url_item, headers={'Authorization': f'Bearer {bearer_token}'}) | |
item_download_link = response_item.json().get('@microsoft.graph.downloadUrl') | |
local_file_path = f'{directory}{file_name_unquoted}' | |
response_download = requests.get(item_download_link) | |
with open(local_file_path, "wb") as file: | |
file.write(response_download.content) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment