CloudConvert Python SDK
The `cloudconvert` library is the official Python SDK for the CloudConvert API v2, providing a convenient wrapper to convert, optimize, and manipulate various file formats programmatically. As of version 2.1.0, it supports features like Signed URLs and improved synchronous API endpoints for job and task waiting. The library is under active development, with major releases often coinciding with updates to the underlying CloudConvert API.
Common errors
-
KeyError: 'tasks'
cause Attempting to access `job['tasks']` from a job object created with an incorrect payload structure or a malformed API response.fixEnsure the `payload` argument to `cloudconvert.Job.create()` is correctly formatted, always including a top-level `'tasks'` key. If iterating a job response, ensure the job has been properly fetched and contains the 'tasks' key. -
KeyError: 'id' (when calling Task.wait)
cause Attempting to call `cloudconvert.Task.wait()` with a job ID instead of a task ID.fixThe `Task.wait()` method expects the ID of a specific task. If you have a job object, extract the relevant task's ID (e.g., `task_id = job['tasks'][0]['id']`) before passing it to `Task.wait()`. For waiting on the entire job, use `cloudconvert.Job.wait(id=job['id'])`. -
CloudConvertClientError: Invalid API Key or missing API Key
cause The API key provided is invalid, expired, or not set. This can also happen if the `CLOUDCONVERT_API_KEY` environment variable is not set and `cloudconvert.configure()` is not called explicitly.fixVerify your API key on the CloudConvert dashboard and ensure it's correctly passed to `cloudconvert.configure(api_key='YOUR_API_KEY')` or set as the `CLOUDCONVERT_API_KEY` environment variable for `cloudconvert.default()`. -
CloudConvertClientError: Unable to convert (various error codes like 86, 87, 88, 91)
cause These generic 'Unable to convert' errors, especially with V1 error codes, often indicate issues with the input file, exceeding conversion time limits, or attempting to use a deprecated API v1 feature.fixCheck the specific error message for details. For V1 error codes, ensure you have fully migrated to API v2. Verify the input file path, format, and size. Increase conversion timeout if possible or simplify the conversion.
Warnings
- breaking CloudConvert API v1 reached End of Life (EOL) on January 1, 2022. All existing integrations using API v1 must be migrated to API v2. The API v2 has a completely different design and requires significant code changes.
- gotcha Incorrectly attempting to wait for a job using `cloudconvert.Task.wait(id=job['id'])` will result in a `KeyError: 'id'` if `job` is the full job object. The `wait` methods expect a task ID, not a job ID directly.
- gotcha The `cloudconvert.Job.create()` method requires a `payload` dictionary with a specific structure, including a top-level `"tasks"` key containing task definitions. Missing or incorrectly structuring this payload will lead to errors like `KeyError: 'tasks'` or invalid job creation.
- gotcha Although the SDK is designed to handle filenames with spaces, some users have reported `ERROR INPUT_TASK_FAILED` when uploading files with spaces in their names. This can be an elusive issue.
Install
-
pip install cloudconvert
Imports
- cloudconvert
import cloudconvert
- Job
from cloudconvert import Job
import cloudconvert cloudconvert.Job.create(...)
- Task
from cloudconvert import Task
import cloudconvert cloudconvert.Task.wait(...)
Quickstart
import cloudconvert
import os
# Configure CloudConvert with your API key from environment variable
# Get your API key at https://cloudconvert.com/dashboard/api/v2/keys
CLOUDCONVERT_API_KEY = os.environ.get('CLOUDCONVERT_API_KEY', 'YOUR_API_KEY')
if CLOUDCONVERT_API_KEY == 'YOUR_API_KEY' or not CLOUDCONVERT_API_KEY:
print("Warning: CLOUDCONVERT_API_KEY not set. Using a placeholder. Set the environment variable or replace 'YOUR_API_KEY'.")
# For demonstration, proceed with placeholder; in production, exit or raise error.
# For actual usage, ensure a valid API key is present.
cloudconvert.configure(api_key=CLOUDCONVERT_API_KEY, sandbox=False)
try:
# Create a job to convert a URL to PDF
job = cloudconvert.Job.create(payload={
"tasks": {
'import-from-url': {
'operation': 'import/url',
'url': 'https://www.example.com/sample.html'
},
'convert-to-pdf': {
'operation': 'convert',
'input': ['import-from-url'],
'output_format': 'pdf'
},
'export-to-url': {
'operation': 'export/url',
'input': ['convert-to-pdf']
}
}
})
# Wait for the job to complete
job = cloudconvert.Job.wait(id=job['id'])
# Download the output file
for task in job["tasks"]:
if task.get("name") == "export-to-url" and task.get("status") == "finished":
export_task = task
# Assuming a single file is exported for simplicity
file = export_task["result"]["files"][0]
# Create a 'downloads' directory if it doesn't exist
os.makedirs('downloads', exist_ok=True)
# Download the file to the 'downloads' directory
download_path = os.path.join('downloads', file['filename'])
cloudconvert.download(filename=download_path, url=file['url'])
print(f"Successfully converted and downloaded to: {download_path}")
break
except cloudconvert.exceptions.CloudConvertClientError as e:
print(f"CloudConvert API Error: {e.message}")
except Exception as e:
print(f"An unexpected error occurred: {e}")