|
1 | 1 | # Access_OneDrive_via_Graph_API_Python
|
2 | 2 | Upload, download, rename your files and many more to your OneDrive both personal and business accounts using Microsoft Graph API (Python code).
|
| 3 | + |
| 4 | +```python |
| 5 | +# Program: Accessing OneDrive via Graph API |
| 6 | +# Author: Pranab Das (Twitter: @Pranab_Das) |
| 7 | +# Version: 20191104 |
| 8 | +``` |
| 9 | + |
| 10 | + |
| 11 | +```python |
| 12 | +# requirements |
| 13 | +import requests |
| 14 | +import json |
| 15 | +import urllib |
| 16 | +import os |
| 17 | +``` |
| 18 | + |
| 19 | +### Get Access token |
| 20 | + |
| 21 | + |
| 22 | +```python |
| 23 | +URL = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize' |
| 24 | +client_id = "362422eb-d9d6-4245-9eca-2be5cf256450" |
| 25 | +permissions = ['files.readwrite'] |
| 26 | +response_type = 'token' |
| 27 | +redirect_uri = 'http://localhost:8080/' |
| 28 | +scope = '' |
| 29 | +for items in range(len(permissions)): |
| 30 | + scope = scope + permissions[items] |
| 31 | + if items < len(permissions)-1: |
| 32 | + scope = scope + '+' |
| 33 | + |
| 34 | +print('Click over this link ' +URL + '?client_id=' + client_id + '&scope=' + scope + '&response_type=' + response_type+\ |
| 35 | + '&redirect_uri=' + urllib.parse.quote(redirect_uri)) |
| 36 | +print('Sign in to your account, copy the whole redirected URL.') |
| 37 | +code = input("Paste the URL here :") |
| 38 | +token = code[(code.find('access_token') + len('access_token') + 1) : (code.find('&token_type'))] |
| 39 | +URL = 'https://graph.microsoft.com/v1.0/' |
| 40 | +HEADERS = {'Authorization': 'Bearer ' + token} |
| 41 | +response = requests.get(URL + 'me/drive/', headers = HEADERS) |
| 42 | +if (response.status_code == 200): |
| 43 | + response = json.loads(response.text) |
| 44 | + print('Connected to the OneDrive of', response['owner']['user']['displayName']+' (',response['driveType']+' ).', \ |
| 45 | + '\nConnection valid for one hour. Reauthenticate if required.') |
| 46 | +elif (response.status_code == 401): |
| 47 | + response = json.loads(response.text) |
| 48 | + print('API Error! : ', response['error']['code'],\ |
| 49 | + '\nSee response for more details.') |
| 50 | +else: |
| 51 | + response = json.loads(response.text) |
| 52 | + print('Unknown error! See response for more details.') |
| 53 | +``` |
| 54 | + |
| 55 | + Click over this link https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=362422eb-d9d6-4245-9eca-2be5cf256450&scope=files.readwrite&response_type=token&redirect_uri=http%3A//localhost%3A8080/ |
| 56 | + Sign in to your account, copy the whole redirected URL. |
| 57 | + Paste the URL here :http://localhost:8080/#access_token=EwBYA8l6BAAUO9chh8cJscQLmU%2bLSWpbnr0vmwwAAXbgH8Q919pMC8ErHXfcrM/uuPvmmsIyKar8nmAp1mvv/0QwrjAkSBM8Y6sJqpPEPrGKBrDHairoIVrQK7FhGCtYLGEy3P88wnaKGr4NYygckbi2g6P4S5KPt7d3m3/7XuAhLips6jwD3X8g89a72SajQaa1xbPFw2TfUed/UG6kqUxzlVUy4gkPCBMm%2bizQ3mP7lXRbmeXqCY5omTSQz6djvkCcjXf9TqC1WfVpRLHGc7yLUPcg15nGmdMfwRxWDxYi8rlD34Y0cVYt4KYw3B2VkdxyMvCWqARgauWApLYTFopGZIUQ8M0Fggb89PncdhHInKehD8Rp7rkBJIhkfIIDZgAACBnA%2btK5eKnhKAJmVnI6%2b2MwF54q9NR04O9xTn0Py/uOJPpyGeAtMRBgHTSI6Eh/Bwr/ybQh2TMbfNBbqpOEjPYx0KDhDhrcS1LldJKKoYj2EOREEkwKZNKYfmTdO1jWQ/MohoOFawGB29gdSyJxkqgRHrC2RedL3wFYMOxE78ehVvfCl1/UqBR4Z4ypPMZ%2bsFlyCOCQ6E2fiLyJt0AF5wZencLGoAhXdlh/gIDVZuSZBVQXZuEP19d07IGqLmwDoVnhecniQMjy3cLVQ5v0vlT15b/GpuESNhtgrdQwGT307F9gHPVO6U9UMzfT1iEx%2bjqOBR5paJz8OiIZOG3SZmqZFB4c606Vycio3BVnkXyNlf6kBZfJMNVLB4IubmXSbM%2byFjadP1Cq3pc2dsQRx%2bMqhYCDYS%2bYm4yBqHW0r/XfLrs/QmiIgVtAneHyw99TYVFEO2sqM3MLPZS1W8Wm0cFvwvfxuDI4cDllhjkX5jPy0wSD35c9rDZ8gwWdpR1x6Xc/XaTsn1eQEb9CcsZxyyIeJ6SA9t2kysZ1udqbu4xqIuMt3QtIdYA3tDDIg9IPJtF7tuC48G5tjm7BlfOANxhfsg8USYtjovd3KC4Jl4w87OBeiGrRQgaoI4pEfZVgYPa4TuOYe6ZuYCEyNW8GYumvetzmkRkrMBwicAqJ5KXVco5Lird6gCbQSWFjBTfxtdzXFKCiEgcQSDAm88xTwN2LvBKsrbV17QkEyNYqcVzo1CdsAg%3d%3d&token_type=bearer&expires_in=3600&scope=Files.ReadWrite%20Files.ReadWrite.All |
| 58 | + Connected to the OneDrive of ( personal ). |
| 59 | + Connection valid for one hour. Reauthenticate if required. |
| 60 | + |
| 61 | + |
| 62 | +Looks all right. We have got the access token, and included in the HEADERS. You can print response to see more. |
| 63 | + |
| 64 | +### List folders unde root |
| 65 | + |
| 66 | +We will pring both directory names and item-d |
| 67 | + |
| 68 | + |
| 69 | +```python |
| 70 | +items = json.loads(requests.get(URL + 'me/drive/root/children', headers=HEADERS).text) |
| 71 | +items = items['value'] |
| 72 | +for entries in range(len(items)): |
| 73 | + print(items[entries]['name'], '| item-id >', items[entries]['id']) |
| 74 | +``` |
| 75 | + |
| 76 | + Documents | item-id > C1465DBECD7188C9!103 |
| 77 | + Pictures | item-id > C1465DBECD7188C9!104 |
| 78 | + Getting started with OneDrive.pdf | item-id > C1465DBECD7188C9!102 |
| 79 | + |
| 80 | + |
| 81 | +### Create new folder (in the root directory) |
| 82 | + |
| 83 | + |
| 84 | +```python |
| 85 | +url = URL + 'me/drive/root/children/' |
| 86 | +body = { |
| 87 | + "name": "New_Folder", |
| 88 | + "folder": {}, |
| 89 | + "@microsoft.graph.conflictBehavior": "rename" |
| 90 | +} |
| 91 | +response = json.loads(requests.post(url, headers=HEADERS, json=body).text) |
| 92 | +``` |
| 93 | + |
| 94 | +Now lets list the directory again |
| 95 | + |
| 96 | + |
| 97 | +```python |
| 98 | +items = json.loads(requests.get(URL + 'me/drive/root/children', headers=HEADERS).text) |
| 99 | +items = items['value'] |
| 100 | +for entries in range(len(items)): |
| 101 | + print(items[entries]['name'], '| item-id >', items[entries]['id']) |
| 102 | +``` |
| 103 | + |
| 104 | + Documents | item-id > C1465DBECD7188C9!103 |
| 105 | + New_Folder | item-id > C1465DBECD7188C9!106 |
| 106 | + Pictures | item-id > C1465DBECD7188C9!104 |
| 107 | + Getting started with OneDrive.pdf | item-id > C1465DBECD7188C9!102 |
| 108 | + |
| 109 | + |
| 110 | +Here we go, we have successfully created the folder New_Folder. |
| 111 | + |
| 112 | +#### List folders under a sub-folder (need to use item-id) |
| 113 | +Note that if you need to create or list sub-folders, you need to use the item-id. The path/folder notation does not work everywhere. |
| 114 | + |
| 115 | + |
| 116 | +```python |
| 117 | +url = URL + 'me/drive/items/C1465DBECD7188C9!106/children' |
| 118 | +items = json.loads(requests.get(url, headers=HEADERS).text) |
| 119 | +items = items['value'] |
| 120 | +for entries in range(len(items)): |
| 121 | + print(items[entries]['name'], '| item-id >', items[entries]['id']) |
| 122 | +``` |
| 123 | + |
| 124 | +Well there are no files or folders under the New_Folder. Ok let's create one. |
| 125 | + |
| 126 | + |
| 127 | +```python |
| 128 | +url = URL + 'me/drive/items/C1465DBECD7188C9!106/children/' |
| 129 | +data = { |
| 130 | + "name": "sub_folder", |
| 131 | + "folder": {}, |
| 132 | + "@microsoft.graph.conflictBehavior": "rename" |
| 133 | +} |
| 134 | + |
| 135 | +response = json.loads(requests.post(url, headers=HEADERS, json = data).text) |
| 136 | +``` |
| 137 | + |
| 138 | +Now let's print the list again. |
| 139 | + |
| 140 | + |
| 141 | +```python |
| 142 | +url = URL + 'me/drive/items/C1465DBECD7188C9!106/children' |
| 143 | +items = json.loads(requests.get(url, headers=HEADERS).text) |
| 144 | +items = items['value'] |
| 145 | +for entries in range(len(items)): |
| 146 | + print(items[entries]['name'], '| item-id >', items[entries]['id']) |
| 147 | +``` |
| 148 | + |
| 149 | + sub_folder | item-id > C1465DBECD7188C9!107 |
| 150 | + |
| 151 | + |
| 152 | +### Rename an item |
| 153 | + |
| 154 | + |
| 155 | +```python |
| 156 | +url = URL + 'me/drive/items/C1465DBECD7188C9!106' |
| 157 | +body = { |
| 158 | + "name": "New_folder_2", |
| 159 | +} |
| 160 | +response = json.loads(requests.patch(url, headers=HEADERS, json = body).text) |
| 161 | +``` |
| 162 | + |
| 163 | + |
| 164 | +```python |
| 165 | +url = URL + 'me/drive/items/root/children' |
| 166 | +items = json.loads(requests.get(url, headers=HEADERS).text) |
| 167 | +items = items['value'] |
| 168 | +for entries in range(len(items)): |
| 169 | + print(items[entries]['name'], '| item-id >', items[entries]['id']) |
| 170 | +``` |
| 171 | + |
| 172 | + Documents | item-id > C1465DBECD7188C9!103 |
| 173 | + New_folder_2 | item-id > C1465DBECD7188C9!106 |
| 174 | + Pictures | item-id > C1465DBECD7188C9!104 |
| 175 | + Getting started with OneDrive.pdf | item-id > C1465DBECD7188C9!102 |
| 176 | + |
| 177 | + |
| 178 | +#### Delete item |
| 179 | + |
| 180 | + |
| 181 | +```python |
| 182 | +url = '/me/drive/items/C1465DBECD7188C9!106' |
| 183 | +url = URL + url |
| 184 | +confirmation = input('Are you sure to delete the Item? (Y/n):') |
| 185 | +if (confirmation.lower()=='y'): |
| 186 | + response = requests.delete(url, headers=HEADERS) |
| 187 | + if (response.status_code == 204): |
| 188 | + print('Item gone! If need to recover, please check OneDrive Recycle Bin.') |
| 189 | +else: |
| 190 | + print("Item not deleted.") |
| 191 | +``` |
| 192 | + |
| 193 | + Are you sure to delete the Item? (Y/n):y |
| 194 | + Item gone! If need to recover, please check OneDrive Recycle Bin. |
| 195 | + |
| 196 | + |
| 197 | + |
| 198 | +```python |
| 199 | +url = URL + 'me/drive/items/root/children' |
| 200 | +items = json.loads(requests.get(url, headers=HEADERS).text) |
| 201 | +items = items['value'] |
| 202 | +for entries in range(len(items)): |
| 203 | + print(items[entries]['name'], '| item-id >', items[entries]['id']) |
| 204 | +``` |
| 205 | + |
| 206 | + Documents | item-id > C1465DBECD7188C9!103 |
| 207 | + Pictures | item-id > C1465DBECD7188C9!104 |
| 208 | + Getting started with OneDrive.pdf | item-id > C1465DBECD7188C9!102 |
| 209 | + |
| 210 | + |
| 211 | +#### Find item-id by item name |
| 212 | + |
| 213 | + |
| 214 | +```python |
| 215 | +items = json.loads(requests.get(URL + 'me/drive/items/root/children', headers=HEADERS).text) |
| 216 | +look_for_item = 'Documents' |
| 217 | +item_id = '' |
| 218 | +items = items['value'] |
| 219 | +for entries in range(len(items)): |
| 220 | + if(items[entries]['name'] == look_for_item): |
| 221 | + item_id = items[entries]['id'] |
| 222 | + print('Item-id of', look_for_item, ':', item_id) |
| 223 | + break |
| 224 | +if(item_id==''): |
| 225 | + print(look_for_item, 'not found in the directory.') |
| 226 | +``` |
| 227 | + |
| 228 | + Item-id of Documents : C1465DBECD7188C9!103 |
| 229 | + |
| 230 | + |
| 231 | +#### Upload file |
| 232 | + |
| 233 | + |
| 234 | +```python |
| 235 | +url = 'me/drive/root:/example_spectrum.txt:/content' |
| 236 | +url = URL + url |
| 237 | +content = open('example_spectrum.txt', 'rb') |
| 238 | +response = json.loads(requests.put(url, headers=HEADERS, data = content).text) |
| 239 | +``` |
| 240 | + |
| 241 | + |
| 242 | +```python |
| 243 | +url = URL + 'me/drive/items/root/children' |
| 244 | +items = json.loads(requests.get(url, headers=HEADERS).text) |
| 245 | +items = items['value'] |
| 246 | +for entries in range(len(items)): |
| 247 | + print(items[entries]['name'], '| item-id >', items[entries]['id']) |
| 248 | +``` |
| 249 | + |
| 250 | + Documents | item-id > C1465DBECD7188C9!103 |
| 251 | + Pictures | item-id > C1465DBECD7188C9!104 |
| 252 | + example_spectrum.txt | item-id > C1465DBECD7188C9!108 |
| 253 | + Getting started with OneDrive.pdf | item-id > C1465DBECD7188C9!102 |
| 254 | + |
| 255 | + |
| 256 | +### Access/Download data |
| 257 | + |
| 258 | + |
| 259 | +```python |
| 260 | +url = 'me/drive/root:/example_spectrum.txt:/content' |
| 261 | +url = URL + url |
| 262 | +data = requests.get(url, headers=HEADERS).text |
| 263 | +``` |
| 264 | + |
| 265 | +You may like to save the data in a file in your local drive. |
| 266 | + |
| 267 | +#### Upload large files (Can be used to upload small files as well) |
| 268 | +If you have files (probably larger than 4 MB), you need to create upload sessions. |
| 269 | + |
| 270 | + |
| 271 | +```python |
| 272 | +url = 'me/drive/items/C1465DBECD7188C9!103:/large_file.dat:/createUploadSession' |
| 273 | +url = URL + url |
| 274 | +url = json.loads(requests.post(url, headers=HEADERS).text) |
| 275 | +url = url['uploadUrl'] |
| 276 | +file_path = '/local/file/path/large_file.dat' |
| 277 | +file_size = os.path.getsize(file_path) |
| 278 | +chunk_size = 320*1024*10 # Has to be multiple of 320 kb |
| 279 | +no_of_uploads = file_size//chunk_size |
| 280 | +content_range_start = 0 |
| 281 | +if file_size < chunk_size : |
| 282 | + content_range_end = file_size |
| 283 | +else : |
| 284 | + content_range_end = chunk_size - 1 |
| 285 | + |
| 286 | +data = open(file_path, 'rb') |
| 287 | +while data.tell() < file_size: |
| 288 | + if ((file_size - data.tell()) <= chunk_size): |
| 289 | + content_range_end = file_size -1 |
| 290 | + headers = {'Content-Range' : 'bytes '+ str(content_range_start)+ '-' +str(content_range_end)+'/'+str(file_size)} |
| 291 | + content = data.read(chunk_size) |
| 292 | + response = json.loads(requests.put(url, headers=headers, data = content).text) |
| 293 | + else: |
| 294 | + headers = {'Content-Range' : 'bytes '+ str(content_range_start)+ '-' +str(content_range_end)+'/'+str(file_size)} |
| 295 | + content = data.read(chunk_size) |
| 296 | + response = json.loads(requests.put(url, headers=headers, data = content).text) |
| 297 | + content_range_start = data.tell() |
| 298 | + content_range_end = data.tell() + chunk_size - 1 |
| 299 | +data.close() |
| 300 | +response2 = requests.delete(url) |
| 301 | +``` |
| 302 | + |
| 303 | +#### OneDrive storage usage |
| 304 | + |
| 305 | + |
| 306 | +```python |
| 307 | +response = json.loads(requests.get(URL + 'me/drive/', headers = HEADERS).text) |
| 308 | +used = round(response['quota']['used']/(1024*1024*1024), 2) |
| 309 | +total = round(response['quota']['total']/(1024*1024*1024), 2) |
| 310 | +print('Using', used, 'GB (', round(used*100/total, 2),'%) of total', total, 'GB.') |
| 311 | +``` |
| 312 | + |
| 313 | + Using 0.48 GB ( 9.6 %) of total 5.0 GB. |
| 314 | + |
| 315 | + |
| 316 | + |
| 317 | +```python |
| 318 | + |
| 319 | +``` |
0 commit comments