Downloading an Archive of Assets
The Scenario API allows you to efficiently download multiple assets (such as generated images or other files) as a single archive. This is particularly useful for batch processing or when you need to retrieve a large number of files. This guide will walk you through the process of generating and downloading an archive of assets, detailing the necessary steps, API endpoints, and parameters. We will also provide code examples to help you integrate asset archiving into your applications.
π Key Concepts
Section titled βπ Key Conceptsβ-
Asset: Any digital file generated or managed within the Scenario platform, such as an image, video, or 3D model.
-
Archive Generation: The process of bundling multiple individual assets into a single compressed file (e.g., a ZIP file) for easier download and management.
-
Asynchronous Process: Generating an archive is an asynchronous operation, meaning it runs in the background and may take some time to complete, especially for large collections of assets. You will need to poll the API to check the status of the archive generation job.
β‘οΈ Workflow for Downloading an Asset Archive
Section titled ββ‘οΈ Workflow for Downloading an Asset ArchiveβThe general workflow for downloading an archive of assets involves the following steps:
- Launch Archive Generation: Initiate the process of creating an archive by specifying the assets you want to include.
- Monitor Job Status: Periodically check the status of the archive generation job until it is complete.
- Retrieve Archive URL: Once the job is successful, obtain the URL from which you can download the generated archive.
Letβs explore each step in detail.
1. Launch Archive Generation
Section titled β1. Launch Archive GenerationβTo begin, you need to launch the generation of an archive. This involves making a POST request to the /v1/assets/download endpoint (client.assets.download.requestBatch in TypeScript, client.assets.download.request_batch in Python), selecting the assets to include by asset, inference or model ID. You also specify options for the archive, such as a template for file names within the archive or whether to flatten the directory structure. A single request is limited to 1000 assets.
Endpoint:
POST https://api.cloud.scenario.com/v1/assets/download
Request Body Parameters:
| Parameter | Type | Description | Required |
|---|---|---|---|
query |
object | An object containing the criteria for selecting assets to archive. | Yes |
query.assetIds |
array of strings | Asset IDs to include in the archive. Pass an empty array if you select by inference or model only. | Yes |
query.inferenceIds |
array of strings | All assets generated by these inferences are included. Pass an empty array if unused. | Yes |
query.modelIds |
array of strings | All assets generated by these models are included. Pass an empty array if unused. | Yes |
options |
object | An object containing options for the archive generation. | Yes |
options.fileNameTemplate |
string | A template for naming files within the archive, built from <seed>, <num>, <prompt>, <generator>, <id> and <description> (e.g., <description>-<id>). A / creates a subdirectory. |
Yes |
options.flat |
boolean | If true, the archive will have a flat directory structure (no subfolders). |
No |
options.archiveName |
string | Name of the zip file, without the .zip extension (max 128 characters). Defaults to <YYYYMMDD>-export. |
No |
options.preferOriginal |
boolean | If true, assets whose upload was re-encoded on creation (e.g., a .mov stored as mp4) are archived in their originally uploaded format. |
No |
Example Request:
import Scenario from '@scenario-labs/sdk';
// Reads SCENARIO_SDK_API_KEY and SCENARIO_SDK_API_SECRET from the environment.const client = new Scenario();
const { jobId } = await client.assets.download.requestBatch({ query: { assetIds: ['asset_V2anp75qTuKmmHOeInzQhg', 'asset_AnotherAssetId'], // Replace with your actual asset IDs inferenceIds: [], modelIds: [], }, options: { flat: true, fileNameTemplate: '<id>', // Name files by their asset ID },});
console.log(`Archive generation launched. Job ID: ${jobId}`);from scenario_sdk import Scenario
# Reads SCENARIO_SDK_API_KEY and SCENARIO_SDK_API_SECRET from the environment.client = Scenario()
response = client.assets.download.request_batch( query={ "asset_ids": ["asset_V2anp75qTuKmmHOeInzQhg", "asset_AnotherAssetId"], # Replace with your actual asset IDs "inference_ids": [], "model_ids": [], }, options={ "flat": True, "file_name_template": "<id>", # Name files by their asset ID },)
print(f"Archive generation launched. Job ID: {response.job_id}")curl -X POST "https://api.cloud.scenario.com/v1/assets/download" \ -H "Authorization: Basic $(printf '%s:%s' "$SCENARIO_SDK_API_KEY" "$SCENARIO_SDK_API_SECRET" | base64 | tr -d '\n')" \ -H "Content-Type: application/json" \ -d '{ "query": { "assetIds": ["asset_V2anp75qTuKmmHOeInzQhg", "asset_AnotherAssetId"], "inferenceIds": [], "modelIds": [] }, "options": { "flat": true, "fileNameTemplate": "<id>" } }'Upon successful initiation, the API will return a jobId. You will use this jobId to monitor the progress of your archive generation.
2. Monitor Job Status
Section titled β2. Monitor Job StatusβSince archive generation is an asynchronous process, you need to poll the API to check the status of your job. You will make GET requests to the /v1/assets/download/{jobId} endpoint (client.assets.download.getStatus in TypeScript, client.assets.download.get_status in Python) until jobStatus reaches a final status (success, failure, or canceled).
Endpoint:
GET https://api.cloud.scenario.com/v1/assets/download/{jobId}
Path Parameters:
| Parameter | Type | Description | Required |
|---|---|---|---|
jobId |
string | The ID of the archive generation job. | Yes |
The response contains the jobId, the current jobStatus and, once the job has succeeded, the downloadUrl of the archive.
Example Request:
const JOB_FINAL_STATUS = ['success', 'failure', 'canceled'];
const sleep = (duration: number) => new Promise((resolve) => setTimeout(resolve, duration));
const pollArchive = async (jobId: string): Promise<string> => { while (true) { const { jobStatus, downloadUrl } = await client.assets.download.getStatus(jobId); console.log(`Job ${jobId} status: ${jobStatus}`);
if (jobStatus === 'success' && downloadUrl) { return downloadUrl; } if (JOB_FINAL_STATUS.includes(jobStatus)) { throw new Error(`Job ${jobId} ended with status: ${jobStatus}`); } await sleep(3000); // Poll every 3 seconds }};
const downloadUrl = await pollArchive(jobId);import time
JOB_FINAL_STATUS = {"success", "failure", "canceled"}
def poll_archive(job_id: str) -> str: while True: status = client.assets.download.get_status(job_id) print(f"Job {job_id} status: {status.job_status}")
if status.job_status == "success" and status.download_url: return status.download_url if status.job_status in JOB_FINAL_STATUS: raise RuntimeError(f"Job {job_id} ended with status: {status.job_status}") time.sleep(3) # Poll every 3 seconds
download_url = poll_archive(response.job_id)curl "https://api.cloud.scenario.com/v1/assets/download/{jobId}" \ -H "Authorization: Basic $(printf '%s:%s' "$SCENARIO_SDK_API_KEY" "$SCENARIO_SDK_API_SECRET" | base64 | tr -d '\n')"3. Get the Archive from the URL
Section titled β3. Get the Archive from the URLβOnce jobStatus is success, the response contains the downloadUrl from which you can download the generated archive.
Example of successful response:
{ "jobId": "job_archive_example", "jobStatus": "success", "downloadUrl": "https://example.com/your_archive.zip"}You can then use a standard HTTP GET request to download the file from the downloadUrl.
Example Download:
import { writeFile } from 'node:fs/promises';
const response = await fetch(downloadUrl);if (!response.ok) { throw new Error(`Failed to download archive: ${response.statusText}`);}await writeFile('./my_assets_archive.zip', Buffer.from(await response.arrayBuffer()));console.log('Archive downloaded to ./my_assets_archive.zip');import httpx
with httpx.stream("GET", download_url) as response: response.raise_for_status() with open("my_assets_archive.zip", "wb") as file: for chunk in response.iter_bytes(): file.write(chunk)
print("Archive downloaded to my_assets_archive.zip")curl -L -o my_assets_archive.zip "<downloadUrl>"