Skip to content

Java SDK for Sirv REST API

By , Head of Sirv StudioUpdated

Open this page in a new chat

Short 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:

Add the dependency to your pom.xml:

<dependency>
<groupId>com.sirv</groupId>
<artifactId>sirv-rest-api-java</artifactId>
<version>1.0.0</version>
</dependency>

Add to your build.gradle:

implementation 'com.sirv:sirv-rest-api-java:1.0.0'
  • Java 11 or higher
  • OkHttp 4.x
  • Gson 2.x
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();
}
}

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 connected
if (client.isConnected()) {
System.out.println("Token is valid");
}
// Get current access token for external use
String token = client.getAccessToken();
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()
);
OptionTypeDefaultDescription
baseUrlStringhttps://api.sirv.comAPI endpoint
autoRefreshTokenbooleantrueAuto-refresh token before expiry
tokenRefreshBufferint60Seconds before expiry to refresh token
timeoutint30000Request timeout in milliseconds
maxRetriesint3Retry failed requests

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 closed

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

CategoryMethods
File OperationsreadFolderContents(), getFileInfo(), uploadFile(), downloadFile(), copyFile(), renameFile(), deleteFile(), createFolder(), fetchUrl()
MetadatagetFileMeta(), setFileMeta(), getApprovalFlag(), setApprovalFlag(), getFileTitle(), setFileTitle(), getFileDescription(), setFileDescription(), getFileTags(), addFileTags(), removeFileTags(), getProductMeta(), setProductMeta()
Batch OperationsbatchZip(), getBatchZipResult(), batchDelete(), getBatchDeleteResult()
// List folder contents
FolderContents contents = client.readFolderContents("/images");
// Get file information
FileInfo info = client.getFileInfo("/images/photo.jpg");
// Upload a file from bytes
byte[] data = Files.readAllBytes(Paths.get("/local/path/photo.jpg"));
client.uploadFile("/images/photo.jpg", data);
// Upload a file from path
client.uploadFile("/images/photo.jpg", new File("/local/path/photo.jpg"));
// Download a file
byte[] downloaded = client.downloadFile("/images/photo.jpg");
Files.write(Paths.get("/local/downloaded.jpg"), downloaded);
// Copy a file
client.copyFile("/images/photo.jpg", "/backup/photo.jpg");
// Rename/move a file
client.renameFile("/images/old-name.jpg", "/images/new-name.jpg");
// Delete a file
client.deleteFile("/images/photo.jpg");
// Create a folder
client.createFolder("/images/new-folder");
// Fetch file from URL
client.fetchUrl("https://example.com/image.jpg", "/images/fetched.jpg");

The SDK supports Elasticsearch-style queries with wildcards, boolean operators (AND/OR/NOT), and field-specific filtering.

// Search files
SearchResult results = client.searchFiles(SearchParams.builder()
.query("filename:*.jpg")
.from("/images")
.size(100)
.build());
// Iterate through results
for (FileInfo file : results.getHits()) {
System.out.println(file.getFilename());
}
// Continue with scroll for pagination
if (results.getScrollId() != null) {
SearchResult nextPage = client.scrollSearch(results.getScrollId());
}
// Get and set file metadata
FileMeta meta = client.getFileMeta("/images/photo.jpg");
client.setFileMeta("/images/photo.jpg", FileMeta.builder()
.title("My Photo")
.description("A beautiful sunset")
.build());
// Get and set title
String title = client.getFileTitle("/images/photo.jpg");
client.setFileTitle("/images/photo.jpg", "New Title");
// Manage tags
List<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 metadata
client.setProductMeta("/images/product.jpg", ProductMeta.builder()
.id("SKU123")
.name("Product Name")
.brand("Brand Name")
.build());
// Approval flag
boolean approved = client.getApprovalFlag("/images/photo.jpg");
client.setApprovalFlag("/images/photo.jpg", true);
// Create ZIP archive
BatchJob zipJob = client.batchZip(Arrays.asList(
"/images/photo1.jpg",
"/images/photo2.jpg"
), "my-archive.zip");
// Check ZIP status
BatchZipResult zipResult = client.getBatchZipResult(zipJob.getToken());
if ("completed".equals(zipResult.getStatus())) {
System.out.println("ZIP URL: " + zipResult.getUrl());
}
// Batch delete
BatchJob deleteJob = client.batchDelete(Arrays.asList(
"/images/temp1.jpg",
"/images/temp2.jpg"
));
BatchDeleteResult deleteResult = client.getBatchDeleteResult(deleteJob.getToken());

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
// Get account information
AccountInfo account = client.getAccountInfo();
System.out.println("CDN URL: " + account.getCdnUrl());
// Get API limits
AccountLimits limits = client.getAccountLimits();
System.out.println("API calls: " + limits.getUsed() + "/" + limits.getLimit());
// Get storage information
StorageInfo storage = client.getStorageInfo();
System.out.println("Storage used: " + storage.getUsed() + " bytes");
// Get billing plan
BillingPlan plan = client.getBillingPlan();
System.out.println("Plan: " + plan.getName());
// List account users
List<User> users = client.getAccountUsers();

Retrieve usage statistics for your account.

MethodDescription
getHttpStats()Get HTTP transfer statistics
getSpinViewsStats()Get spin viewer statistics (max 5 days)
getStorageStats()Get storage statistics
import java.time.LocalDate;
// HTTP transfer statistics
LocalDate 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 statistics
StorageStats storageStats = client.getStorageStats(from, to);

Convert between spin and video formats, manage points of interest, and export to marketplaces.

// Convert spin to video
VideoResult video = client.spin2Video(Spin2VideoParams.builder()
.filename("/spins/product.spin")
.build());
// Convert video to spin
SpinResult spin = client.video2Spin(Video2SpinParams.builder()
.filename("/videos/product.mp4")
.build());
// Export spin for marketplaces
client.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 interest
List<PointOfInterest> pois = client.getPointsOfInterest("/spins/product.spin");
// Set point of interest
client.setPointOfInterest("/spins/product.spin", PointOfInterest.builder()
.name("Feature Highlight")
.frame(10)
.x(0.5)
.y(0.3)
.build());

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());

Retrieve user information.

// Get current user info
UserInfo user = client.getUserInfo();
System.out.println("Email: " + user.getEmail());
// Get specific user info
UserInfo specificUser = client.getUserInfo("user-id-here");

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());
}
Status CodeDescription
401Unauthorized - Invalid credentials
403Forbidden - Access denied
404Not found - File or resource doesn’t exist
409Conflict - Resource already exists
429Rate limit exceeded

If you get a 429 error, wait until your API limit resets and try again.

Back to top