# Ruby SDK for Sirv REST API

The official Ruby SDK provides a clean Ruby 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 uses only Ruby’s standard library with no external dependencies.

**Resources:**

-   [GitHub Repository](https://github.com/sirv/sirv-rest-api-ruby)
-   [RubyGems Package](https://rubygems.org/gems/sirv_rest_api)
-   [API Documentation](/help/rest-api/reference/)

## Installation

Install the SDK via RubyGems:

```bash
gem install sirv_rest_api
```

Or add to your Gemfile:

```ruby
gem 'sirv_rest_api'
```

### Requirements

-   Ruby 2.7 or higher
-   No external dependencies (uses Ruby stdlib only)

## Quick Start

```ruby
require 'sirv_rest_api'

# Initialize the client
client = SirvRestApi::Client.new(
  client_id: 'your-client-id',
  client_secret: 'your-client-secret'
)

# Connect (authenticate)
token = client.connect
puts "Connected! Token expires in #{token.expires_in} seconds"

# Get account information
account = client.get_account_info
puts "Account: #{account.alias}"
puts "CDN URL: #{account.cdn_url}"

# List files in a directory
folder = client.read_folder_contents('/')
folder.contents.each do |file|
  puts file.filename
end
```

## Authentication

The SDK handles authentication automatically. When you make your first API call, it obtains an access token using your client credentials.

The token is automatically refreshed when it expires.

Tip

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

```ruby
client = SirvRestApi::Client.new(
  client_id: 'your-client-id',
  client_secret: 'your-client-secret'
)

# Connect and get token
token = client.connect
puts "Scopes: #{token.scope.join(', ')}"

# Request a token with custom expiry time (5-604800 seconds)
token = client.connect(expires_in: 3600) # Token valid for 1 hour

# Check if connected
client.connected? # => true

# Get current token
client.access_token
```

### Configuration Options

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `client_id` | String | required | Your Sirv API client ID |
| `client_secret` | String | required | Your Sirv API client secret |
| `base_url` | String | `https://api.sirv.com` | Base URL for API requests |
| `auto_refresh_token` | Boolean | `true` | Automatically refresh token before expiry |
| `token_refresh_buffer` | Integer | `60` | Seconds before expiry to trigger refresh |
| `timeout` | Integer | `30` | Request timeout in seconds |
| `max_retries` | Integer | `3` | Maximum retries for 5xx errors |

```ruby
client = SirvRestApi::Client.new(
  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
)
```

## 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`, `copy_file`, `rename_file`, `delete_file`, `create_folder`, `fetch_url` |
| **Metadata** | `get_file_meta`, `set_file_meta`, `get_file_title`, `set_file_title`, `get_file_description`, `set_file_description`, `get_file_tags`, `add_file_tags`, `get_product_meta`, `set_product_meta`, `get_approval_flag`, `set_approval_flag` |
| **Batch Operations** | `batch_zip`, `get_zip_status`, `batch_delete`, `get_batch_delete_status` |
| **Spins & Export** | `spin_to_video`, `video_to_spin`, `export_spin_to_amazon`, `export_spin_to_walmart`, `export_spin_to_home_depot`, `export_spin_to_lowes`, `export_spin_to_grainger` |

### Basic Operations

```ruby
# List folder contents
folder = client.read_folder_contents('/images')
folder.contents.each { |f| puts f.filename }

# Iterate through all items (handles pagination)
client.each_folder_item('/images') do |file|
  puts file.filename
end

# Upload a file
client.upload_file_from_path('/images/photo.jpg', './local-photo.jpg')

# Download a file
content = client.download_file('/images/photo.jpg')
File.binwrite('downloaded.jpg', content)

# Copy a file
client.copy_file(from: '/images/photo.jpg', to: '/backup/photo.jpg')

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

### Search Files

```ruby
# Search files
results = client.search_files(query: '*.jpg', size: 100)
puts "Found #{results.total} files"

# Iterate through all search results (handles pagination)
client.each_search_result(query: '*') do |file|
  puts file.filename
end
```

### Metadata Operations

```ruby
# Set file metadata
client.set_file_meta('/images/photo.jpg', {
  title: 'My Photo',
  description: 'A beautiful sunset'
})

# Set tags
client.add_file_tags('/images/photo.jpg', ['nature', 'sunset'])

# Set product metadata
client.set_product_meta('/images/product.jpg', {
  id: 'SKU123',
  name: 'Product Name',
  brand: 'Brand Name'
})
```

### JWT Protected URLs

```ruby
jwt = client.generate_jwt(
  filename: '/protected/image.jpg',
  expires_in: 3600 # 1 hour
)
puts "Protected URL: #{jwt.url}"
```

## 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/) |
| `update_account(options)` | Update account settings (minify, fetching) |
| `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 |
| `search_events(params)` | Search account events |
| `mark_events_seen(event_ids)` | Mark events as seen |

```ruby
# Get account information
account = client.get_account_info
puts "CDN URL: #{account.cdn_url}"

# Get API limits
limits = client.get_account_limits
if limits.rest
  puts "REST API: #{limits.rest.remaining}/#{limits.rest.limit}"
end

# Get storage information
storage = client.get_storage_info
puts "Storage used: #{storage.used} bytes"

# Search account events
events = client.search_events(level: 'error')
```

## Statistics API

Retrieve usage statistics for your account.

| Method | Description |
| --- | --- |
| `get_http_stats(from:, to:)` | Get HTTP transfer statistics |
| `get_spin_views_stats(from:, to:)` | Get spin viewer statistics (max 5 days) |
| `get_storage_stats(from:, to:)` | Get storage statistics |

```ruby
# HTTP transfer statistics
http_stats = client.get_http_stats(from: '2024-01-01', to: '2024-01-31')

# Storage statistics
storage_stats = client.get_storage_stats(from: '2024-01-01', to: '2024-01-31')

# Spin views (max 5-day range)
spin_stats = client.get_spin_views_stats(from: '2024-01-01', to: '2024-01-05')
```

## Error Handling

The SDK provides specific exception types for different error scenarios.

| Exception | Description |
| --- | --- |
| `SirvRestApi::AuthenticationError` | Invalid credentials or authentication failed (401) |
| `SirvRestApi::NotFoundError` | Resource not found (404) |
| `SirvRestApi::RateLimitError` | Rate limit exceeded (429) |
| `SirvRestApi::ValidationError` | Invalid request parameters (400) |
| `SirvRestApi::ApiError` | General API errors |

```ruby
begin
  account = client.get_account_info
rescue SirvRestApi::AuthenticationError => e
  puts "Auth error: #{e.message}"
rescue SirvRestApi::NotFoundError => e
  puts "Not found: #{e.message}"
rescue SirvRestApi::RateLimitError => e
  puts "Rate limited: #{e.message}"
rescue SirvRestApi::ApiError => e
  puts "API error: #{e.message} (status #{e.status_code})"
end
```

### ApiError Properties

| Property | Description |
| --- | --- |
| `status_code` | HTTP status code |
| `error_code` | API error code (if any) |
| `message` | Error message |

Check the status code and message to see why a request failed.
