Upload a file (Python)
This guide shows how to upload a file to the Stonal platform using Python.
Prerequisites
- A valid access token (see Authentication)
- Your organization code (used in the endpoint path)
- Python environment with the
requests
library installed
Upload example
Here's a simple Python example that uploads a file using streaming to minimize memory usage:
📄 upload.py
#!/usr/bin/env python3
import json
import requests
from typing import Dict, Any
def upload_file(
organization_code: str,
access_token: str,
file_path: str,
file_mime_type: str,
manifest_data: Dict[str, Any],
env: str = "prod",
) -> Dict[str, Any]:
"""
Upload a file to Stonal platform using streaming to avoid loading entire file in memory.
Args:
organization_code: Your organization code
access_token: OAuth access token
file_path: Path to the file to upload
manifest_data: Manifest JSON data as Python dictionary
Returns:
Response JSON containing documentUid and duplicateDocumentIds
"""
domain: str = {
"prod": "stonal.io",
"staging": "stonal-staging.io",
"test": "stonal-test.io",
"dev": "stonal-dev.io",
}[env]
url = f"https://api.{domain}/document-storage/v1/organizations/{organization_code}/files/upload"
headers: Dict[str, str] = {"Authorization": f"Bearer {access_token}"}
# Create manifest JSON string
manifest_json: str = json.dumps(manifest_data)
# Open file in binary mode for streaming
with open(file_path, "rb") as file:
files = {
"manifest": ("manifest.json", manifest_json, "application/json"),
"file": (file_path.split("/")[-1], file, file_mime_type),
}
response: requests.Response = requests.post(url, headers=headers, files=files)
response.raise_for_status()
return response.json()
# Example usage
def main():
# Example manifest for asset + documentation strategy
manifest: Dict[str, Any] = {
"asset": {"uid": "ac6d8be3-5036-47be-a010-eb3bbe0d7ae8"},
"documentation": {"uid": "dbce00ca-3540-4d1c-a11c-5474400d2b19"},
}
try:
result: Dict[str, Any] = upload_file(
organization_code="DEMO",
access_token="33286103-9b5b-43c8-9183-89b869f88861",
file_path="document.pdf",
file_mime_type="application/pdf",
manifest_data=manifest,
)
print(f"Upload successful! Document UID: {result['documentId']}")
if result.get("duplicateDocumentIds"):
print(f"Duplicate documents found: {result['duplicateDocumentIds']}")
except requests.exceptions.HTTPError as e:
print(f"Upload failed: {e}")
print(f"Response: {e.response.reason}")
if __name__ == "__main__":
main()
Notes
- Memory efficient: Uses file streaming to avoid loading the entire file into memory
- Error handling: Proper HTTP error handling with detailed responses
For complete manifest options, refer to the Upload a file documentation.