Search Tutorials
--Ads--Ingesting Documents from S3, Azure Blob, Google Drive and SharePoint
Load documents from cloud storage and SharePoint into a RAG pipeline with Python SDKs.
In most organisations the documents for a RAG system sit in cloud storage: Amazon S3 buckets, Azure Blob Storage containers, Google Drive folders and SharePoint document libraries. This lesson shows how to list and download files from each with the official Python SDKs or APIs, feed them into the same parsing pipeline, and keep the index in sync as files change.
What you will learn
- How to list and download files from Amazon S3 and Azure Blob Storage
- How to read files from Google Drive, including exporting Google Docs
- How to read SharePoint and OneDrive files through Microsoft Graph
- How to sync only changed files and keep source links for citations
Prerequisites
- Loading Documents and Office Documents
- Access to the storage service, with credentials configured outside your code
The calls below use long-standing SDK and REST APIs (boto3, azure-storage-blob, Google Drive API v3, Microsoft Graph v1.0). They have not been executed against live accounts for this tutorial. Check each provider's documentation for current authentication options and permissions.
The common pattern
Whatever the source, the pipeline is the same: list files with their id, path, size and last-modified time; skip unchanged ones; download the bytes; parse them with the loaders from earlier lessons; and index the chunks with metadata including a link back to the file. Each connector below produces the same simple record:
from dataclasses import dataclass
@dataclass
class RemoteFile:
source: str # "s3", "azure", "gdrive", "sharepoint"
file_id: str # stable id used as the document id
name: str
modified: str # ISO timestamp or version tag from the service
url: str # link for citations
mime_type: str = "" # used by Google Drive exports
The snippets below are parts of one module, cloud_sources.py; import os once at the top.
Amazon S3
pip install boto3
import boto3
s3 = boto3.client("s3") # credentials from AWS config, environment or IAM role
def list_s3(bucket: str, prefix: str = ""):
paginator = s3.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket=bucket, Prefix=prefix):
for obj in page.get("Contents", []):
if obj["Key"].endswith("/"):
continue # folder placeholder
yield RemoteFile("s3", f"s3://{bucket}/{obj['Key']}", obj["Key"],
obj["ETag"], f"s3://{bucket}/{obj['Key']}")
def download_s3(remote: RemoteFile) -> bytes:
bucket, key = remote.file_id.removeprefix("s3://").split("/", 1)
return s3.get_object(Bucket=bucket, Key=key)["Body"].read()
The ETag changes when the content changes, which makes it a good change marker. For event-driven updates, S3 can send event notifications to a queue or function when objects are created or deleted.
Azure Blob Storage
pip install azure-storage-blob azure-identity
import os
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient
blob_service = BlobServiceClient(account_url=os.environ["AZURE_STORAGE_URL"], # https://<account>.blob.core.windows.net
credential=DefaultAzureCredential())
def list_azure(container: str, prefix: str = ""):
container_client = blob_service.get_container_client(container)
for blob in container_client.list_blobs(name_starts_with=prefix):
yield RemoteFile("azure", f"{container}/{blob.name}", blob.name, blob.etag,
f"{container_client.url}/{blob.name}")
def download_azure(remote: RemoteFile) -> bytes:
container, name = remote.file_id.split("/", 1)
return blob_service.get_blob_client(container, name).download_blob().readall()
DefaultAzureCredential picks up a managed identity, environment variables or your Azure CLI login, so no keys appear in code.
Google Drive
pip install google-api-python-client google-auth
import io
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
creds = service_account.Credentials.from_service_account_file(
os.environ["GOOGLE_APPLICATION_CREDENTIALS"],
scopes=["https://www.googleapis.com/auth/drive.readonly"])
drive = build("drive", "v3", credentials=creds)
GOOGLE_EXPORTS = { # native Google formats must be exported
"application/vnd.google-apps.document": "text/plain",
"application/vnd.google-apps.spreadsheet": "text/csv",
"application/vnd.google-apps.presentation": "text/plain",
}
def list_gdrive(folder_id: str):
page_token = None
while True:
response = drive.files().list(
q=f"'{folder_id}' in parents and trashed = false",
fields="nextPageToken, files(id, name, mimeType, modifiedTime, webViewLink)",
pageToken=page_token).execute()
for f in response["files"]:
yield RemoteFile("gdrive", f["id"], f["name"], f["modifiedTime"], f["webViewLink"], f["mimeType"])
page_token = response.get("nextPageToken")
if not page_token:
return
def download_gdrive(remote: RemoteFile) -> bytes:
if remote.mime_type in GOOGLE_EXPORTS:
request = drive.files().export_media(fileId=remote.file_id, mimeType=GOOGLE_EXPORTS[remote.mime_type])
else:
request = drive.files().get_media(fileId=remote.file_id)
buffer = io.BytesIO()
downloader = MediaIoBaseDownload(buffer, request)
done = False
while not done:
_, done = downloader.next_chunk()
return buffer.getvalue()
Share the folder with the service account's email address so it can read it (in Google Workspace, administrators can also grant domain-wide access). Subfolders are files with the folder MIME type; recurse into them. For change tracking, the Drive API's changes feed reports what changed since a saved token.
SharePoint and OneDrive (Microsoft Graph)
pip install msal requests
import msal
import requests
GRAPH = "https://graph.microsoft.com/v1.0"
def graph_token() -> str:
app = msal.ConfidentialClientApplication(
os.environ["AZURE_CLIENT_ID"],
authority=f"https://login.microsoftonline.com/{os.environ['AZURE_TENANT_ID']}",
client_credential=os.environ["AZURE_CLIENT_SECRET"])
result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
return result["access_token"]
def list_sharepoint(site_id: str, folder_path: str = ""):
headers = {"Authorization": f"Bearer {graph_token()}"}
url = (f"{GRAPH}/sites/{site_id}/drive/root:/{folder_path}:/children" if folder_path
else f"{GRAPH}/sites/{site_id}/drive/root/children")
while url:
body = requests.get(url, headers=headers, timeout=30).json()
for item in body.get("value", []):
if "file" in item: # folders have a "folder" facet instead
yield RemoteFile("sharepoint", f"{site_id}|{item['id']}", item["name"],
item["lastModifiedDateTime"], item["webUrl"])
url = body.get("@odata.nextLink") # Graph pagination
def download_sharepoint(remote: RemoteFile) -> bytes:
site_id, item_id = remote.file_id.split("|")
headers = {"Authorization": f"Bearer {graph_token()}"}
response = requests.get(f"{GRAPH}/sites/{site_id}/drive/items/{item_id}/content",
headers=headers, timeout=60)
response.raise_for_status()
return response.content
Register an application in Microsoft Entra ID with the Graph permissions it needs (for example Sites.Read.All, or the narrower Sites.Selected granted to specific sites) and admin consent. Graph's delta query on a drive returns only items changed since the last call, which is the efficient way to sync. Store the client secret in a secrets manager, or use a certificate instead.
Syncing only what changed
import json
from pathlib import Path
SEEN = Path("seen_files.json")
def sync(files, download, parse_and_index, delete_document):
"""files: iterable of RemoteFile. parse_and_index(remote, data) replaces the doc's chunks."""
seen = json.loads(SEEN.read_text()) if SEEN.exists() else {}
current = {}
for remote in files:
current[remote.file_id] = remote.modified
if seen.get(remote.file_id) == remote.modified:
continue # unchanged since last run
parse_and_index(remote, download(remote))
for file_id in set(seen) - set(current):
delete_document(file_id) # removed from the source
SEEN.write_text(json.dumps(current))
Store the file's link (remote.url) in chunk metadata so answers can cite and link to the original. Capture the file's sharing permissions too if users have different access (see Access Control).
Common errors and troubleshooting
- 403 / AccessDenied: the identity lacks read permission on the bucket, container, folder or site.
- Google Docs download fails: native Google formats need
export_media, notget_media. - Only the first page of files: you ignored the continuation token (
nextPageToken,@odata.nextLink). - Huge files time out: stream downloads to disk instead of memory, and set generous read timeouts.
Key takeaways
- Every source follows the same list, skip, download, parse and index pattern.
- Use each provider's identity system (IAM roles, managed identities, service accounts, app registrations); never hard-code keys.
- Use ETags, modified times or delta feeds to process only changed files, and remove deleted ones.
- Keep a link to the original file for citations, and its permissions for access control.
Frequently asked questions
Can I use framework loaders instead?
Yes. LangChain and LlamaIndex have loaders for these services. The code above shows what they do, which helps when you need incremental sync, permissions or custom parsing.
Do managed RAG services read these sources directly?
Often. For example, Bedrock Knowledge Bases can use S3 as a data source and Azure AI Search has indexers for Blob Storage; see RAG with Amazon Bedrock.
Practice exercises
- Index one S3 prefix of PDFs and print a citation link for each answer's sources.
- Rewrite the SharePoint listing to use the drive's delta query and save the delta link between runs.