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