# Swift SDK for Sirv REST API

The official Swift SDK provides native async/await concurrency 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 features full Codable & Sendable type safety, automatic token management, and AsyncThrowingStream iterators for pagination.

**Resources:**

-   [GitHub Repository](https://github.com/sirv/sirv-rest-api-swift)
-   [API Documentation](/help/rest-api/reference/)

## Features

-   Native Swift async/await concurrency
-   Full Codable & Sendable type safety
-   Automatic token management
-   AsyncThrowingStream iterators for pagination
-   Retry logic with exponential backoff
-   All 50+ API endpoints implemented

## Installation

### Swift Package Manager

Add to your `Package.swift` dependencies:

```swift
.package(url: "https://github.com/sirv/sirv-rest-api-swift.git", from: "1.0.0")
```

Then add to your target dependencies:

```swift
.target(name: "YourApp", dependencies: ["SirvSDK"])
```

## Quick Start

```swift
import SirvSDK

let client = SirvClient(config: SirvClientConfig(
    clientId: "your-client-id",
    clientSecret: "your-client-secret"
))

// Authenticate
try await client.connect()

// Get account info
let account = try await client.getAccountInfo()
print("CDN URL:", account.cdnURL ?? "")

// Upload a file
let imageData = try Data(contentsOf: URL(fileURLWithPath: "./photo.jpg"))
try await client.uploadFile(targetPath: "/images/photo.jpg", data: imageData)

// Search files
let results = try await client.searchFiles(SearchParams(query: "product", size: 20))
print("Found \(results.total) files")

// Iterate with automatic pagination
for try await file in client.iterateSearchResults(SearchParams(query: "*")) {
    print(file.filename ?? "")
}
```

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

```swift
// Default token (20 minutes)
try await client.connect()

// Custom expiry time (1 hour)
try await client.connect(expiresIn: 3600)

// Check if connected
if client.isConnected() {
    print("Connected!")
}

// Get current token
let token = client.getAccessToken()
```

### Configuration Options

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `clientId` | String | required | Your Sirv API client ID |
| `clientSecret` | String | required | Your Sirv API client secret |
| `baseUrl` | String | `https://api.sirv.com` | API base URL |
| `autoRefreshToken` | Bool | `true` | Automatically refresh tokens |
| `tokenRefreshBuffer` | TimeInterval | `60` | Seconds before expiry to refresh |
| `timeout` | TimeInterval | `30` | Request timeout in seconds |
| `maxRetries` | Int | `3` | Max retries for failed requests |

```swift
let client = SirvClient(config: SirvClientConfig(
    clientId: "your-client-id",
    clientSecret: "your-client-secret",
    baseUrl: "https://api.sirv.com",
    autoRefreshToken: true,
    tokenRefreshBuffer: 60,
    timeout: 30,
    maxRetries: 3
))
```

## Files API

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

### Available Methods

| Category | Methods |
| --- | --- |
| **File Operations** | `readFolderContents`, `getFileInfo`, `uploadFile`, `downloadFile`, `copyFile`, `renameFile`, `deleteFile`, `createFolder`, `fetchUrl` |
| **Iteration** | `iterateFolderContents`, `iterateSearchResults` |
| **Metadata** | `getFileMeta`, `setFileMeta`, `getFileTitle`, `setFileTitle`, `getFileDescription`, `setFileDescription`, `getFileTags`, `addFileTags`, `removeFileTags`, `getProductMeta`, `setProductMeta`, `getApprovalFlag`, `setApprovalFlag` |
| **Batch Operations** | `batchZip`, `getZipStatus`, `batchDelete` |
| **Spins & Export** | `spin2Video`, `video2Spin`, `exportSpinToAmazon`, `exportSpinToWalmart`, `exportSpinToHomeDepot`, `exportSpinToLowes`, `exportSpinToGrainger` |

### Basic Operations

```swift
// List folder contents
let folder = try await client.readFolderContents(dirname: "/images")

// Iterate through all items (handles pagination)
for try await file in client.iterateFolderContents(dirname: "/") {
    print(file.filename ?? "")
}

// Get file info
let info = try await client.getFileInfo(filename: "/images/photo.jpg")

// Upload a file
let imageData = try Data(contentsOf: URL(fileURLWithPath: "./photo.jpg"))
try await client.uploadFile(targetPath: "/images/photo.jpg", data: imageData)

// Upload from file path
try await client.uploadFile(targetPath: "/images/photo.jpg", filePath: "./photo.jpg")

// Download a file
let data = try await client.downloadFile(filename: "/images/photo.jpg")

// Download to local path
try await client.downloadFileTo(filename: "/images/photo.jpg", localPath: "./downloaded.jpg")

// Copy a file
try await client.copyFile(CopyParams(from: "/a.jpg", to: "/b.jpg"))

// Rename/move a file
try await client.renameFile(RenameParams(from: "/old.jpg", to: "/new.jpg"))

// Delete a file
try await client.deleteFile(filename: "/images/old-photo.jpg")

// Create a folder
try await client.createFolder(dirname: "/new-folder")

// Batch delete
let result = try await client.batchDelete(filenames: ["/img1.jpg", "/img2.jpg"])
```

### Search Files

```swift
// Search files
let results = try await client.searchFiles(SearchParams(
    query: "product",
    size: 20,
    sort: SortOptions(field: "mtime", order: "desc")
))
print("Found \(results.total) files")

// Iterate through all search results (handles scroll pagination)
for try await file in client.iterateSearchResults(SearchParams(query: "product")) {
    print(file.filename ?? "")
}

// Continue scrolling manually
let moreResults = try await client.scrollSearch(scrollId: results.scrollId!)
```

### Metadata Operations

```swift
// Get/set file metadata
let meta = try await client.getFileMeta(filename: "/images/photo.jpg")

try await client.setFileMeta(filename: "/images/photo.jpg", meta: FileMeta(
    title: "Product Photo",
    description: "Main image",
    tags: ["product", "featured"]
))

// Title
let titleResp = try await client.getFileTitle(filename: "/images/photo.jpg")
try await client.setFileTitle(filename: "/images/photo.jpg", title: "New Title")

// Description
let descResp = try await client.getFileDescription(filename: "/images/photo.jpg")
try await client.setFileDescription(filename: "/images/photo.jpg", description: "New description")

// Tags
let tagsResp = try await client.getFileTags(filename: "/images/photo.jpg")
try await client.addFileTags(filename: "/images/photo.jpg", tags: ["new", "tags"])
try await client.removeFileTags(filename: "/images/photo.jpg", tags: ["old"])

// Product metadata
let product = try await client.getProductMeta(filename: "/products/item.jpg")
try await client.setProductMeta(filename: "/products/item.jpg", meta: ProductMeta(
    id: "SKU-123",
    name: "Product Name",
    brand: "Brand"
))

// Approval flag
let approvalResp = try await client.getApprovalFlag(filename: "/images/photo.jpg")
try await client.setApprovalFlag(filename: "/images/photo.jpg", approved: true)
```

### Folder Options

```swift
// Get folder options
let options = try await client.getFolderOptions(dirname: "/products")

// Set folder options
try await client.setFolderOptions(dirname: "/products", options: FolderOptions(
    scanSpins: true,
    allowListing: false
))
```

### Fetch from URL

```swift
try await client.fetchUrl(FetchUrlParams(
    url: "https://example.com/image.jpg",
    filename: "/fetched/image.jpg",
    wait: true
))
```

### Batch ZIP

```swift
let zipResult = try await client.batchZip(BatchZipParams(
    filenames: ["/img1.jpg", "/img2.jpg"],
    filename: "/archive.zip"
))

// Check ZIP status
let status = try await client.getZipStatus(jobId: zipResult.jobId)
```

### JWT Protected URLs

```swift
let jwt = try await client.generateJwt(JwtParams(
    filename: "/private/document.pdf",
    expiresIn: 3600
))
print("Protected URL:", jwt.url)
```

## Account API

Manage your Sirv account settings and retrieve account information.

| Method | Description |
| --- | --- |
| `getAccountInfo()` | Get account information including CDN URL and [account name](/help/getting-started/account-name-subdomain/) |
| `updateAccount(_:)` | Update account settings (minify, fetching) |
| `getAccountLimits()` | Get API request limits and usage |
| `getStorageInfo()` | Get storage usage information |
| `getAccountUsers()` | List all account users |
| `getBillingPlan()` | Get billing plan details |
| `searchEvents(_:)` | Search account events |
| `markEventsSeen(_:)` | Mark events as seen |

```swift
// Get account information
let account = try await client.getAccountInfo()

// Update account settings
try await client.updateAccount(AccountUpdateOptions(
    minify: MinifyOptions(enabled: true)
))

// Get API limits
let limits = try await client.getAccountLimits()

// Get storage information
let storage = try await client.getStorageInfo()

// Get account users
let users = try await client.getAccountUsers()

// Get billing plan
let plan = try await client.getBillingPlan()

// Search account events
let events = try await client.searchEvents(EventSearchParams(level: "error"))

// Mark events as seen
try await client.markEventsSeen(["event-id-1", "event-id-2"])
```

## User API

```swift
// Get current user info
let user = try await client.getUserInfo()

// Get specific user info
let specificUser = try await client.getUserInfo(userId: "user-id")
```

## Spins/360 API

### Convert Spin to Video

```swift
let video = try await client.spin2Video(SpinConvertParams(
    filename: "/spins/product.spin",
    options: SpinConvertOptions(width: 1920, height: 1080, loops: 2)
))
```

### Convert Video to Spin

```swift
let spin = try await client.video2Spin(Video2SpinParams(
    filename: "/videos/product.mp4",
    targetFilename: "/spins/product.spin",
    options: Video2SpinOptions(frames: 36)
))
```

### Export to Marketplaces

```swift
try await client.exportSpinToAmazon(ExportSpinParams(filename: "/spins/p.spin", asin: "B08XXX"))
try await client.exportSpinToWalmart(ExportSpinParams(filename: "/spins/p.spin", productId: "xxx"))
try await client.exportSpinToHomeDepot(ExportSpinParams(filename: "/spins/p.spin", productId: "xxx"))
try await client.exportSpinToLowes(ExportSpinParams(filename: "/spins/p.spin", productId: "xxx"))
try await client.exportSpinToGrainger(ExportSpinParams(filename: "/spins/p.spin", productId: "xxx"))
```

### Points of Interest

```swift
// Get points of interest
let pois = try await client.getPointsOfInterest(filename: "/spins/product.spin")

// Set point of interest
try await client.setPointOfInterest(
    filename: "/spins/product.spin",
    poi: PointOfInterest(name: "Feature 1", x: 0.5, y: 0.3, frame: 10)
)

// Delete point of interest
try await client.deletePointOfInterest(filename: "/spins/product.spin", name: "Feature 1")
```

## Statistics API

Retrieve usage statistics for your account.

| Method | Description |
| --- | --- |
| `getHttpStats(_:)` | Get HTTP transfer statistics |
| `getSpinViewsStats(_:)` | Get spin viewer statistics (max 5 days) |
| `getStorageStats(_:)` | Get storage statistics |

```swift
// HTTP transfer statistics
let httpStats = try await client.getHttpStats(StatsParams(
    from: "2024-01-01",
    to: "2024-01-31"
))

// Storage statistics
let storageStats = try await client.getStorageStats(StatsParams(
    from: "2024-01-01",
    to: "2024-01-31"
))

// Spin views (max 5-day range)
let spinStats = try await client.getSpinViewsStats(StatsParams(
    from: "2024-01-01",
    to: "2024-01-05"
))
```

## Error Handling

The SDK provides a specific error type for API errors.

```swift
do {
    try await client.uploadFile(targetPath: "/photo.jpg", data: data)
} catch let error as SirvApiError {
    print("API Error:", error.message)
    print("Status:", error.statusCode)
    print("Code:", error.errorCode ?? "N/A")
} catch {
    print("Error:", error)
}
```

### SirvApiError Properties

| Property | Type | Description |
| --- | --- | --- |
| `message` | String | Error message |
| `statusCode` | Int | HTTP status code |
| `errorCode` | String? | API error code (if any) |

## Types Reference

All types conform to `Codable` and `Sendable` for type safety and thread safety.

### SirvClientConfig

```swift
public struct SirvClientConfig {
    let clientId: String
    let clientSecret: String
    var baseUrl: String              // "https://api.sirv.com"
    var autoRefreshToken: Bool       // true
    var tokenRefreshBuffer: TimeInterval // 60
    var timeout: TimeInterval        // 30
    var maxRetries: Int              // 3
}
```

### TokenResponse

```swift
public struct TokenResponse: Codable, Sendable {
    let token: String
    let expiresIn: Int
    let scope: [String]
}
```

### AccountInfo

```swift
public struct AccountInfo: Codable, Sendable {
    let alias: String?
    let cdnURL: String?
    let dateCreated: String?
    let fetching: FetchingOptions?
    let minify: MinifyOptions?
    let aliases: [String: AliasConfig]?
    let fileSizeLimit: Int?
}
```

### FileInfo

```swift
public struct FileInfo: Codable, Sendable {
    let filename: String?
    let dirname: String?
    let basename: String?
    let isDirectory: Bool?
    let size: Int?
    let ctime: String?
    let mtime: String?
    let contentType: String?
    let meta: FileMeta?
}
```

### FileMeta

```swift
public struct FileMeta: Codable, Sendable {
    var title: String?
    var description: String?
    var tags: [String]?
    var approved: Bool?
}
```

### ProductMeta

```swift
public struct ProductMeta: Codable, Sendable {
    var id: String?
    var name: String?
    var brand: String?
    var category: String?
    var sku: String?
}
```

### SearchResult

```swift
public struct SearchResult: Sendable {
    let hits: [FileInfo]
    let total: Int
    let scrollId: String?
}
```

### SearchParams

```swift
public struct SearchParams: Codable, Sendable {
    var query: String?
    var from: Int?
    var size: Int?
    var sort: SortOptions?
    var filters: SearchFilters?
}
```

### PointOfInterest

```swift
public struct PointOfInterest: Codable, Sendable {
    var name: String
    var x: Double    // 0-1
    var y: Double    // 0-1
    var frame: Int?
}
```

### StatsParams

```swift
public struct StatsParams: Sendable {
    var from: String  // ISO date
    var to: String    // ISO date
}
```

Use ISO dates, such as 2026-01-31, for the start and end of the period you want statistics for.
