Python SDK for Sirv REST API
pip install sirv-rest-api2. Copy your Client ID and Client secret from Account › Settings › API.3. Connectfrom sirv import SirvClient
client = SirvClient(
client_id="your-client-id",
client_secret="your-client-secret",
)
client.connect() No account yet? Create one freeShort answer
Sirv's official Python SDK wraps the Sirv REST API, so you can upload, download, search and manage files, metadata, spins and account statistics from your code. Install it with pip install sirv-rest-api, then connect with the client ID and secret from your Sirv account's API settings. The SDK gets and refreshes the access token for you.
After reading this you will know
- How to install the SDK and connect to your Sirv account
- Which file, account, statistics and spin methods it offers
- How to handle errors and limits
The official Python SDK provides a Pythonic interface for interacting with the Sirv REST API.
It handles authentication automatically with token refresh and provides generator-based iteration for paginated results.
Resources:
Installation
Section titled “Installation”Install the SDK using pip:
pip install sirv-rest-apiFor async support:
pip install sirv-rest-api[async]Requirements
Section titled “Requirements”- Python 3.8 or higher
requestslibraryrequests-toolbeltfor uploads
Quick Start
Section titled “Quick Start”from sirv import SirvClient
# Initialize the clientclient = SirvClient( client_id="your-client-id", client_secret="your-client-secret")
# Connect to obtain tokenclient.connect()
# Get account informationaccount = client.get_account_info()print(f"Account: {account['alias']}")
# List files in a directorycontents = client.read_folder_contents("/")for file in contents["contents"]: print(file["filename"])Authentication
Section titled “Authentication”The SDK handles authentication automatically. When you call connect(), it obtains an access token using your client credentials. The token is automatically refreshed before it expires.
client = SirvClient( client_id="your-client-id", client_secret="your-client-secret", auto_refresh_token=True # Default: automatically refresh before expiry)
# Connect with default expiryclient.connect()
# Or connect with custom expiry (1 hour)client.connect(expires_in=3600)
# Check if connectedif client.is_connected(): print("Token is valid")
# Get current access token for external usetoken = client.get_access_token()Configuration Options
Section titled “Configuration Options”| Option | Type | Default | Description |
|---|---|---|---|
client_id | str | required | Your API client ID |
client_secret | str | required | Your API client secret |
base_url | str | https://api.sirv.com | API endpoint |
auto_refresh_token | bool | True | Auto-refresh token before expiry |
token_refresh_buffer | int | 60 | Seconds before expiry to refresh token |
timeout | int | 30 | Request timeout in seconds |
max_retries | int | 3 | Retry failed requests |
client = SirvClient( client_id="your-client-id", client_secret="your-client-secret", base_url="https://api.sirv.com", auto_refresh_token=True, token_refresh_buffer=60, timeout=30, max_retries=3)Context Manager
Section titled “Context Manager”Use the context manager for automatic connection and cleanup:
with SirvClient(client_id="client-id", client_secret="client-secret") as client: account = client.get_account_info() print(f"Account: {account['alias']}")# Client automatically disconnectedFiles API
Section titled “Files API”Complete file management including upload, download, copy, rename, delete, and metadata operations.
Available Methods
Section titled “Available Methods”| Category | Methods |
|---|---|
| File Operations | read_folder_contents(), get_file_info(), upload_file(), download_file(), download_file_to(), copy_file(), rename_file(), delete_file(), batch_delete(), create_folder(), fetch_url() |
| Metadata | get_file_meta(), set_file_meta(), get_approval_flag(), set_approval_flag(), get_file_title(), set_file_title(), get_file_description(), set_file_description(), get_file_tags(), add_file_tags(), remove_file_tags(), set_product_meta() |
| Folder Options | get_folder_options(), set_folder_options() |
| Search & Iteration | search_files(), iterate_search_results(), scroll_search(), iterate_folder_contents() |
Basic Operations
Section titled “Basic Operations”# List folder contentscontents = client.read_folder_contents("/images")
# Get file informationinfo = client.get_file_info("/images/photo.jpg")
# Upload a file from byteswith open("/local/path/photo.jpg", "rb") as f: data = f.read()client.upload_file("/images/photo.jpg", data)
# Upload a file from pathclient.upload_file("/images/photo.jpg", "/local/path/photo.jpg")
# Upload a file objectwith open("/local/path/photo.jpg", "rb") as f: client.upload_file("/images/photo.jpg", f)
# Download a file to bytesdata = client.download_file("/images/photo.jpg")
# Download a file to local pathclient.download_file_to("/images/photo.jpg", "/local/downloaded.jpg")
# Copy a fileclient.copy_file("/images/photo.jpg", "/backup/photo.jpg")
# Rename/move a fileclient.rename_file("/images/old-name.jpg", "/images/new-name.jpg")
# Delete a fileclient.delete_file("/images/photo.jpg")
# Batch delete filesclient.batch_delete(["/images/photo1.jpg", "/images/photo2.jpg"])
# Create a folderclient.create_folder("/images/new-folder")
# Fetch file from URLclient.fetch_url("https://example.com/image.jpg", "/images/fetched.jpg")
# Fetch with wait for completionclient.fetch_url("https://example.com/image.jpg", "/images/fetched.jpg", wait=True)Search Files
Section titled “Search Files”# Search filesresults = client.search_files({ "query": "filename:*.jpg", "from": "/images", "size": 100})
# Iterate through search results (auto-pagination)for file in client.iterate_search_results({ "query": "extension:.jpg", "from": "/images"}): print(file["filename"])
# Manual pagination with scrollresults = client.search_files({"query": "*.jpg", "size": 100})while results.get("_scroll_id"): results = client.scroll_search(results["_scroll_id"]) for file in results["hits"]: print(file["filename"])Folder Iteration
Section titled “Folder Iteration”# Iterate through folder contents (auto-pagination)for item in client.iterate_folder_contents("/images"): print(item["filename"])Metadata Operations
Section titled “Metadata Operations”# Get and set file metadatameta = client.get_file_meta("/images/photo.jpg")
client.set_file_meta("/images/photo.jpg", { "title": "My Photo", "description": "A beautiful sunset"})
# Get and set titletitle = client.get_file_title("/images/photo.jpg")client.set_file_title("/images/photo.jpg", "New Title")
# Get and set descriptiondescription = client.get_file_description("/images/photo.jpg")client.set_file_description("/images/photo.jpg", "New Description")
# Manage tagstags = client.get_file_tags("/images/photo.jpg")client.add_file_tags("/images/photo.jpg", ["nature", "sunset", "beach"])client.remove_file_tags("/images/photo.jpg", ["beach"])
# Set product metadataclient.set_product_meta("/images/product.jpg", { "id": "SKU123", "name": "Product Name", "brand": "Brand Name"})
# Approval flagapproved = client.get_approval_flag("/images/photo.jpg")client.set_approval_flag("/images/photo.jpg", True)Folder Options
Section titled “Folder Options”# Get folder optionsoptions = client.get_folder_options("/images")
# Set folder optionsclient.set_folder_options("/images", { "scanSpins": True})Account API
Section titled “Account API”Manage your Sirv account settings and retrieve account information.
| Method | Description |
|---|---|
get_account_info() | Get account information including CDN URL and account name |
get_account_limits() | Get API request limits and usage |
get_storage_info() | Get storage usage information |
get_account_users() | List all account users |
get_billing_plan() | Get billing plan details |
# Get account informationaccount = client.get_account_info()print(f"CDN URL: {account['cdnURL']}")
# Get API limitslimits = client.get_account_limits()print(f"API calls: {limits['used']}/{limits['limit']}")
# Get storage informationstorage = client.get_storage_info()print(f"Storage used: {storage['used']} bytes")
# Get billing planplan = client.get_billing_plan()print(f"Plan: {plan['name']}")
# List account usersusers = client.get_account_users()Statistics API
Section titled “Statistics API”Retrieve usage statistics for your account.
| Method | Description |
|---|---|
get_http_stats() | Get HTTP transfer statistics |
get_spin_views_stats() | Get spin viewer statistics (max 5 days) |
get_storage_stats() | Get storage statistics |
from datetime import date
# HTTP transfer statisticshttp_stats = client.get_http_stats( from_date=date(2024, 1, 1), to_date=date(2024, 1, 31))
# Spin views statistics (max 5 days)spin_stats = client.get_spin_views_stats( from_date=date(2024, 1, 1), to_date=date(2024, 1, 5), alias="account-alias")
# Storage statisticsstorage_stats = client.get_storage_stats( from_date=date(2024, 1, 1), to_date=date(2024, 1, 31))Spins & 360 Views
Section titled “Spins & 360 Views”Convert between spin and video formats, manage points of interest, and export to marketplaces.
# Convert spin to videovideo = client.spin2video({ "filename": "/spins/product.spin"})
# Convert video to spinspin = client.video2spin({ "filename": "/videos/product.mp4"})
# Export spin for marketplacesclient.export_spin_to_amazon(filename="/spins/product.spin")client.export_spin_to_walmart(filename="/spins/product.spin")client.export_spin_to_home_depot(filename="/spins/product.spin")client.export_spin_to_lowes(filename="/spins/product.spin")client.export_spin_to_grainger(filename="/spins/product.spin")
# Get points of interestpois = client.get_points_of_interest("/spins/product.spin")
# Set point of interestclient.set_point_of_interest("/spins/product.spin", { "name": "Feature Highlight", "frame": 10, "x": 0.5, "y": 0.3})
# Delete point of interestclient.delete_point_of_interest("/spins/product.spin", "poi-id")JWT Generation
Section titled “JWT Generation”Generate protected access tokens for secure file access.
jwt = client.generate_jwt({ "filename": "/images/private-photo.jpg", "expiresIn": 3600 # 1 hour})print(f"Protected URL: {jwt['url']}")Error Handling
Section titled “Error Handling”The SDK provides a SirvApiError class for API-specific exceptions.
from sirv import SirvClient, SirvApiError
try: client.upload_file("/images/photo.jpg", data)except SirvApiError as e: print(f"Status: {e.status_code}") print(f"Error code: {e.error_code}") print(f"Message: {e.message}")except Exception as e: print(f"Unexpected error: {e}")SirvApiError Properties
Section titled “SirvApiError Properties”| Property | Description |
|---|---|
status_code | HTTP status code |
error_code | Sirv-specific error code |
message | Error message |
Type Hints
Section titled “Type Hints”The SDK includes full type hints with TypedDict definitions for all response types:
from sirv.types import AccountInfo, FileInfo, SearchResult, PointOfInterest
# IDE will provide autocomplete and type checkingaccount: AccountInfo = client.get_account_info()print(account["cdnURL"]) # Type-safe accessAvailable Types
Section titled “Available Types”AccountInfo,StorageInfo,BillingPlanFileInfo,FolderContents,SearchResultFileMeta,ProductMeta,PointOfInterestHttpStats,SpinViewsStats,StorageStats- And 20+ additional types
