# .NET SDK for Sirv REST API

The official .NET SDK provides a modern, async-first 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 `IAsyncEnumerable` for paginated results.

**Resources:**

-   [GitHub Repository](https://github.com/sirv/sirv-rest-api-dotnet)
-   [NuGet Package](https://www.nuget.org/packages/Sirv.RestApi)
-   [API Documentation](/help/rest-api/reference/)

## Installation

Install the SDK via NuGet:

```bash
dotnet add package Sirv.RestApi
```

Or using the Package Manager Console:

```powershell
Install-Package Sirv.RestApi
```

Or add to your `.csproj` file:

```xml
<PackageReference Include="Sirv.RestApi" Version="1.0.0" />
```

### Requirements

-   .NET 6, 7, or 8
-   .NET Standard 2.0 or 2.1

## Quick Start

```csharp
using Sirv;

// Initialize the client
var client = new SirvClient(new SirvClientConfig
{
    ClientId = "your-client-id",
    ClientSecret = "your-client-secret"
});

// Get account information
var account = await client.GetAccountInfoAsync();
Console.WriteLine($"Account: {account.Alias}");

// List files in a directory
var contents = await client.ReadFolderContentsAsync("/");
foreach (var file in contents.Contents)
{
    Console.WriteLine(file.Filename);
}
```

## 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 before it expires.

Tip

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

```csharp
var client = new SirvClient(new SirvClientConfig
{
    ClientId = "your-client-id",
    ClientSecret = "your-client-secret",
    AutoRefreshToken = true // Default: automatically refresh before expiry
});

// Optional: Manually authenticate to verify credentials
try
{
    await client.ConnectAsync();
    Console.WriteLine("Authenticated successfully");
}
catch (SirvApiException ex)
{
    Console.WriteLine($"Authentication failed: {ex.Message}");
}

// Check if connected
if (client.IsConnected())
{
    Console.WriteLine("Token is valid");
}

// Get current access token for external use
var token = client.GetAccessToken();
```

### Configuration Options

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `ClientId` | string | required | Your API client ID |
| `ClientSecret` | string | required | Your API client secret |
| `BaseUrl` | string | `https://api.sirv.com` | API endpoint |
| `AutoRefreshToken` | bool | `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 with exponential backoff |

```csharp
var client = new SirvClient(new SirvClientConfig
{
    ClientId = "your-client-id",
    ClientSecret = "your-client-secret",
    BaseUrl = "https://api.sirv.com",
    AutoRefreshToken = true,
    TokenRefreshBuffer = 60,
    Timeout = 30000,
    MaxRetries = 3
});
```

## Files API

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

### Available Methods

| Category | Methods |
| --- | --- |
| **File Operations** | `ReadFolderContentsAsync()`, `GetFileInfoAsync()`, `UploadFileAsync()`, `UploadFileFromPathAsync()`, `DownloadFileAsync()`, `DownloadFileToAsync()`, `CopyFileAsync()`, `RenameFileAsync()`, `DeleteFileAsync()`, `BatchDeleteAsync()`, `CreateFolderAsync()`, `FetchUrlAsync()`, `BatchZipAsync()` |
| **Metadata** | `GetFileMetaAsync()`, `SetFileMetaAsync()`, `GetApprovalFlagAsync()`, `SetApprovalFlagAsync()`, `GetFileTitleAsync()`, `SetFileTitleAsync()`, `GetFileTagsAsync()`, `AddFileTagsAsync()`, `RemoveFileTagsAsync()`, `GetProductMetaAsync()`, `SetProductMetaAsync()` |
| **Search & Iteration** | `SearchFilesAsync()`, `IterateSearchResultsAsync()`, `IterateFolderContentsAsync()` |

### Basic Operations

```csharp
// List folder contents
var contents = await client.ReadFolderContentsAsync("/images");

// Get file information
var info = await client.GetFileInfoAsync("/images/photo.jpg");

// Upload a file from bytes
byte[] data = File.ReadAllBytes("/local/path/photo.jpg");
await client.UploadFileAsync("/images/photo.jpg", data);

// Upload a file from stream
using var stream = File.OpenRead("/local/path/photo.jpg");
await client.UploadFileAsync("/images/photo.jpg", stream);

// Upload a file from path
await client.UploadFileFromPathAsync("/images/photo.jpg", "/local/path/photo.jpg");

// Download a file to bytes
byte[] downloaded = await client.DownloadFileAsync("/images/photo.jpg");

// Download a file to local path
await client.DownloadFileToAsync("/images/photo.jpg", "/local/downloaded.jpg");

// Copy a file
await client.CopyFileAsync("/images/photo.jpg", "/backup/photo.jpg");

// Rename/move a file
await client.RenameFileAsync("/images/old-name.jpg", "/images/new-name.jpg");

// Delete a file
await client.DeleteFileAsync("/images/photo.jpg");

// Batch delete files
await client.BatchDeleteAsync(new[] { "/images/photo1.jpg", "/images/photo2.jpg" });

// Create a folder
await client.CreateFolderAsync("/images/new-folder");

// Fetch file from URL
await client.FetchUrlAsync("https://example.com/image.jpg", "/images/fetched.jpg");

// Create ZIP archive
var zip = await client.BatchZipAsync(new BatchZipParams
{
    Filenames = new[] { "/images/photo1.jpg", "/images/photo2.jpg" },
    ZipFilename = "my-archive.zip"
});
```

### Search Files

```csharp
// Search files
var results = await client.SearchFilesAsync(new SearchParams
{
    Query = "filename:*.jpg",
    From = "/images",
    Size = 100
});

// Iterate through search results (auto-pagination with IAsyncEnumerable)
await foreach (var file in client.IterateSearchResultsAsync(new SearchParams
{
    Query = "extension:.jpg",
    From = "/images"
}))
{
    Console.WriteLine(file.Filename);
}
```

### Folder Iteration

```csharp
// Iterate through folder contents (auto-pagination with IAsyncEnumerable)
await foreach (var item in client.IterateFolderContentsAsync("/images"))
{
    Console.WriteLine(item.Filename);
}
```

### Metadata Operations

```csharp
// Get and set file metadata
var meta = await client.GetFileMetaAsync("/images/photo.jpg");

await client.SetFileMetaAsync("/images/photo.jpg", new FileMeta
{
    Title = "My Photo",
    Description = "A beautiful sunset"
});

// Get and set title
var title = await client.GetFileTitleAsync("/images/photo.jpg");
await client.SetFileTitleAsync("/images/photo.jpg", "New Title");

// Manage tags
var tags = await client.GetFileTagsAsync("/images/photo.jpg");
await client.AddFileTagsAsync("/images/photo.jpg", new[] { "nature", "sunset", "beach" });
await client.RemoveFileTagsAsync("/images/photo.jpg", new[] { "beach" });

// Set product metadata
await client.SetProductMetaAsync("/images/product.jpg", new ProductMeta
{
    Id = "SKU123",
    Name = "Product Name",
    Brand = "Brand Name"
});

// Approval flag
var approved = await client.GetApprovalFlagAsync("/images/photo.jpg");
await client.SetApprovalFlagAsync("/images/photo.jpg", true);
```

## Account API

Manage your Sirv account settings and retrieve account information.

### Available Methods

| Method | Description |
| --- | --- |
| `GetAccountInfoAsync()` | Get account information including CDN URL and [account name](/help/getting-started/account-name-subdomain/) |
| `UpdateAccountAsync()` | Update account settings (minify, fetching) |
| `GetAccountLimitsAsync()` | Get API request limits and usage |
| `GetStorageInfoAsync()` | Get storage usage information |
| `GetAccountUsersAsync()` | List all account users |
| `GetBillingPlanAsync()` | Get billing plan details |
| `SearchEventsAsync()` | Search account events |
| `MarkEventsSeenAsync()` | Mark events as seen |

### Examples

```csharp
// Get account information
var account = await client.GetAccountInfoAsync();
Console.WriteLine($"CDN URL: {account.CdnUrl}");

// Get API limits
var limits = await client.GetAccountLimitsAsync();
Console.WriteLine($"API calls: {limits.Used}/{limits.Limit}");

// Get storage information
var storage = await client.GetStorageInfoAsync();
Console.WriteLine($"Storage used: {storage.Used} bytes");

// Get billing plan
var plan = await client.GetBillingPlanAsync();
Console.WriteLine($"Plan: {plan.Name}");

// List account users
var users = await client.GetAccountUsersAsync();

// Search account events
var events = await client.SearchEventsAsync(new EventSearchParams
{
    Module = "files",
    Level = "error"
});

// Mark events as seen
await client.MarkEventsSeenAsync(new[] { "event-id-1", "event-id-2" });
```

## Statistics API

Retrieve usage statistics for your account.

| Method | Description |
| --- | --- |
| `GetHttpStatsAsync()` | Get HTTP transfer statistics |
| `GetSpinViewsStatsAsync()` | Get spin viewer statistics (max 5 days) |
| `GetStorageStatsAsync()` | Get storage statistics |

```csharp
// HTTP transfer statistics
var from = new DateTime(2024, 1, 1);
var to = new DateTime(2024, 1, 31);

var httpStats = await client.GetHttpStatsAsync(from, to);

// Spin views statistics (max 5 days)
var spinFrom = new DateTime(2024, 1, 1);
var spinTo = new DateTime(2024, 1, 5);

var spinStats = await client.GetSpinViewsStatsAsync(spinFrom, spinTo, "account-alias");

// Storage statistics
var storageStats = await client.GetStorageStatsAsync(from, to);
```

## Spins & 360 Views

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

```csharp
// Convert spin to video
var video = await client.Spin2VideoAsync(new Spin2VideoParams
{
    Filename = "/spins/product.spin"
});

// Convert video to spin
var spin = await client.Video2SpinAsync(new Video2SpinParams
{
    Filename = "/videos/product.mp4"
});

// Export spin for marketplaces
await client.ExportSpinToAmazonAsync(new SpinExportParams
{
    Filename = "/spins/product.spin"
});

await client.ExportSpinToWalmartAsync(new SpinExportParams
{
    Filename = "/spins/product.spin"
});

// Get points of interest
var pois = await client.GetPointsOfInterestAsync("/spins/product.spin");

// Set point of interest
await client.SetPointOfInterestAsync("/spins/product.spin", new PointOfInterest
{
    Name = "Feature Highlight",
    Frame = 10,
    X = 0.5,
    Y = 0.3
});
```

## JWT Generation

Generate protected access tokens for secure file access.

```csharp
var jwt = await client.GenerateJwtAsync(new JwtParams
{
    Filename = "/images/private-photo.jpg",
    ExpiresIn = 3600 // 1 hour
});
Console.WriteLine($"Protected URL: {jwt.Url}");
```

## Error Handling

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

```csharp
using Sirv;

try
{
    await client.UploadFileAsync("/images/photo.jpg", data);
}
catch (SirvApiException ex)
{
    Console.WriteLine($"Status: {ex.StatusCode}");
    Console.WriteLine($"Error code: {ex.ErrorCode}");
    Console.WriteLine($"Message: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"Unexpected error: {ex.Message}");
}
```

### SirvApiException Properties

| Property | Description |
| --- | --- |
| `StatusCode` | HTTP status code |
| `ErrorCode` | Sirv-specific error code |
| `Message` | Error message |

## Dependency Injection

Register the client in your DI container for application-wide availability:

```csharp
// In Program.cs or Startup.cs
services.AddSingleton(new SirvClient(new SirvClientConfig
{
    ClientId = Configuration["Sirv:ClientId"],
    ClientSecret = Configuration["Sirv:ClientSecret"]
}));

// Or using options pattern
services.AddSingleton(sp =>
{
    var config = sp.GetRequiredService<IOptions<SirvConfig>>().Value;
    return new SirvClient(new SirvClientConfig
    {
        ClientId = config.ClientId,
        ClientSecret = config.ClientSecret
    });
});
```

## Cancellation Token Support

All async methods support cancellation tokens:

```csharp
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));

try
{
    var account = await client.GetAccountInfoAsync(cts.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine("Operation was cancelled");
}
```

If a request takes longer than the time you set, it is cancelled and your code can retry or show an error.
