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

authentication.mddocs/

Authentication & Client Setup

Comprehensive authentication support for Microsoft 365 services with multiple authentication flows designed for enterprise environments. The library supports both modern OAuth2 flows for Microsoft Graph and legacy authentication methods for SharePoint REST API.

Capabilities

GraphClient Authentication

Microsoft Graph API client with support for OAuth2 flows including client credentials, certificate-based authentication, interactive authentication, and device code flow.

class GraphClient:
    def __init__(self, tenant: str = None, scopes: List[str] = None, token_cache=None, environment=None):
        """
        Initialize Microsoft Graph client.
        
        Args:
            tenant (str, optional): Azure AD tenant ID or domain name
            scopes (List[str], optional): OAuth2 scopes to request
            token_cache (optional): Token cache for storing authentication tokens
            environment (AzureEnvironment, optional): Azure cloud environment
        """
    
    def with_client_secret(self, client_id: str, client_secret: str) -> 'GraphClient':
        """
        Authenticate using client credentials flow (app-only authentication).
        
        Args:
            client_id (str): Azure AD application client ID
            client_secret (str): Azure AD application client secret
            
        Returns:
            GraphClient: Self for method chaining
        """
    
    def with_certificate(self, client_id: str, thumbprint: str, private_key: str) -> 'GraphClient':
        """
        Authenticate using certificate-based authentication.
        
        Args:
            client_id (str): Azure AD application client ID
            thumbprint (str): Certificate thumbprint (SHA-1 hash)
            private_key (str): PEM-formatted private key
            
        Returns:
            GraphClient: Self for method chaining
        """
    
    def with_token_interactive(self, client_id: str, username: str = None) -> 'GraphClient':
        """
        Authenticate using interactive browser flow.
        
        Args:
            client_id (str): Azure AD application client ID
            username (str, optional): Username hint for login
            
        Returns:
            GraphClient: Self for method chaining
        """
    
    def with_username_and_password(self, client_id: str, username: str, password: str) -> 'GraphClient':
        """
        Authenticate using username and password (resource owner password credentials flow).
        
        Args:
            client_id (str): Azure AD application client ID
            username (str): User's username or email
            password (str): User's password
            
        Returns:
            GraphClient: Self for method chaining
        """
    
    def with_device_flow(self, tenant: str, client_id: str, scopes: List[str] = None) -> 'GraphClient':
        """
        Authenticate using device code flow for devices without web browsers.
        
        Args:
            tenant (str): Azure AD tenant ID or domain name
            client_id (str): Azure AD application client ID
            scopes (List[str], optional): OAuth2 scopes to request
            
        Returns:
            GraphClient: Self for method chaining
        """
    
    def with_access_token(self, token_func: Callable[[], dict]) -> 'GraphClient':
        """
        Authenticate using custom token provider callback.
        
        Args:
            token_func (Callable): Function that returns token dictionary
            
        Returns:
            GraphClient: Self for method chaining
        """

SharePoint ClientContext Authentication

SharePoint REST API client with support for modern OAuth2 flows and legacy authentication methods including NTLM and digest authentication.

class ClientContext:
    def __init__(self, site_url: str):
        """
        Initialize SharePoint client context.
        
        Args:
            site_url (str): SharePoint site URL
        """
    
    def with_client_credentials(self, client_id: str, client_secret: str) -> 'ClientContext':
        """
        Authenticate using OAuth2 client credentials flow.
        
        Args:
            client_id (str): Azure AD application client ID
            client_secret (str): Azure AD application client secret
            
        Returns:
            ClientContext: Authenticated SharePoint client
        """
    
    def with_client_certificate(self, tenant: str, client_id: str, thumbprint: str, cert_path: str = None, private_key: str = None, scopes: List[str] = None, passphrase: str = None) -> 'ClientContext':
        """
        Authenticate using certificate-based authentication.
        
        Args:
            tenant (str): Azure AD tenant ID or domain name
            client_id (str): Azure AD application client ID
            thumbprint (str): Certificate thumbprint (SHA-1 hash)
            cert_path (str, optional): Path to certificate file
            private_key (str, optional): PEM-formatted private key
            scopes (List[str], optional): OAuth2 scopes to request
            passphrase (str, optional): Certificate passphrase if encrypted
            
        Returns:
            ClientContext: Authenticated SharePoint client
        """
    
    def with_interactive(self, tenant: str, client_id: str, scopes: List[str] = None) -> 'ClientContext':
        """
        Authenticate using interactive browser flow.
        
        Args:
            tenant (str): Azure AD tenant ID or domain name
            client_id (str): Azure AD application client ID
            scopes (List[str], optional): OAuth2 scopes to request
            
        Returns:
            ClientContext: Authenticated SharePoint client
        """
    
    def with_user_credentials(self, username: str, password: str) -> 'ClientContext':
        """
        Authenticate using username and password.
        
        Args:
            username (str): User's username or email
            password (str): User's password
            
        Returns:
            ClientContext: Authenticated SharePoint client
        """
    
    def with_ntlm(self, username: str, password: str) -> 'ClientContext':
        """
        Authenticate using NTLM authentication (for on-premises SharePoint).
        
        Args:
            username (str): Domain\\username or username@domain
            password (str): User's password
            
        Returns:
            ClientContext: Authenticated SharePoint client
        """
    
    def with_digest(self, username: str, password: str) -> 'ClientContext':
        """
        Authenticate using digest authentication.
        
        Args:
            username (str): User's username
            password (str): User's password
            
        Returns:
            ClientContext: Authenticated SharePoint client
        """
    
    def with_access_token(self, token_func: Callable[[], dict]) -> 'ClientContext':
        """
        Authenticate using custom token provider callback.
        
        Args:
            token_func (Callable): Function that returns token dictionary
            
        Returns:
            ClientContext: Authenticated SharePoint client
        """
    
    def with_device_flow(self, tenant: str, client_id: str, scopes: List[str] = None) -> 'ClientContext':
        """
        Authenticate using device code flow for devices without web browsers.
        
        Args:
            tenant (str): Azure AD tenant ID or domain name
            client_id (str): Azure AD application client ID
            scopes (List[str], optional): OAuth2 scopes to request
            
        Returns:
            ClientContext: Authenticated SharePoint client
        """
    
    def with_credentials(self, credentials: Union[UserCredential, ClientCredential]) -> 'ClientContext':
        """
        Authenticate using credential object.
        
        Args:
            credentials (Union[UserCredential, ClientCredential]): Pre-configured credential object
            
        Returns:
            ClientContext: Authenticated SharePoint client
        """

Authentication Context Management

Core authentication infrastructure supporting multiple credential types and token management.

class AuthenticationContext:
    """Core authentication management with support for multiple auth flows."""
    
    def __init__(self, authority_url: str):
        """
        Initialize authentication context.
        
        Args:
            authority_url (str): Azure AD authority URL
        """
    
    def acquire_token_for_client(self, client_id: str, client_secret: str, resource: str) -> Dict[str, Any]:
        """
        Acquire token using client credentials flow.
        
        Returns:
            Dict containing access_token, token_type, expires_in
        """

class ClientCredential:
    """Client credentials authentication."""
    
    def __init__(self, client_id: str, client_secret: str):
        """
        Initialize client credentials.
        
        Args:
            client_id (str): Application client ID
            client_secret (str): Application client secret
        """

class UserCredential:
    """User credentials authentication."""
    
    def __init__(self, username: str, password: str):
        """
        Initialize user credentials.
        
        Args:
            username (str): User's username or email
            password (str): User's password
        """

class CertificateCredential:
    """Certificate-based authentication."""
    
    def __init__(self, client_id: str, thumbprint: str, private_key: str):
        """
        Initialize certificate credentials.
        
        Args:
            client_id (str): Application client ID
            thumbprint (str): Certificate thumbprint
            private_key (str): PEM-formatted private key
        """

class InteractiveCredential:
    """Interactive browser authentication."""
    
    def __init__(self, client_id: str, tenant: str = None):
        """
        Initialize interactive credentials.
        
        Args:
            client_id (str): Application client ID
            tenant (str, optional): Tenant ID or domain
        """

Azure Environment Configuration

Configuration for different Azure cloud environments with appropriate endpoints and settings.

class AzureEnvironment:
    """Azure cloud environment configuration with appropriate endpoints."""
    
    @property
    def authority_host_url(self) -> str:
        """Azure AD authority host URL for the environment."""
    
    @property
    def graph_endpoint_url(self) -> str:
        """Microsoft Graph API endpoint URL for the environment."""
    
    @property
    def sharepoint_principal_id(self) -> str:
        """SharePoint service principal ID for the environment."""

# Pre-configured environments
AzureEnvironment.Global: AzureEnvironment  # Azure Global cloud (default)
AzureEnvironment.China: AzureEnvironment   # Azure China (21Vianet)
AzureEnvironment.USGovernment: AzureEnvironment  # Azure US Government
AzureEnvironment.Germany: AzureEnvironment  # Azure Germany

Usage Examples

Client Credentials Flow (Server-to-Server)

from office365.graph_client import GraphClient
from office365.sharepoint.client_context import ClientContext

# Microsoft Graph API
graph_client = GraphClient(tenant="your-tenant-id").with_client_secret(
    client_id="your-app-id",
    client_secret="your-app-secret"
)

# SharePoint REST API
sharepoint_ctx = ClientContext("https://tenant.sharepoint.com/sites/sitename").with_client_credentials(
    client_id="your-app-id",
    client_secret="your-app-secret"
)

Certificate-Based Authentication

# Load certificate
with open("private_key.pem", "r") as key_file:
    private_key = key_file.read()

# Microsoft Graph with certificate
graph_client = GraphClient(tenant="your-tenant-id").with_certificate(
    client_id="your-app-id",
    thumbprint="certificate-thumbprint",
    private_key=private_key
)

# SharePoint with certificate
sharepoint_ctx = ClientContext("https://tenant.sharepoint.com/sites/sitename").with_client_certificate(
    tenant="your-tenant-id",
    client_id="your-app-id", 
    thumbprint="certificate-thumbprint",
    private_key=private_key
)

Interactive Authentication

# Interactive login for Microsoft Graph
graph_client = GraphClient(tenant="your-tenant-id").with_token_interactive(
    client_id="your-app-id",
    username="user@domain.com"  # Optional username hint
)

# Interactive login for SharePoint
sharepoint_ctx = ClientContext("https://tenant.sharepoint.com/sites/sitename").with_interactive(
    tenant="your-tenant-id",
    client_id="your-app-id"
)

Username/Password Authentication

# Microsoft Graph with user credentials
graph_client = GraphClient(tenant="your-tenant-id").with_username_and_password(
    client_id="your-app-id",
    username="user@domain.com",
    password="user-password"
)

# SharePoint with user credentials
sharepoint_ctx = ClientContext("https://tenant.sharepoint.com/sites/sitename").with_user_credentials(
    username="user@domain.com",
    password="user-password"
)

Custom Token Provider

def custom_token_provider():
    # Your custom logic to acquire token
    return {
        "access_token": "your-access-token",
        "token_type": "Bearer",
        "expires_in": 3600
    }

# Use custom token provider
graph_client = GraphClient().with_token_callback(custom_token_provider)

Types

from typing import Dict, Any, Callable, List, Optional

class ClientRequestException(Exception):
    """Exception raised for API request errors."""
    
    def __init__(self, message: str, response: Dict[str, Any] = None):
        """
        Initialize request exception.
        
        Args:
            message (str): Error message
            response (Dict, optional): HTTP response details
        """

class RequestOptions:
    """Configuration options for HTTP requests."""
    
    def __init__(self):
        self.headers: Dict[str, str] = {}
        self.timeout: int = 30
        self.retry_count: int = 3
        self.stream: bool = False
        
class ClientResult:
    """Container for API response data."""
    
    def __init__(self, value: Any = None):
        self.value: Any = value

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