Java SDK for Sirv REST API
implementation 'com.sirv:sirv-rest-api-java:1.0.0'2. Copy your Client ID and Client secret from Account › Settings › API.3. ConnectSirvClient client = new SirvClient("your-client-id", "your-client-secret");
client.connect(); No account yet? Create one freeShort answer
Sirv's official Java 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 com.sirv sirv-rest-api-java package from Maven Central, 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 Java SDK provides a robust interface for interacting with the Sirv REST API.
It handles authentication automatically with token refresh and provides comprehensive file management capabilities.
Resources:
Installation
Section titled “Installation”Add the dependency to your pom.xml:
<dependency> <groupId>com.sirv</groupId> <artifactId>sirv-rest-api-java</artifactId> <version>1.0.0</version></dependency>Gradle
Section titled “Gradle”Add to your build.gradle:
implementation 'com.sirv:sirv-rest-api-java:1.0.0'Requirements
Section titled “Requirements”- Java 11 or higher
- OkHttp 4.x
- Gson 2.x
Quick Start
Section titled “Quick Start”import com.sirv.SirvClient;import com.sirv.model.AccountInfo;import com.sirv.model.FolderContents;
public class Example { public static void main(String[] args) { // Initialize the client SirvClient client = new SirvClient( "your-client-id", "your-client-secret" );
// Connect to obtain token client.connect();
// Get account information AccountInfo account = client.getAccountInfo(); System.out.println("Account: " + account.getAlias());
// List files in a directory FolderContents contents = client.readFolderContents("/"); for (FileInfo file : contents.getContents()) { System.out.println(file.getFilename()); }
// Clean up client.close(); }}Authentication
Section titled “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.
SirvClient client = new SirvClient("your-client-id", "your-client-secret");
// Connect with default expiry (20 minutes)client.connect();
// Or connect with custom expiry (1 hour)client.connect(3600);
// Check if connectedif (client.isConnected()) { System.out.println("Token is valid");}
// Get current access token for external useString token = client.getAccessToken();Configuration Options
Section titled “Configuration Options”SirvClient client = new SirvClient( "your-client-id", "your-client-secret", SirvClientConfig.builder() .baseUrl("https://api.sirv.com") .autoRefreshToken(true) .tokenRefreshBuffer(60) .timeout(30000) .maxRetries(3) .build());| Option | Type | Default | Description |
|---|---|---|---|
baseUrl | String | https://api.sirv.com | API endpoint |
autoRefreshToken | boolean | true | Auto-refresh token before expiry |
tokenRefreshBuffer | int | 60 | Seconds before expiry to refresh token |
timeout | int | 30000 | Request timeout in milliseconds |
maxRetries | int | 3 | Retry failed requests |
Try-with-Resources
Section titled “Try-with-Resources”Use try-with-resources for automatic cleanup:
try (SirvClient client = new SirvClient("client-id", "client-secret")) { client.connect(); AccountInfo account = client.getAccountInfo(); System.out.println("Account: " + account.getAlias());} // Client automatically closedFiles 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() |
| Metadata | getFileMeta(), setFileMeta(), getApprovalFlag(), setApprovalFlag(), getFileTitle(), setFileTitle(), getFileDescription(), setFileDescription(), getFileTags(), addFileTags(), removeFileTags(), getProductMeta(), setProductMeta() |
| Batch Operations | batchZip(), getBatchZipResult(), batchDelete(), getBatchDeleteResult() |
Basic Operations
Section titled “Basic Operations”// List folder contentsFolderContents contents = client.readFolderContents("/images");
// Get file informationFileInfo info = client.getFileInfo("/images/photo.jpg");
// Upload a file from bytesbyte[] data = Files.readAllBytes(Paths.get("/local/path/photo.jpg"));client.uploadFile("/images/photo.jpg", data);
// Upload a file from pathclient.uploadFile("/images/photo.jpg", new File("/local/path/photo.jpg"));
// Download a filebyte[] downloaded = client.downloadFile("/images/photo.jpg");Files.write(Paths.get("/local/downloaded.jpg"), downloaded);
// Copy a fileclient.copyFile("/images/photo.jpg", "/backup/photo.jpg");
// Rename/move a fileclient.renameFile("/images/old-name.jpg", "/images/new-name.jpg");
// Delete a fileclient.deleteFile("/images/photo.jpg");
// Create a folderclient.createFolder("/images/new-folder");
// Fetch file from URLclient.fetchUrl("https://example.com/image.jpg", "/images/fetched.jpg");Search Files
Section titled “Search Files”The SDK supports Elasticsearch-style queries with wildcards, boolean operators (AND/OR/NOT), and field-specific filtering.
// Search filesSearchResult results = client.searchFiles(SearchParams.builder() .query("filename:*.jpg") .from("/images") .size(100) .build());
// Iterate through resultsfor (FileInfo file : results.getHits()) { System.out.println(file.getFilename());}
// Continue with scroll for paginationif (results.getScrollId() != null) { SearchResult nextPage = client.scrollSearch(results.getScrollId());}Metadata Operations
Section titled “Metadata Operations”// Get and set file metadataFileMeta meta = client.getFileMeta("/images/photo.jpg");
client.setFileMeta("/images/photo.jpg", FileMeta.builder() .title("My Photo") .description("A beautiful sunset") .build());
// Get and set titleString title = client.getFileTitle("/images/photo.jpg");client.setFileTitle("/images/photo.jpg", "New Title");
// Manage tagsList<String> tags = client.getFileTags("/images/photo.jpg");client.addFileTags("/images/photo.jpg", Arrays.asList("nature", "sunset", "beach"));client.removeFileTags("/images/photo.jpg", Arrays.asList("beach"));
// Set product metadataclient.setProductMeta("/images/product.jpg", ProductMeta.builder() .id("SKU123") .name("Product Name") .brand("Brand Name") .build());
// Approval flagboolean approved = client.getApprovalFlag("/images/photo.jpg");client.setApprovalFlag("/images/photo.jpg", true);Batch Operations
Section titled “Batch Operations”// Create ZIP archiveBatchJob zipJob = client.batchZip(Arrays.asList( "/images/photo1.jpg", "/images/photo2.jpg"), "my-archive.zip");
// Check ZIP statusBatchZipResult zipResult = client.getBatchZipResult(zipJob.getToken());if ("completed".equals(zipResult.getStatus())) { System.out.println("ZIP URL: " + zipResult.getUrl());}
// Batch deleteBatchJob deleteJob = client.batchDelete(Arrays.asList( "/images/temp1.jpg", "/images/temp2.jpg"));
BatchDeleteResult deleteResult = client.getBatchDeleteResult(deleteJob.getToken());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 |
// Get account informationAccountInfo account = client.getAccountInfo();System.out.println("CDN URL: " + account.getCdnUrl());
// Get API limitsAccountLimits limits = client.getAccountLimits();System.out.println("API calls: " + limits.getUsed() + "/" + limits.getLimit());
// Get storage informationStorageInfo storage = client.getStorageInfo();System.out.println("Storage used: " + storage.getUsed() + " bytes");
// Get billing planBillingPlan plan = client.getBillingPlan();System.out.println("Plan: " + plan.getName());
// List account usersList<User> users = client.getAccountUsers();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 |
import java.time.LocalDate;
// HTTP transfer statisticsLocalDate from = LocalDate.of(2024, 1, 1);LocalDate to = LocalDate.of(2024, 1, 31);
HttpStats httpStats = client.getHttpStats(from, to);
// Spin views statistics (max 5 days)LocalDate spinFrom = LocalDate.of(2024, 1, 1);LocalDate spinTo = LocalDate.of(2024, 1, 5);
SpinViewsStats spinStats = client.getSpinViewsStats(spinFrom, spinTo, "account-alias");
// Storage statisticsStorageStats storageStats = client.getStorageStats(from, to);Spins & 360 Views
Section titled “Spins & 360 Views”Convert between spin and video formats, manage points of interest, and export to marketplaces.
// Convert spin to videoVideoResult video = client.spin2Video(Spin2VideoParams.builder() .filename("/spins/product.spin") .build());
// Convert video to spinSpinResult spin = client.video2Spin(Video2SpinParams.builder() .filename("/videos/product.mp4") .build());
// Export spin for marketplacesclient.exportSpinToAmazon("/spins/product.spin");client.exportSpinToWalmart("/spins/product.spin");client.exportSpinToHomeDepot("/spins/product.spin");client.exportSpinToLowes("/spins/product.spin");client.exportSpinToGrainger("/spins/product.spin");
// Get points of interestList<PointOfInterest> pois = client.getPointsOfInterest("/spins/product.spin");
// Set point of interestclient.setPointOfInterest("/spins/product.spin", PointOfInterest.builder() .name("Feature Highlight") .frame(10) .x(0.5) .y(0.3) .build());JWT Generation
Section titled “JWT Generation”Generate protected access tokens for secure file access.
JwtResult jwt = client.generateJwt(JwtParams.builder() .filename("/images/private-photo.jpg") .expiresIn(3600) // 1 hour .build());System.out.println("Protected URL: " + jwt.getUrl());User API
Section titled “User API”Retrieve user information.
// Get current user infoUserInfo user = client.getUserInfo();System.out.println("Email: " + user.getEmail());
// Get specific user infoUserInfo specificUser = client.getUserInfo("user-id-here");Error Handling
Section titled “Error Handling”The SDK provides a SirvApiException class for API-specific exceptions.
import com.sirv.SirvClient;import com.sirv.exception.SirvApiException;
try { client.uploadFile("/images/photo.jpg", data);} catch (SirvApiException e) { System.out.println("Status: " + e.getStatusCode()); System.out.println("Error code: " + e.getErrorCode()); System.out.println("Message: " + e.getMessage());} catch (Exception e) { System.out.println("Unexpected error: " + e.getMessage());}Common Status Codes
Section titled “Common Status Codes”| Status Code | Description |
|---|---|
401 | Unauthorized - Invalid credentials |
403 | Forbidden - Access denied |
404 | Not found - File or resource doesn’t exist |
409 | Conflict - Resource already exists |
429 | Rate limit exceeded |
If you get a 429 error, wait until your API limit resets and try again.
