Skip to content

Swift SDK for Sirv REST API

By , Head of Sirv StudioUpdated

Open this page in a new chat

Short answer

Sirv's official Swift 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 the sirv-rest-api-swift package with Swift Package Manager, 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 Swift SDK provides native async/await concurrency for interacting with the Sirv REST API.

It features full Codable & Sendable type safety, automatic token management, and AsyncThrowingStream iterators for pagination.

Resources:

  • 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

Add to your Package.swift dependencies:

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

Then add to your target dependencies:

.target(name: "YourApp", dependencies: ["SirvSDK"])
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 ?? "")
}

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.

// 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()
OptionTypeDefaultDescription
clientIdStringrequiredYour Sirv API client ID
clientSecretStringrequiredYour Sirv API client secret
baseUrlStringhttps://api.sirv.comAPI base URL
autoRefreshTokenBooltrueAutomatically refresh tokens
tokenRefreshBufferTimeInterval60Seconds before expiry to refresh
timeoutTimeInterval30Request timeout in seconds
maxRetriesInt3Max retries for failed requests
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
))

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

CategoryMethods
File OperationsreadFolderContents, getFileInfo, uploadFile, downloadFile, copyFile, renameFile, deleteFile, createFolder, fetchUrl
IterationiterateFolderContents, iterateSearchResults
MetadatagetFileMeta, setFileMeta, getFileTitle, setFileTitle, getFileDescription, setFileDescription, getFileTags, addFileTags, removeFileTags, getProductMeta, setProductMeta, getApprovalFlag, setApprovalFlag
Batch OperationsbatchZip, getZipStatus, batchDelete
Spins & Exportspin2Video, video2Spin, exportSpinToAmazon, exportSpinToWalmart, exportSpinToHomeDepot, exportSpinToLowes, exportSpinToGrainger
// 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
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!)
// 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)
// 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
))
try await client.fetchUrl(FetchUrlParams(
url: "https://example.com/image.jpg",
filename: "/fetched/image.jpg",
wait: true
))
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)
let jwt = try await client.generateJwt(JwtParams(
filename: "/private/document.pdf",
expiresIn: 3600
))
print("Protected URL:", jwt.url)

Manage your Sirv account settings and retrieve account information.

MethodDescription
getAccountInfo()Get account information including CDN URL and account name
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
// 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"])
// Get current user info
let user = try await client.getUserInfo()
// Get specific user info
let specificUser = try await client.getUserInfo(userId: "user-id")
let video = try await client.spin2Video(SpinConvertParams(
filename: "/spins/product.spin",
options: SpinConvertOptions(width: 1920, height: 1080, loops: 2)
))
let spin = try await client.video2Spin(Video2SpinParams(
filename: "/videos/product.mp4",
targetFilename: "/spins/product.spin",
options: Video2SpinOptions(frames: 36)
))
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"))
// 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")

Retrieve usage statistics for your account.

MethodDescription
getHttpStats(_:)Get HTTP transfer statistics
getSpinViewsStats(_:)Get spin viewer statistics (max 5 days)
getStorageStats(_:)Get storage statistics
// 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"
))

The SDK provides a specific error type for API errors.

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)
}
PropertyTypeDescription
messageStringError message
statusCodeIntHTTP status code
errorCodeString?API error code (if any)

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

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
}
public struct TokenResponse: Codable, Sendable {
let token: String
let expiresIn: Int
let scope: [String]
}
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?
}
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?
}
public struct FileMeta: Codable, Sendable {
var title: String?
var description: String?
var tags: [String]?
var approved: Bool?
}
public struct ProductMeta: Codable, Sendable {
var id: String?
var name: String?
var brand: String?
var category: String?
var sku: String?
}
public struct SearchResult: Sendable {
let hits: [FileInfo]
let total: Int
let scrollId: String?
}
public struct SearchParams: Codable, Sendable {
var query: String?
var from: Int?
var size: Int?
var sort: SortOptions?
var filters: SearchFilters?
}
public struct PointOfInterest: Codable, Sendable {
var name: String
var x: Double // 0-1
var y: Double // 0-1
var frame: Int?
}
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.

Back to top