Skip to content

Instantly share code, notes, and snippets.

@petergs
Created April 25, 2025 20:51
Show Gist options
  • Select an option

  • Save petergs/8b39555c241c2621a2e68ac9e55ca57e to your computer and use it in GitHub Desktop.

Select an option

Save petergs/8b39555c241c2621a2e68ac9e55ca57e to your computer and use it in GitHub Desktop.
onedrive-upload.py
import requests
import json
import pathlib
import sys
def upload(access_token: str, file_path: str, file_name: str):
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'text/plain'
}
with open(file_path, 'rb') as file:
file_content = file.read()
upload_url = f'https://graph.microsoft.com/v1.0/me/drive/root:/{file_name}:/content'
response = requests.put(upload_url, headers=headers, data=file_content)
if response.status_code == 201:
print('File uploaded successfully!')
print(json.dumps(response.json(), indent=2))
else:
print(f'Error uploading file: {response.status_code}')
if __name__ == "__main__":
if sys.stdin is not None:
access_token = sys.stdin.readline().rstrip()
else:
print("Error: Expecting an access_token supplied from stdin")
sys.exit(1)
home = pathlib.Path.home()
file_path = f'{home}/example.txt'
file_name = 'example.txt'
upload(access_token, file_path, file_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment