# Python SDK for Sirv REST API

The official Python SDK provides a Pythonic interface for interacting with the [Sirv REST API](/help/rest-api/reference/).

Using an AI coding agent?

Install the [`sirv-api`](https://www.skills.sh/sirv/image-optimization-skill/sirv-api) skill, and your agent can call the Sirv API for you. Ask in plain words, such as “Upload the photos in /shoots/spring and tag them by product.” [See all 8 skills](/help/rest-api/sirv-skills-for-ai-agents/)

It handles authentication automatically with token refresh and provides generator-based iteration for paginated results.

**Resources:**

-   [GitHub Repository](https://github.com/sirv/sirv-rest-api-python)
-   [PyPI Package](https://pypi.org/project/sirv-rest-api/)
-   [API Documentation](/help/rest-api/reference/)

## Installation

Install the SDK using pip:

```bash
pip install sirv-rest-api
```

For async support:

```bash
pip install sirv-rest-api[async]
```

### Requirements

-   Python 3.8 or higher
-   `requests` library
-   `requests-toolbelt` for uploads

## Quick Start

```python
from sirv import SirvClient

# Initialize the client
client = SirvClient(
    client_id="your-client-id",
    client_secret="your-client-secret"
)

# Connect to obtain token
client.connect()

# Get account information
account = client.get_account_info()
print(f"Account: {account['alias']}")

# List files in a directory
contents = client.read_folder_contents("/")
for file in contents["contents"]:
    print(file["filename"])
```

## 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.

Tip

Get your API credentials from [Settings > API access](https://app.sirv.com/settings/api) in your Sirv account.

```python
client = SirvClient(
    client_id="your-client-id",
    client_secret="your-client-secret",
    auto_refresh_token=True  # Default: automatically refresh before expiry
)

# Connect with default expiry
client.connect()

# Or connect with custom expiry (1 hour)
client.connect(expires_in=3600)

# Check if connected
if client.is_connected():
    print("Token is valid")

# Get current access token for external use
token = client.get_access_token()
```

### 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 |

```python
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

Use the context manager for automatic connection and cleanup:

```python
with SirvClient(client_id="client-id", client_secret="client-secret") as client:
    account = client.get_account_info()
    print(f"Account: {account['alias']}")
# Client automatically disconnected
```

## Files API

Complete file management including upload, download, copy, rename, delete, and metadata operations.

### 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

```python
# List folder contents
contents = client.read_folder_contents("/images")

# Get file information
info = client.get_file_info("/images/photo.jpg")

# Upload a file from bytes
with open("/local/path/photo.jpg", "rb") as f:
    data = f.read()
client.upload_file("/images/photo.jpg", data)

# Upload a file from path
client.upload_file("/images/photo.jpg", "/local/path/photo.jpg")

# Upload a file object
with open("/local/path/photo.jpg", "rb") as f:
    client.upload_file("/images/photo.jpg", f)

# Download a file to bytes
data = client.download_file("/images/photo.jpg")

# Download a file to local path
client.download_file_to("/images/photo.jpg", "/local/downloaded.jpg")

# Copy a file
client.copy_file("/images/photo.jpg", "/backup/photo.jpg")

# Rename/move a file
client.rename_file("/images/old-name.jpg", "/images/new-name.jpg")

# Delete a file
client.delete_file("/images/photo.jpg")

# Batch delete files
client.batch_delete(["/images/photo1.jpg", "/images/photo2.jpg"])

# Create a folder
client.create_folder("/images/new-folder")

# Fetch file from URL
client.fetch_url("https://example.com/image.jpg", "/images/fetched.jpg")

# Fetch with wait for completion
client.fetch_url("https://example.com/image.jpg", "/images/fetched.jpg", wait=True)
```

### Search Files

```python
# Search files
results = 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 scroll
results = 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

```python
# Iterate through folder contents (auto-pagination)
for item in client.iterate_folder_contents("/images"):
    print(item["filename"])
```

### Metadata Operations

```python
# Get and set file metadata
meta = client.get_file_meta("/images/photo.jpg")

client.set_file_meta("/images/photo.jpg", {
    "title": "My Photo",
    "description": "A beautiful sunset"
})

# Get and set title
title = client.get_file_title("/images/photo.jpg")
client.set_file_title("/images/photo.jpg", "New Title")

# Get and set description
description = client.get_file_description("/images/photo.jpg")
client.set_file_description("/images/photo.jpg", "New Description")

# Manage tags
tags = 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 metadata
client.set_product_meta("/images/product.jpg", {
    "id": "SKU123",
    "name": "Product Name",
    "brand": "Brand Name"
})

# Approval flag
approved = client.get_approval_flag("/images/photo.jpg")
client.set_approval_flag("/images/photo.jpg", True)
```

### Folder Options

```python
# Get folder options
options = client.get_folder_options("/images")

# Set folder options
client.set_folder_options("/images", {
    "scanSpins": True
})
```

## 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](/help/getting-started/account-name-subdomain/) |
| `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 |

```python
# Get account information
account = client.get_account_info()
print(f"CDN URL: {account['cdnURL']}")

# Get API limits
limits = client.get_account_limits()
print(f"API calls: {limits['used']}/{limits['limit']}")

# Get storage information
storage = client.get_storage_info()
print(f"Storage used: {storage['used']} bytes")

# Get billing plan
plan = client.get_billing_plan()
print(f"Plan: {plan['name']}")

# List account users
users = client.get_account_users()
```

## 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 |

```python
from datetime import date

# HTTP transfer statistics
http_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 statistics
storage_stats = client.get_storage_stats(
    from_date=date(2024, 1, 1),
    to_date=date(2024, 1, 31)
)
```

## Spins & 360 Views

Convert between spin and video formats, manage points of interest, and export to marketplaces.

```python
# Convert spin to video
video = client.spin2video({
    "filename": "/spins/product.spin"
})

# Convert video to spin
spin = client.video2spin({
    "filename": "/videos/product.mp4"
})

# Export spin for marketplaces
client.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 interest
pois = client.get_points_of_interest("/spins/product.spin")

# Set point of interest
client.set_point_of_interest("/spins/product.spin", {
    "name": "Feature Highlight",
    "frame": 10,
    "x": 0.5,
    "y": 0.3
})

# Delete point of interest
client.delete_point_of_interest("/spins/product.spin", "poi-id")
```

## JWT Generation

Generate protected access tokens for secure file access.

```python
jwt = client.generate_jwt({
    "filename": "/images/private-photo.jpg",
    "expiresIn": 3600  # 1 hour
})
print(f"Protected URL: {jwt['url']}")
```

## Error Handling

The SDK provides a `SirvApiError` class for API-specific exceptions.

```python
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

| Property | Description |
| --- | --- |
| `status_code` | HTTP status code |
| `error_code` | Sirv-specific error code |
| `message` | Error message |

## Type Hints

The SDK includes full type hints with TypedDict definitions for all response types:

```python
from sirv.types import AccountInfo, FileInfo, SearchResult, PointOfInterest

# IDE will provide autocomplete and type checking
account: AccountInfo = client.get_account_info()
print(account["cdnURL"])  # Type-safe access
```

### Available Types

-   `AccountInfo`, `StorageInfo`, `BillingPlan`
-   `FileInfo`, `FolderContents`, `SearchResult`
-   `FileMeta`, `ProductMeta`, `PointOfInterest`
-   `HttpStats`, `SpinViewsStats`, `StorageStats`
-   And 20+ additional types
