A small Python script that downloads a file from SharePoint Online using Microsoft Graph and an Azure Entra ID application registration.
- Uses MSAL client credentials authentication.
- Reads the client secret from an environment variable.
- Streams the downloaded file to disk.
- Prints token and Microsoft Graph diagnostics without exposing secrets.
- Python 3.9 or newer
- An Azure Entra ID app registration
- Microsoft Graph application permissions, for example
Sites.Read.All - Admin consent granted for the configured application permissions
If your tenant uses Sites.Selected, an administrator must also grant the app access to the specific SharePoint site.
- Create and activate a virtual environment:
python3 -m venv .venv
source .venv/bin/activate- Install dependencies:
pip install -r requirements.txt- Configure the values at the top of
download_spo_file.py:
TENANT_ID = "your-tenant-id"
CLIENT_ID = "your-client-id"
SITE_HOSTNAME = "your-tenant.sharepoint.com"
SITE_PATH = "/sites/your-site"
FILE_PATH = "Shared Documents/path/to/file.txt"
OUTPUT_FILE = "output/file.txt"- Export the client secret:
export AZURE_CLIENT_SECRET="your-client-secret"Run the script:
python download_spo_file.pyThe file is downloaded to the path configured in OUTPUT_FILE.
- Do not commit client secrets, downloaded files, or tenant-specific private configuration.
- Prefer environment variables or your CI/CD secret store for credentials.
- Review Graph permissions before making the repository public.
401or403usually means the app is missing permissions, admin consent, or site-level access.- Check the printed token roles to confirm which Microsoft Graph application roles are present.
- Verify that
SITE_HOSTNAME,SITE_PATH, andFILE_PATHmatch the SharePoint location exactly.