This script demonstrates some of the basics needed for downloading image files from an O365 SharePoint library to a local Linux directory using Python.
Main process
Get the site id from a JSON file with all lists and libraries related to a host and site name.
site_id = make_request(site_uri).get('id', {})
Use the site id to get a JSON file with all the drives on the site.
drives = make_request(drive_uri)
Loop over the drives to get the drive id of a library by name, e.g. "Images"
drive_id = item.get('id')
Get a JSON list of the files on the library's drive.
items = make_request(items_uri)
Download each item on the list.
download_the_files(items)
Microsoft returns this list as a JSON file containing only 200 results at a time, so look for an @odata.nextLink key in each response for a link to the next page of results.
items_uri = items.get('@odata.nextLink')
Get access token from Microsoft
The get_access_token method makes an OAuth request to Microsoft using an Application (client) ID and a Client secret created in an Azure App registration Service Principal.
CLIENT_ID = The Application (client) ID on the Overview page
CLIENT_SECRET = The client secret created on the Certificates & secrets page
TENANT_ID = The Directory (tenant) ID on the Overview page
All CAPTIALIZED settings should be added as secrets in a production environment.
Make a request
Simplify the code with a reusable make_request method that returns a JSON file.
r = requests.get(url, headers=headers)
Download the files
The download_the_files method downloads an image file using a @microsoft.graph.downloadUrl link provided by the JSON block for each image file. The LOCAL_DIR setting refers to the local Linux download directory relative to the Python script.
