Swift SDK for Sirv REST API
.package(url: "https://github.com/sirv/sirv-rest-api-swift.git", from: "1.0.0")2. Copy your Client ID and Client secret from Account › Settings › API.3. Connectlet client = SirvClient(config: SirvClientConfig(
clientId: "your-client-id",
clientSecret: "your-client-secret"
))
try await client.connect() No account yet? Create one freeShort 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:
Features
Section titled “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
Section titled “Installation”Swift Package Manager
Section titled “Swift Package Manager”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"])Quick Start
Section titled “Quick Start”import SirvSDK
let client = SirvClient(config: SirvClientConfig( clientId: "your-client-id", clientSecret: "your-client-secret"))
// Authenticatetry await client.connect()
// Get account infolet account = try await client.getAccountInfo()print("CDN URL:", account.cdnURL ?? "")
// Upload a filelet imageData = try Data(contentsOf: URL(fileURLWithPath: "./photo.jpg"))try await client.uploadFile(targetPath: "/images/photo.jpg", data: imageData)
// Search fileslet results = try await client.searchFiles(SearchParams(query: "product", size: 20))print("Found \(results.total) files")
// Iterate with automatic paginationfor try await file in client.iterateSearchResults(SearchParams(query: "*")) { print(file.filename ?? "")}Authentication
Section titled “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.
// Default token (20 minutes)try await client.connect()
// Custom expiry time (1 hour)try await client.connect(expiresIn: 3600)
// Check if connectedif client.isConnected() { print("Connected!")}
// Get current tokenlet token = client.getAccessToken()Configuration Options
Section titled “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 |
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
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 | 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
Section titled “Basic Operations”// List folder contentslet 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 infolet info = try await client.getFileInfo(filename: "/images/photo.jpg")
// Upload a filelet imageData = try Data(contentsOf: URL(fileURLWithPath: "./photo.jpg"))try await client.uploadFile(targetPath: "/images/photo.jpg", data: imageData)
// Upload from file pathtry await client.uploadFile(targetPath: "/images/photo.jpg", filePath: "./photo.jpg")
// Download a filelet data = try await client.downloadFile(filename: "/images/photo.jpg")
// Download to local pathtry await client.downloadFileTo(filename: "/images/photo.jpg", localPath: "./downloaded.jpg")
// Copy a filetry await client.copyFile(CopyParams(from: "/a.jpg", to: "/b.jpg"))
// Rename/move a filetry await client.renameFile(RenameParams(from: "/old.jpg", to: "/new.jpg"))
// Delete a filetry await client.deleteFile(filename: "/images/old-photo.jpg")
// Create a foldertry await client.createFolder(dirname: "/new-folder")
// Batch deletelet result = try await client.batchDelete(filenames: ["/img1.jpg", "/img2.jpg"])Search Files
Section titled “Search Files”// Search fileslet 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 manuallylet moreResults = try await client.scrollSearch(scrollId: results.scrollId!)Metadata Operations
Section titled “Metadata Operations”// Get/set file metadatalet 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"]))
// Titlelet titleResp = try await client.getFileTitle(filename: "/images/photo.jpg")try await client.setFileTitle(filename: "/images/photo.jpg", title: "New Title")
// Descriptionlet descResp = try await client.getFileDescription(filename: "/images/photo.jpg")try await client.setFileDescription(filename: "/images/photo.jpg", description: "New description")
// Tagslet 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 metadatalet 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 flaglet approvalResp = try await client.getApprovalFlag(filename: "/images/photo.jpg")try await client.setApprovalFlag(filename: "/images/photo.jpg", approved: true)Folder Options
Section titled “Folder Options”// Get folder optionslet options = try await client.getFolderOptions(dirname: "/products")
// Set folder optionstry await client.setFolderOptions(dirname: "/products", options: FolderOptions( scanSpins: true, allowListing: false))Fetch from URL
Section titled “Fetch from URL”try await client.fetchUrl(FetchUrlParams( url: "https://example.com/image.jpg", filename: "/fetched/image.jpg", wait: true))Batch ZIP
Section titled “Batch ZIP”let zipResult = try await client.batchZip(BatchZipParams( filenames: ["/img1.jpg", "/img2.jpg"], filename: "/archive.zip"))
// Check ZIP statuslet status = try await client.getZipStatus(jobId: zipResult.jobId)JWT Protected URLs
Section titled “JWT Protected URLs”let jwt = try await client.generateJwt(JwtParams( filename: "/private/document.pdf", expiresIn: 3600))print("Protected URL:", jwt.url)Account API
Section titled “Account API”Manage your Sirv account settings and retrieve account information.
| Method | Description |
|---|---|
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 informationlet account = try await client.getAccountInfo()
// Update account settingstry await client.updateAccount(AccountUpdateOptions( minify: MinifyOptions(enabled: true)))
// Get API limitslet limits = try await client.getAccountLimits()
// Get storage informationlet storage = try await client.getStorageInfo()
// Get account userslet users = try await client.getAccountUsers()
// Get billing planlet plan = try await client.getBillingPlan()
// Search account eventslet events = try await client.searchEvents(EventSearchParams(level: "error"))
// Mark events as seentry await client.markEventsSeen(["event-id-1", "event-id-2"])User API
Section titled “User API”// Get current user infolet user = try await client.getUserInfo()
// Get specific user infolet specificUser = try await client.getUserInfo(userId: "user-id")Spins/360 API
Section titled “Spins/360 API”Convert Spin to Video
Section titled “Convert Spin to Video”let video = try await client.spin2Video(SpinConvertParams( filename: "/spins/product.spin", options: SpinConvertOptions(width: 1920, height: 1080, loops: 2)))Convert Video to Spin
Section titled “Convert Video to Spin”let spin = try await client.video2Spin(Video2SpinParams( filename: "/videos/product.mp4", targetFilename: "/spins/product.spin", options: Video2SpinOptions(frames: 36)))Export to Marketplaces
Section titled “Export to Marketplaces”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
Section titled “Points of Interest”// Get points of interestlet pois = try await client.getPointsOfInterest(filename: "/spins/product.spin")
// Set point of interesttry await client.setPointOfInterest( filename: "/spins/product.spin", poi: PointOfInterest(name: "Feature 1", x: 0.5, y: 0.3, frame: 10))
// Delete point of interesttry await client.deletePointOfInterest(filename: "/spins/product.spin", name: "Feature 1")Statistics API
Section titled “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 |
// HTTP transfer statisticslet httpStats = try await client.getHttpStats(StatsParams( from: "2024-01-01", to: "2024-01-31"))
// Storage statisticslet 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
Section titled “Error Handling”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)}SirvApiError Properties
Section titled “SirvApiError Properties”| Property | Type | Description |
|---|---|---|
message | String | Error message |
statusCode | Int | HTTP status code |
errorCode | String? | API error code (if any) |
Types Reference
Section titled “Types Reference”All types conform to Codable and Sendable for type safety and thread safety.
SirvClientConfig
Section titled “SirvClientConfig”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
Section titled “TokenResponse”public struct TokenResponse: Codable, Sendable { let token: String let expiresIn: Int let scope: [String]}AccountInfo
Section titled “AccountInfo”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
Section titled “FileInfo”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
Section titled “FileMeta”public struct FileMeta: Codable, Sendable { var title: String? var description: String? var tags: [String]? var approved: Bool?}ProductMeta
Section titled “ProductMeta”public struct ProductMeta: Codable, Sendable { var id: String? var name: String? var brand: String? var category: String? var sku: String?}SearchResult
Section titled “SearchResult”public struct SearchResult: Sendable { let hits: [FileInfo] let total: Int let scrollId: String?}SearchParams
Section titled “SearchParams”public struct SearchParams: Codable, Sendable { var query: String? var from: Int? var size: Int? var sort: SortOptions? var filters: SearchFilters?}PointOfInterest
Section titled “PointOfInterest”public struct PointOfInterest: Codable, Sendable { var name: String var x: Double // 0-1 var y: Double // 0-1 var frame: Int?}StatsParams
Section titled “StatsParams”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.
