CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-office365-rest-python-client

Microsoft 365 & Microsoft Graph Library for Python

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

onedrive-files.mddocs/

OneDrive & File Management

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.

Capabilities

Drive Access and Management

OneDrive storage containers with support for personal drives, shared drives, and SharePoint document libraries with comprehensive metadata and permission management.

class Drive:
    """OneDrive storage container with file and folder management capabilities."""
    
    # Core Properties
    id: str
    name: str
    description: str
    drive_type: str  # "personal", "business", "documentLibrary"
    web_url: str
    created_date_time: str
    last_modified_date_time: str
    
    def get(self) -> 'Drive':
        """
        Retrieve drive information and metadata.
        
        Returns:
            Drive: Updated drive object with current data
        """
    
    def get_by_path(self, path: str) -> 'DriveItem':
        """
        Get drive item by path.
        
        Args:
            path (str): Item path relative to drive root
            
        Returns:
            DriveItem: Item at specified path
        """
    
    def search(self, query: str) -> 'DriveItemCollection':
        """
        Search for items in drive.
        
        Args:
            query (str): Search query string
            
        Returns:
            DriveItemCollection: Collection of matching items
        """
    
    def recent(self) -> 'DriveItemCollection':
        """
        Get recently accessed items in drive.
        
        Returns:
            DriveItemCollection: Collection of recent items
        """
    
    def shared_with_me(self) -> 'DriveItemCollection':
        """
        Get items shared with current user.
        
        Returns:
            DriveItemCollection: Collection of shared items
        """
    
    # Navigation Properties
    @property
    def root(self) -> 'DriveItem':
        """Root folder of the drive."""
    
    @property
    def items(self) -> 'DriveItemCollection':
        """All items in the drive."""
    
    @property
    def special(self) -> 'DriveItemCollection':
        """Special folders (Documents, Photos, etc.)."""
    
    @property
    def quota(self) -> Dict[str, Any]:
        """Drive storage quota information."""

class DriveCollection:
    """Collection of OneDrive storage containers with query capabilities."""
    
    def get(self) -> 'DriveCollection':
        """Retrieve collection of drives."""
    
    def filter(self, expression: str) -> 'DriveCollection':
        """
        Filter drives by OData expression.
        
        Args:
            expression (str): OData filter expression
            
        Returns:
            DriveCollection: Filtered collection
        """
    
    def get_by_id(self, drive_id: str) -> Drive:
        """
        Get drive by ID.
        
        Args:
            drive_id (str): Drive unique identifier
            
        Returns:
            Drive: Drive object
        """

File and Folder Operations

Comprehensive file system operations including upload, download, copy, move, and metadata management with support for large files and batch operations.

class DriveItem:
    """File or folder in OneDrive with comprehensive management capabilities."""
    
    # Core Properties
    id: str
    name: str
    description: str
    web_url: str
    size: int
    created_date_time: str
    last_modified_date_time: str
    e_tag: str
    c_tag: str
    
    def get(self) -> 'DriveItem':
        """
        Retrieve item information and metadata.
        
        Returns:
            DriveItem: Updated item object
        """
    
    def update(self) -> 'DriveItem':
        """
        Update item properties and metadata.
        
        Returns:
            DriveItem: Updated item object
        """
    
    def delete(self) -> None:
        """Delete item (move to recycle bin)."""
    
    def copy(self, parent_reference: Dict[str, str], name: str = None) -> Dict[str, str]:
        """
        Copy item to new location.
        
        Args:
            parent_reference (Dict): Destination parent folder reference
            name (str, optional): New name for copied item
            
        Returns:
            Dict: Copy operation status with monitor URL
        """
    
    def move(self, parent_reference: Dict[str, str], name: str = None) -> 'DriveItem':
        """
        Move item to new location.
        
        Args:
            parent_reference (Dict): Destination parent folder reference  
            name (str, optional): New name for moved item
            
        Returns:
            DriveItem: Updated item object at new location
        """
    
    def restore(self, parent_reference: Dict[str, str] = None, name: str = None) -> 'DriveItem':
        """
        Restore deleted item from recycle bin.
        
        Args:
            parent_reference (Dict, optional): Parent folder reference
            name (str, optional): Restored item name
            
        Returns:
            DriveItem: Restored item object
        """
    
    def create_link(self, link_type: str, scope: str = "anonymous", password: str = None, expiration_date_time: str = None) -> Dict[str, str]:
        """
        Create sharing link for item.
        
        Args:
            link_type (str): "view", "edit", or "embed"
            scope (str): "anonymous", "organization", or "users"
            password (str, optional): Password protection
            expiration_date_time (str, optional): Link expiration (ISO 8601)
            
        Returns:
            Dict: Sharing link information with URL and permissions
        """
    
    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]]:
        """
        Send sharing invitation for item.
        
        Args:
            recipients (List[Dict]): List of email addresses to invite
            message (str, optional): Personal message in invitation
            require_sign_in (bool): Require recipients to sign in
            send_invitation (bool): Send email invitation
            roles (List[str], optional): Permission roles ("read", "write")
            
        Returns:
            List[Dict]: Invitation results for each recipient
        """
    
    # Navigation Properties
    @property
    def children(self) -> 'DriveItemCollection':
        """Child items (for folders)."""
    
    @property
    def permissions(self) -> 'PermissionCollection':
        """Sharing permissions for the item."""
    
    @property
    def thumbnails(self) -> 'ThumbnailSetCollection':
        """Thumbnail images for the item."""
    
    @property
    def versions(self) -> 'DriveItemVersionCollection':
        """Version history for the item."""
    
    @property
    def parent(self) -> 'DriveItem':
        """Parent folder of the item."""

class File(DriveItem):
    """File-specific operations extending DriveItem capabilities."""
    
    # File Properties
    mime_type: str
    hashes: Dict[str, str]  # SHA1, SHA256, etc.
    
    def download(self) -> bytes:
        """
        Download file content.
        
        Returns:
            bytes: File content as bytes
        """
    
    def upload(self, content: bytes) -> 'File':
        """
        Upload file content (replaces existing content).
        
        Args:
            content (bytes): File content to upload
            
        Returns:
            File: Updated file object
        """
    
    def create_upload_session(self, item: Dict[str, Any] = None) -> Dict[str, str]:
        """
        Create upload session for large files (>4MB).
        
        Args:
            item (Dict, optional): File metadata
            
        Returns:
            Dict: Upload session information with upload URL
        """
    
    def get_content(self) -> bytes:
        """
        Get file content as bytes.
        
        Returns:
            bytes: File content
        """
    
    def checkout(self) -> None:
        """Check out file for editing (SharePoint)."""
    
    def checkin(self, comment: str = None) -> None:
        """
        Check in file after editing.
        
        Args:
            comment (str, optional): Check-in comment
        """
    
    def preview(self, page: str = None, zoom: float = None) -> Dict[str, str]:
        """
        Get file preview information.
        
        Args:
            page (str, optional): Page number for multi-page files
            zoom (float, optional): Zoom level
            
        Returns:
            Dict: Preview URL and metadata
        """

class Folder(DriveItem):
    """Folder-specific operations extending DriveItem capabilities."""
    
    # Folder Properties
    child_count: int
    
    def upload_file(self, name: str, content: bytes) -> File:
        """
        Upload file to folder.
        
        Args:
            name (str): File name
            content (bytes): File content
            
        Returns:
            File: Uploaded file object
        """
    
    def create_folder(self, name: str) -> 'Folder':
        """
        Create subfolder.
        
        Args:
            name (str): Folder name
            
        Returns:
            Folder: Created folder object
        """
    
    def get_by_name(self, name: str) -> DriveItem:
        """
        Get child item by name.
        
        Args:
            name (str): Item name
            
        Returns:
            DriveItem: Child item with specified name
        """

class DriveItemCollection:
    """Collection of drive items with query and management capabilities."""
    
    def get(self) -> 'DriveItemCollection':
        """Retrieve collection of drive items."""
    
    def filter(self, expression: str) -> 'DriveItemCollection':
        """
        Filter items by OData expression.
        
        Args:
            expression (str): OData filter expression
            
        Returns:
            DriveItemCollection: Filtered collection
        """
    
    def select(self, properties: List[str]) -> 'DriveItemCollection':
        """
        Select specific properties to retrieve.
        
        Args:
            properties (List[str]): Property names to select
            
        Returns:
            DriveItemCollection: Collection with selected properties
        """
    
    def top(self, count: int) -> 'DriveItemCollection':
        """
        Limit results to top N items.
        
        Args:
            count (int): Maximum number of items to return
            
        Returns:
            DriveItemCollection: Limited collection
        """
    
    def order_by(self, property_name: str, ascending: bool = True) -> 'DriveItemCollection':
        """
        Sort items by property.
        
        Args:
            property_name (str): Property to sort by
            ascending (bool): Sort direction
            
        Returns:
            DriveItemCollection: Sorted collection
        """
    
    def add(self, item_creation_info: Dict[str, Any]) -> DriveItem:
        """
        Create new item in collection.
        
        Args:
            item_creation_info (Dict): Item properties for creation
            
        Returns:
            DriveItem: Created item object
        """

Permission and Sharing Management

Comprehensive sharing and permission management with support for link sharing, user invitations, and permission inheritance.

class Permission:
    """Sharing permission for drive item with user and role information."""
    
    # Core Properties
    id: str
    roles: List[str]  # "read", "write", "owner"
    link: Dict[str, Any]  # Sharing link information
    invitation: Dict[str, Any]  # Invitation details
    inherit_from: Dict[str, str]  # Permission inheritance
    granted_to: Dict[str, Any]  # User/group with permission
    granted_to_identities: List[Dict[str, Any]]  # Multiple grantees
    
    def get(self) -> 'Permission':
        """
        Retrieve permission information.
        
        Returns:
            Permission: Updated permission object
        """
    
    def update(self) -> 'Permission':
        """
        Update permission roles or settings.
        
        Returns:
            Permission: Updated permission object
        """
    
    def delete(self) -> None:
        """Remove permission from item."""

class PermissionCollection:
    """Collection of sharing permissions with management capabilities."""
    
    def get(self) -> 'PermissionCollection':
        """Retrieve collection of permissions."""
    
    def add(self, permission_info: Dict[str, Any]) -> Permission:
        """
        Add new permission to item.
        
        Args:
            permission_info (Dict): Permission configuration
            
        Returns:
            Permission: Created permission object
        """
    
    def get_by_id(self, permission_id: str) -> Permission:
        """
        Get permission by ID.
        
        Args:
            permission_id (str): Permission unique identifier
            
        Returns:
            Permission: Permission object
        """

Version and Thumbnail Management

File version history and thumbnail generation with support for version restoration and image previews.

class DriveItemVersion:
    """File version with content and metadata access."""
    
    # Core Properties
    id: str
    last_modified_date_time: str
    size: int
    
    def get(self) -> 'DriveItemVersion':
        """
        Retrieve version information.
        
        Returns:
            DriveItemVersion: Updated version object
        """
    
    def restore(self) -> None:
        """Restore this version as current version."""
    
    def get_content(self) -> bytes:
        """
        Get version content.
        
        Returns:
            bytes: Version content as bytes
        """

class DriveItemVersionCollection:
    """Collection of file versions with management capabilities."""
    
    def get(self) -> 'DriveItemVersionCollection':
        """Retrieve collection of versions."""
    
    def get_by_id(self, version_id: str) -> DriveItemVersion:
        """
        Get version by ID.
        
        Args:
            version_id (str): Version unique identifier
            
        Returns:
            DriveItemVersion: Version object
        """

class ThumbnailSet:
    """Set of thumbnail images for drive item in different sizes."""
    
    # Core Properties
    id: str
    large: Dict[str, Any]  # Large thumbnail (1920x1920)
    medium: Dict[str, Any]  # Medium thumbnail (176x176)
    small: Dict[str, Any]  # Small thumbnail (96x96)
    source: Dict[str, Any]  # Source image thumbnail
    
    def get(self) -> 'ThumbnailSet':
        """
        Retrieve thumbnail set information.
        
        Returns:
            ThumbnailSet: Updated thumbnail set object
        """

class ThumbnailSetCollection:
    """Collection of thumbnail sets with different configurations."""
    
    def get(self) -> 'ThumbnailSetCollection':
        """Retrieve collection of thumbnail sets."""
    
    def get_by_id(self, set_id: str) -> ThumbnailSet:
        """
        Get thumbnail set by ID.
        
        Args:
            set_id (str): Thumbnail set identifier
            
        Returns:
            ThumbnailSet: Thumbnail set object
        """

Usage Examples

Basic File Operations

from office365.graph_client import GraphClient

client = GraphClient.with_client_secret(client_id, client_secret, tenant)

# Access user's OneDrive
drive = client.me.drive.get().execute_query()
print(f"Drive: {drive.name}, Type: {drive.drive_type}")

# List root folder contents
root_items = drive.root.children.get().execute_query()
for item in root_items:
    print(f"{item.name} ({'Folder' if hasattr(item, 'folder') else 'File'})")

# Create a new folder
new_folder = drive.root.create_folder("Project Documents").execute_query()
print(f"Created folder: {new_folder.name}")

# Upload a file
with open("document.pdf", "rb") as file_content:
    uploaded_file = new_folder.upload_file("document.pdf", file_content.read())
    client.execute_query()
    print(f"Uploaded: {uploaded_file.web_url}")

Advanced File Management

# Search for files
search_results = drive.search("*.xlsx").execute_query()
for item in search_results:
    print(f"Found: {item.name} at {item.web_url}")

# Get file by path
specific_file = drive.get_by_path("/Documents/Report.docx").get().execute_query()
print(f"File size: {specific_file.size} bytes")

# Download file content
file_content = specific_file.download()
with open("local_copy.docx", "wb") as local_file:
    local_file.write(file_content)

# Copy file to another folder
destination_folder = {"driveId": drive.id, "id": "folder-id"}
copy_operation = specific_file.copy(destination_folder, "Report_Copy.docx")
client.execute_query()
print(f"Copy operation: {copy_operation.value}")

File Sharing and Permissions

# Create sharing link
sharing_link = specific_file.create_link("view", "organization").execute_query()
print(f"Sharing URL: {sharing_link.value.get('link', {}).get('webUrl')}")

# Send sharing invitation
recipients = [{"email": "colleague@company.com"}]
invitations = specific_file.invite(
    recipients=recipients,
    message="Please review this document",
    roles=["read"]
).execute_query()

# List file permissions
permissions = specific_file.permissions.get().execute_query()
for permission in permissions:
    print(f"Permission: {permission.roles} for {permission.granted_to}")

# Get file versions
versions = specific_file.versions.get().execute_query()
for version in versions:
    print(f"Version: {version.id}, Modified: {version.last_modified_date_time}")

Large File Upload

# Upload large file using upload session
large_file_path = "large_video.mp4"
with open(large_file_path, "rb") as file_content:
    file_size = len(file_content.read())
    file_content.seek(0)
    
    # Create upload session
    upload_session = new_folder.create_upload_session({
        "name": "large_video.mp4",
        "size": file_size
    }).execute_query()
    
    upload_url = upload_session.value["uploadUrl"]
    
    # Upload file in chunks (implementation would handle chunking)
    # This is a simplified example - actual implementation would chunk the file
    chunk_size = 320 * 1024  # 320KB chunks
    # ... chunked upload logic ...

Types

from typing import Dict, List, Any, Optional

class ItemReference:
    """Reference to a drive item by ID and path."""
    
    drive_id: str
    drive_type: str
    id: str
    name: str
    path: str
    share_id: str
    sharepoint_ids: Dict[str, str]

class FileSystemInfo:
    """File system metadata from the local file system."""
    
    created_date_time: str
    last_accessed_date_time: str
    last_modified_date_time: str

class Hashes:
    """File content hashes for integrity verification."""
    
    crc32_hash: str
    sha1_hash: str
    sha256_hash: str
    quick_xor_hash: str

class Image:
    """Image metadata for image files."""
    
    height: int
    width: int

class Photo:
    """Photo metadata including EXIF data."""
    
    camera_make: str
    camera_model: str
    exposure_denominator: float
    exposure_numerator: float
    focal_length: float
    f_number: float
    iso: int
    orientation: int
    taken_date_time: str

class Video:
    """Video file metadata."""
    
    audio_bits_per_sample: int
    audio_channels: int
    audio_format: str
    audio_samples_per_second: int
    bitrate: int
    duration: int
    four_cc: str
    frame_rate: float
    height: int
    width: int

class SharingLink:
    """Sharing link configuration and properties."""
    
    application: Dict[str, str]
    prevents_download: bool
    scope: str  # "anonymous", "organization", "users"
    type: str   # "view", "edit", "embed"
    web_html: str
    web_url: str

class SharingInvitation:
    """Sharing invitation details and recipient information."""
    
    email: str
    invited_by: Dict[str, Any]
    redeemed_by: str
    sign_in_required: bool

class Quota:
    """Drive storage quota information."""
    
    deleted: int
    remaining: int
    state: str  # "normal", "nearing", "critical", "exceeded"
    total: int
    used: int

class UploadSession:
    """Large file upload session configuration."""
    
    upload_url: str
    expiration_date_time: str
    next_expected_ranges: List[str]

Install with Tessl CLI

npx tessl i tessl/pypi-office365-rest-python-client

docs

authentication.md

directory-services.md

email-calendar.md

index.md

onedrive-files.md

sharepoint-sites.md

teams.md

tile.json