# Java SDK for Sirv REST API

The official Java SDK provides a robust interface 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 handles authentication automatically with token refresh and provides comprehensive file management capabilities.

**Resources:**

-   [GitHub Repository](https://github.com/sirv/sirv-rest-api-java)
-   [Maven Central](https://central.sonatype.com/artifact/com.sirv/sirv-rest-api-java)
-   [API Documentation](/help/rest-api/reference/)

## Installation

### Maven

Add the dependency to your `pom.xml`:

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

### Gradle

Add to your `build.gradle`:

```groovy
implementation 'com.sirv:sirv-rest-api-java:1.0.0'
```

### Requirements

-   Java 11 or higher
-   OkHttp 4.x
-   Gson 2.x

## Quick Start

```java
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

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.

Tip

Get your API credentials from [Settings > API access](https://app.sirv.com/settings/api) in your Sirv account.

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

### Configuration Options

```java
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

Use try-with-resources for automatic cleanup:

```java
try (SirvClient client = new SirvClient("client-id", "client-secret")) {
    client.connect();
    AccountInfo account = client.getAccountInfo();
    System.out.println("Account: " + account.getAlias());
} // Client automatically closed
```

## 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()` |
| **Metadata** | `getFileMeta()`, `setFileMeta()`, `getApprovalFlag()`, `setApprovalFlag()`, `getFileTitle()`, `setFileTitle()`, `getFileDescription()`, `setFileDescription()`, `getFileTags()`, `addFileTags()`, `removeFileTags()`, `getProductMeta()`, `setProductMeta()` |
| **Batch Operations** | `batchZip()`, `getBatchZipResult()`, `batchDelete()`, `getBatchDeleteResult()` |

### Basic Operations

```java
// 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");
```

### Search Files

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

```java
// 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());
}
```

### Metadata Operations

```java
// 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);
```

### Batch Operations

```java
// 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());
```

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

```java
// 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();
```

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

```java
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);
```

## Spins & 360 Views

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

```java
// 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());
```

## JWT Generation

Generate protected access tokens for secure file access.

```java
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

Retrieve user information.

```java
// 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");
```

## Error Handling

The SDK provides a `SirvApiException` class for API-specific exceptions.

```java
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

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