0
# OneDrive & File Management
1
2
Comprehensive OneDrive storage access with file operations including upload, download, sharing, and metadata management through Microsoft Graph API. Provides complete document management capabilities for personal OneDrive and SharePoint document libraries.
3
4
## Capabilities
5
6
### Drive Access and Management
7
8
OneDrive storage containers with support for personal drives, shared drives, and SharePoint document libraries with comprehensive metadata and permission management.
9
10
```python { .api }
11
class Drive:
12
"""OneDrive storage container with file and folder management capabilities."""
13
14
# Core Properties
15
id: str
16
name: str
17
description: str
18
drive_type: str # "personal", "business", "documentLibrary"
19
web_url: str
20
created_date_time: str
21
last_modified_date_time: str
22
23
def get(self) -> 'Drive':
24
"""
25
Retrieve drive information and metadata.
26
27
Returns:
28
Drive: Updated drive object with current data
29
"""
30
31
def get_by_path(self, path: str) -> 'DriveItem':
32
"""
33
Get drive item by path.
34
35
Args:
36
path (str): Item path relative to drive root
37
38
Returns:
39
DriveItem: Item at specified path
40
"""
41
42
def search(self, query: str) -> 'DriveItemCollection':
43
"""
44
Search for items in drive.
45
46
Args:
47
query (str): Search query string
48
49
Returns:
50
DriveItemCollection: Collection of matching items
51
"""
52
53
def recent(self) -> 'DriveItemCollection':
54
"""
55
Get recently accessed items in drive.
56
57
Returns:
58
DriveItemCollection: Collection of recent items
59
"""
60
61
def shared_with_me(self) -> 'DriveItemCollection':
62
"""
63
Get items shared with current user.
64
65
Returns:
66
DriveItemCollection: Collection of shared items
67
"""
68
69
# Navigation Properties
70
@property
71
def root(self) -> 'DriveItem':
72
"""Root folder of the drive."""
73
74
@property
75
def items(self) -> 'DriveItemCollection':
76
"""All items in the drive."""
77
78
@property
79
def special(self) -> 'DriveItemCollection':
80
"""Special folders (Documents, Photos, etc.)."""
81
82
@property
83
def quota(self) -> Dict[str, Any]:
84
"""Drive storage quota information."""
85
86
class DriveCollection:
87
"""Collection of OneDrive storage containers with query capabilities."""
88
89
def get(self) -> 'DriveCollection':
90
"""Retrieve collection of drives."""
91
92
def filter(self, expression: str) -> 'DriveCollection':
93
"""
94
Filter drives by OData expression.
95
96
Args:
97
expression (str): OData filter expression
98
99
Returns:
100
DriveCollection: Filtered collection
101
"""
102
103
def get_by_id(self, drive_id: str) -> Drive:
104
"""
105
Get drive by ID.
106
107
Args:
108
drive_id (str): Drive unique identifier
109
110
Returns:
111
Drive: Drive object
112
"""
113
```
114
115
### File and Folder Operations
116
117
Comprehensive file system operations including upload, download, copy, move, and metadata management with support for large files and batch operations.
118
119
```python { .api }
120
class DriveItem:
121
"""File or folder in OneDrive with comprehensive management capabilities."""
122
123
# Core Properties
124
id: str
125
name: str
126
description: str
127
web_url: str
128
size: int
129
created_date_time: str
130
last_modified_date_time: str
131
e_tag: str
132
c_tag: str
133
134
def get(self) -> 'DriveItem':
135
"""
136
Retrieve item information and metadata.
137
138
Returns:
139
DriveItem: Updated item object
140
"""
141
142
def update(self) -> 'DriveItem':
143
"""
144
Update item properties and metadata.
145
146
Returns:
147
DriveItem: Updated item object
148
"""
149
150
def delete(self) -> None:
151
"""Delete item (move to recycle bin)."""
152
153
def copy(self, parent_reference: Dict[str, str], name: str = None) -> Dict[str, str]:
154
"""
155
Copy item to new location.
156
157
Args:
158
parent_reference (Dict): Destination parent folder reference
159
name (str, optional): New name for copied item
160
161
Returns:
162
Dict: Copy operation status with monitor URL
163
"""
164
165
def move(self, parent_reference: Dict[str, str], name: str = None) -> 'DriveItem':
166
"""
167
Move item to new location.
168
169
Args:
170
parent_reference (Dict): Destination parent folder reference
171
name (str, optional): New name for moved item
172
173
Returns:
174
DriveItem: Updated item object at new location
175
"""
176
177
def restore(self, parent_reference: Dict[str, str] = None, name: str = None) -> 'DriveItem':
178
"""
179
Restore deleted item from recycle bin.
180
181
Args:
182
parent_reference (Dict, optional): Parent folder reference
183
name (str, optional): Restored item name
184
185
Returns:
186
DriveItem: Restored item object
187
"""
188
189
def create_link(self, link_type: str, scope: str = "anonymous", password: str = None, expiration_date_time: str = None) -> Dict[str, str]:
190
"""
191
Create sharing link for item.
192
193
Args:
194
link_type (str): "view", "edit", or "embed"
195
scope (str): "anonymous", "organization", or "users"
196
password (str, optional): Password protection
197
expiration_date_time (str, optional): Link expiration (ISO 8601)
198
199
Returns:
200
Dict: Sharing link information with URL and permissions
201
"""
202
203
def invite(self, recipients: List[Dict[str, str]], message: str = None, require_sign_in: bool = True, send_invitation: bool = True, roles: List[str] = None) -> List[Dict[str, Any]]:
204
"""
205
Send sharing invitation for item.
206
207
Args:
208
recipients (List[Dict]): List of email addresses to invite
209
message (str, optional): Personal message in invitation
210
require_sign_in (bool): Require recipients to sign in
211
send_invitation (bool): Send email invitation
212
roles (List[str], optional): Permission roles ("read", "write")
213
214
Returns:
215
List[Dict]: Invitation results for each recipient
216
"""
217
218
# Navigation Properties
219
@property
220
def children(self) -> 'DriveItemCollection':
221
"""Child items (for folders)."""
222
223
@property
224
def permissions(self) -> 'PermissionCollection':
225
"""Sharing permissions for the item."""
226
227
@property
228
def thumbnails(self) -> 'ThumbnailSetCollection':
229
"""Thumbnail images for the item."""
230
231
@property
232
def versions(self) -> 'DriveItemVersionCollection':
233
"""Version history for the item."""
234
235
@property
236
def parent(self) -> 'DriveItem':
237
"""Parent folder of the item."""
238
239
class File(DriveItem):
240
"""File-specific operations extending DriveItem capabilities."""
241
242
# File Properties
243
mime_type: str
244
hashes: Dict[str, str] # SHA1, SHA256, etc.
245
246
def download(self) -> bytes:
247
"""
248
Download file content.
249
250
Returns:
251
bytes: File content as bytes
252
"""
253
254
def upload(self, content: bytes) -> 'File':
255
"""
256
Upload file content (replaces existing content).
257
258
Args:
259
content (bytes): File content to upload
260
261
Returns:
262
File: Updated file object
263
"""
264
265
def create_upload_session(self, item: Dict[str, Any] = None) -> Dict[str, str]:
266
"""
267
Create upload session for large files (>4MB).
268
269
Args:
270
item (Dict, optional): File metadata
271
272
Returns:
273
Dict: Upload session information with upload URL
274
"""
275
276
def get_content(self) -> bytes:
277
"""
278
Get file content as bytes.
279
280
Returns:
281
bytes: File content
282
"""
283
284
def checkout(self) -> None:
285
"""Check out file for editing (SharePoint)."""
286
287
def checkin(self, comment: str = None) -> None:
288
"""
289
Check in file after editing.
290
291
Args:
292
comment (str, optional): Check-in comment
293
"""
294
295
def preview(self, page: str = None, zoom: float = None) -> Dict[str, str]:
296
"""
297
Get file preview information.
298
299
Args:
300
page (str, optional): Page number for multi-page files
301
zoom (float, optional): Zoom level
302
303
Returns:
304
Dict: Preview URL and metadata
305
"""
306
307
class Folder(DriveItem):
308
"""Folder-specific operations extending DriveItem capabilities."""
309
310
# Folder Properties
311
child_count: int
312
313
def upload_file(self, name: str, content: bytes) -> File:
314
"""
315
Upload file to folder.
316
317
Args:
318
name (str): File name
319
content (bytes): File content
320
321
Returns:
322
File: Uploaded file object
323
"""
324
325
def create_folder(self, name: str) -> 'Folder':
326
"""
327
Create subfolder.
328
329
Args:
330
name (str): Folder name
331
332
Returns:
333
Folder: Created folder object
334
"""
335
336
def get_by_name(self, name: str) -> DriveItem:
337
"""
338
Get child item by name.
339
340
Args:
341
name (str): Item name
342
343
Returns:
344
DriveItem: Child item with specified name
345
"""
346
347
class DriveItemCollection:
348
"""Collection of drive items with query and management capabilities."""
349
350
def get(self) -> 'DriveItemCollection':
351
"""Retrieve collection of drive items."""
352
353
def filter(self, expression: str) -> 'DriveItemCollection':
354
"""
355
Filter items by OData expression.
356
357
Args:
358
expression (str): OData filter expression
359
360
Returns:
361
DriveItemCollection: Filtered collection
362
"""
363
364
def select(self, properties: List[str]) -> 'DriveItemCollection':
365
"""
366
Select specific properties to retrieve.
367
368
Args:
369
properties (List[str]): Property names to select
370
371
Returns:
372
DriveItemCollection: Collection with selected properties
373
"""
374
375
def top(self, count: int) -> 'DriveItemCollection':
376
"""
377
Limit results to top N items.
378
379
Args:
380
count (int): Maximum number of items to return
381
382
Returns:
383
DriveItemCollection: Limited collection
384
"""
385
386
def order_by(self, property_name: str, ascending: bool = True) -> 'DriveItemCollection':
387
"""
388
Sort items by property.
389
390
Args:
391
property_name (str): Property to sort by
392
ascending (bool): Sort direction
393
394
Returns:
395
DriveItemCollection: Sorted collection
396
"""
397
398
def add(self, item_creation_info: Dict[str, Any]) -> DriveItem:
399
"""
400
Create new item in collection.
401
402
Args:
403
item_creation_info (Dict): Item properties for creation
404
405
Returns:
406
DriveItem: Created item object
407
"""
408
```
409
410
### Permission and Sharing Management
411
412
Comprehensive sharing and permission management with support for link sharing, user invitations, and permission inheritance.
413
414
```python { .api }
415
class Permission:
416
"""Sharing permission for drive item with user and role information."""
417
418
# Core Properties
419
id: str
420
roles: List[str] # "read", "write", "owner"
421
link: Dict[str, Any] # Sharing link information
422
invitation: Dict[str, Any] # Invitation details
423
inherit_from: Dict[str, str] # Permission inheritance
424
granted_to: Dict[str, Any] # User/group with permission
425
granted_to_identities: List[Dict[str, Any]] # Multiple grantees
426
427
def get(self) -> 'Permission':
428
"""
429
Retrieve permission information.
430
431
Returns:
432
Permission: Updated permission object
433
"""
434
435
def update(self) -> 'Permission':
436
"""
437
Update permission roles or settings.
438
439
Returns:
440
Permission: Updated permission object
441
"""
442
443
def delete(self) -> None:
444
"""Remove permission from item."""
445
446
class PermissionCollection:
447
"""Collection of sharing permissions with management capabilities."""
448
449
def get(self) -> 'PermissionCollection':
450
"""Retrieve collection of permissions."""
451
452
def add(self, permission_info: Dict[str, Any]) -> Permission:
453
"""
454
Add new permission to item.
455
456
Args:
457
permission_info (Dict): Permission configuration
458
459
Returns:
460
Permission: Created permission object
461
"""
462
463
def get_by_id(self, permission_id: str) -> Permission:
464
"""
465
Get permission by ID.
466
467
Args:
468
permission_id (str): Permission unique identifier
469
470
Returns:
471
Permission: Permission object
472
"""
473
```
474
475
### Version and Thumbnail Management
476
477
File version history and thumbnail generation with support for version restoration and image previews.
478
479
```python { .api }
480
class DriveItemVersion:
481
"""File version with content and metadata access."""
482
483
# Core Properties
484
id: str
485
last_modified_date_time: str
486
size: int
487
488
def get(self) -> 'DriveItemVersion':
489
"""
490
Retrieve version information.
491
492
Returns:
493
DriveItemVersion: Updated version object
494
"""
495
496
def restore(self) -> None:
497
"""Restore this version as current version."""
498
499
def get_content(self) -> bytes:
500
"""
501
Get version content.
502
503
Returns:
504
bytes: Version content as bytes
505
"""
506
507
class DriveItemVersionCollection:
508
"""Collection of file versions with management capabilities."""
509
510
def get(self) -> 'DriveItemVersionCollection':
511
"""Retrieve collection of versions."""
512
513
def get_by_id(self, version_id: str) -> DriveItemVersion:
514
"""
515
Get version by ID.
516
517
Args:
518
version_id (str): Version unique identifier
519
520
Returns:
521
DriveItemVersion: Version object
522
"""
523
524
class ThumbnailSet:
525
"""Set of thumbnail images for drive item in different sizes."""
526
527
# Core Properties
528
id: str
529
large: Dict[str, Any] # Large thumbnail (1920x1920)
530
medium: Dict[str, Any] # Medium thumbnail (176x176)
531
small: Dict[str, Any] # Small thumbnail (96x96)
532
source: Dict[str, Any] # Source image thumbnail
533
534
def get(self) -> 'ThumbnailSet':
535
"""
536
Retrieve thumbnail set information.
537
538
Returns:
539
ThumbnailSet: Updated thumbnail set object
540
"""
541
542
class ThumbnailSetCollection:
543
"""Collection of thumbnail sets with different configurations."""
544
545
def get(self) -> 'ThumbnailSetCollection':
546
"""Retrieve collection of thumbnail sets."""
547
548
def get_by_id(self, set_id: str) -> ThumbnailSet:
549
"""
550
Get thumbnail set by ID.
551
552
Args:
553
set_id (str): Thumbnail set identifier
554
555
Returns:
556
ThumbnailSet: Thumbnail set object
557
"""
558
```
559
560
## Usage Examples
561
562
### Basic File Operations
563
564
```python
565
from office365.graph_client import GraphClient
566
567
client = GraphClient.with_client_secret(client_id, client_secret, tenant)
568
569
# Access user's OneDrive
570
drive = client.me.drive.get().execute_query()
571
print(f"Drive: {drive.name}, Type: {drive.drive_type}")
572
573
# List root folder contents
574
root_items = drive.root.children.get().execute_query()
575
for item in root_items:
576
print(f"{item.name} ({'Folder' if hasattr(item, 'folder') else 'File'})")
577
578
# Create a new folder
579
new_folder = drive.root.create_folder("Project Documents").execute_query()
580
print(f"Created folder: {new_folder.name}")
581
582
# Upload a file
583
with open("document.pdf", "rb") as file_content:
584
uploaded_file = new_folder.upload_file("document.pdf", file_content.read())
585
client.execute_query()
586
print(f"Uploaded: {uploaded_file.web_url}")
587
```
588
589
### Advanced File Management
590
591
```python
592
# Search for files
593
search_results = drive.search("*.xlsx").execute_query()
594
for item in search_results:
595
print(f"Found: {item.name} at {item.web_url}")
596
597
# Get file by path
598
specific_file = drive.get_by_path("/Documents/Report.docx").get().execute_query()
599
print(f"File size: {specific_file.size} bytes")
600
601
# Download file content
602
file_content = specific_file.download()
603
with open("local_copy.docx", "wb") as local_file:
604
local_file.write(file_content)
605
606
# Copy file to another folder
607
destination_folder = {"driveId": drive.id, "id": "folder-id"}
608
copy_operation = specific_file.copy(destination_folder, "Report_Copy.docx")
609
client.execute_query()
610
print(f"Copy operation: {copy_operation.value}")
611
```
612
613
### File Sharing and Permissions
614
615
```python
616
# Create sharing link
617
sharing_link = specific_file.create_link("view", "organization").execute_query()
618
print(f"Sharing URL: {sharing_link.value.get('link', {}).get('webUrl')}")
619
620
# Send sharing invitation
621
recipients = [{"email": "colleague@company.com"}]
622
invitations = specific_file.invite(
623
recipients=recipients,
624
message="Please review this document",
625
roles=["read"]
626
).execute_query()
627
628
# List file permissions
629
permissions = specific_file.permissions.get().execute_query()
630
for permission in permissions:
631
print(f"Permission: {permission.roles} for {permission.granted_to}")
632
633
# Get file versions
634
versions = specific_file.versions.get().execute_query()
635
for version in versions:
636
print(f"Version: {version.id}, Modified: {version.last_modified_date_time}")
637
```
638
639
### Large File Upload
640
641
```python
642
# Upload large file using upload session
643
large_file_path = "large_video.mp4"
644
with open(large_file_path, "rb") as file_content:
645
file_size = len(file_content.read())
646
file_content.seek(0)
647
648
# Create upload session
649
upload_session = new_folder.create_upload_session({
650
"name": "large_video.mp4",
651
"size": file_size
652
}).execute_query()
653
654
upload_url = upload_session.value["uploadUrl"]
655
656
# Upload file in chunks (implementation would handle chunking)
657
# This is a simplified example - actual implementation would chunk the file
658
chunk_size = 320 * 1024 # 320KB chunks
659
# ... chunked upload logic ...
660
```
661
662
## Types
663
664
```python { .api }
665
from typing import Dict, List, Any, Optional
666
667
class ItemReference:
668
"""Reference to a drive item by ID and path."""
669
670
drive_id: str
671
drive_type: str
672
id: str
673
name: str
674
path: str
675
share_id: str
676
sharepoint_ids: Dict[str, str]
677
678
class FileSystemInfo:
679
"""File system metadata from the local file system."""
680
681
created_date_time: str
682
last_accessed_date_time: str
683
last_modified_date_time: str
684
685
class Hashes:
686
"""File content hashes for integrity verification."""
687
688
crc32_hash: str
689
sha1_hash: str
690
sha256_hash: str
691
quick_xor_hash: str
692
693
class Image:
694
"""Image metadata for image files."""
695
696
height: int
697
width: int
698
699
class Photo:
700
"""Photo metadata including EXIF data."""
701
702
camera_make: str
703
camera_model: str
704
exposure_denominator: float
705
exposure_numerator: float
706
focal_length: float
707
f_number: float
708
iso: int
709
orientation: int
710
taken_date_time: str
711
712
class Video:
713
"""Video file metadata."""
714
715
audio_bits_per_sample: int
716
audio_channels: int
717
audio_format: str
718
audio_samples_per_second: int
719
bitrate: int
720
duration: int
721
four_cc: str
722
frame_rate: float
723
height: int
724
width: int
725
726
class SharingLink:
727
"""Sharing link configuration and properties."""
728
729
application: Dict[str, str]
730
prevents_download: bool
731
scope: str # "anonymous", "organization", "users"
732
type: str # "view", "edit", "embed"
733
web_html: str
734
web_url: str
735
736
class SharingInvitation:
737
"""Sharing invitation details and recipient information."""
738
739
email: str
740
invited_by: Dict[str, Any]
741
redeemed_by: str
742
sign_in_required: bool
743
744
class Quota:
745
"""Drive storage quota information."""
746
747
deleted: int
748
remaining: int
749
state: str # "normal", "nearing", "critical", "exceeded"
750
total: int
751
used: int
752
753
class UploadSession:
754
"""Large file upload session configuration."""
755
756
upload_url: str
757
expiration_date_time: str
758
next_expected_ranges: List[str]
759
```