.NET SDK for Sirv REST API
dotnet add package Sirv.RestApi2. Copy your Client ID and Client secret from Account › Settings › API.3. Connectvar client = new SirvClient(new SirvClientConfig
{
ClientId = "your-client-id",
ClientSecret = "your-client-secret"
}); No account yet? Create one freeShort answer
Sirv's official .NET 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 dotnet add package Sirv.RestApi, 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 .NET SDK provides a modern, async-first interface for interacting with the Sirv REST API.
It handles authentication automatically with token refresh and provides IAsyncEnumerable for paginated results.
Resources:
Installation
Section titled “Installation”Install the SDK via NuGet:
dotnet add package Sirv.RestApiOr using the Package Manager Console:
Install-Package Sirv.RestApiOr add to your .csproj file:
<PackageReference Include="Sirv.RestApi" Version="1.0.0" />Requirements
Section titled “Requirements”- .NET 6, 7, or 8
- .NET Standard 2.0 or 2.1
Quick Start
Section titled “Quick Start”using Sirv;
// Initialize the clientvar client = new SirvClient(new SirvClientConfig{ ClientId = "your-client-id", ClientSecret = "your-client-secret"});
// Get account informationvar account = await client.GetAccountInfoAsync();Console.WriteLine($"Account: {account.Alias}");
// List files in a directoryvar contents = await client.ReadFolderContentsAsync("/");foreach (var file in contents.Contents){ Console.WriteLine(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 before it expires.
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 credentialstry{ await client.ConnectAsync(); Console.WriteLine("Authenticated successfully");}catch (SirvApiException ex){ Console.WriteLine($"Authentication failed: {ex.Message}");}
// Check if connectedif (client.IsConnected()){ Console.WriteLine("Token is valid");}
// Get current access token for external usevar token = client.GetAccessToken();Configuration Options
Section titled “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 |
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
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 | 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
Section titled “Basic Operations”// List folder contentsvar contents = await client.ReadFolderContentsAsync("/images");
// Get file informationvar info = await client.GetFileInfoAsync("/images/photo.jpg");
// Upload a file from bytesbyte[] data = File.ReadAllBytes("/local/path/photo.jpg");await client.UploadFileAsync("/images/photo.jpg", data);
// Upload a file from streamusing var stream = File.OpenRead("/local/path/photo.jpg");await client.UploadFileAsync("/images/photo.jpg", stream);
// Upload a file from pathawait client.UploadFileFromPathAsync("/images/photo.jpg", "/local/path/photo.jpg");
// Download a file to bytesbyte[] downloaded = await client.DownloadFileAsync("/images/photo.jpg");
// Download a file to local pathawait client.DownloadFileToAsync("/images/photo.jpg", "/local/downloaded.jpg");
// Copy a fileawait client.CopyFileAsync("/images/photo.jpg", "/backup/photo.jpg");
// Rename/move a fileawait client.RenameFileAsync("/images/old-name.jpg", "/images/new-name.jpg");
// Delete a fileawait client.DeleteFileAsync("/images/photo.jpg");
// Batch delete filesawait client.BatchDeleteAsync(new[] { "/images/photo1.jpg", "/images/photo2.jpg" });
// Create a folderawait client.CreateFolderAsync("/images/new-folder");
// Fetch file from URLawait client.FetchUrlAsync("https://example.com/image.jpg", "/images/fetched.jpg");
// Create ZIP archivevar zip = await client.BatchZipAsync(new BatchZipParams{ Filenames = new[] { "/images/photo1.jpg", "/images/photo2.jpg" }, ZipFilename = "my-archive.zip"});Search Files
Section titled “Search Files”// Search filesvar 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
Section titled “Folder Iteration”// Iterate through folder contents (auto-pagination with IAsyncEnumerable)await foreach (var item in client.IterateFolderContentsAsync("/images")){ Console.WriteLine(item.Filename);}Metadata Operations
Section titled “Metadata Operations”// Get and set file metadatavar 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 titlevar title = await client.GetFileTitleAsync("/images/photo.jpg");await client.SetFileTitleAsync("/images/photo.jpg", "New Title");
// Manage tagsvar 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 metadataawait client.SetProductMetaAsync("/images/product.jpg", new ProductMeta{ Id = "SKU123", Name = "Product Name", Brand = "Brand Name"});
// Approval flagvar approved = await client.GetApprovalFlagAsync("/images/photo.jpg");await client.SetApprovalFlagAsync("/images/photo.jpg", true);Account API
Section titled “Account API”Manage your Sirv account settings and retrieve account information.
Available Methods
Section titled “Available Methods”| Method | Description |
|---|---|
GetAccountInfoAsync() | Get account information including CDN URL and account name |
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
Section titled “Examples”// Get account informationvar account = await client.GetAccountInfoAsync();Console.WriteLine($"CDN URL: {account.CdnUrl}");
// Get API limitsvar limits = await client.GetAccountLimitsAsync();Console.WriteLine($"API calls: {limits.Used}/{limits.Limit}");
// Get storage informationvar storage = await client.GetStorageInfoAsync();Console.WriteLine($"Storage used: {storage.Used} bytes");
// Get billing planvar plan = await client.GetBillingPlanAsync();Console.WriteLine($"Plan: {plan.Name}");
// List account usersvar users = await client.GetAccountUsersAsync();
// Search account eventsvar events = await client.SearchEventsAsync(new EventSearchParams{ Module = "files", Level = "error"});
// Mark events as seenawait client.MarkEventsSeenAsync(new[] { "event-id-1", "event-id-2" });Statistics API
Section titled “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 |
// HTTP transfer statisticsvar 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 statisticsvar storageStats = await client.GetStorageStatsAsync(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 videovar video = await client.Spin2VideoAsync(new Spin2VideoParams{ Filename = "/spins/product.spin"});
// Convert video to spinvar spin = await client.Video2SpinAsync(new Video2SpinParams{ Filename = "/videos/product.mp4"});
// Export spin for marketplacesawait client.ExportSpinToAmazonAsync(new SpinExportParams{ Filename = "/spins/product.spin"});
await client.ExportSpinToWalmartAsync(new SpinExportParams{ Filename = "/spins/product.spin"});
// Get points of interestvar pois = await client.GetPointsOfInterestAsync("/spins/product.spin");
// Set point of interestawait client.SetPointOfInterestAsync("/spins/product.spin", new PointOfInterest{ Name = "Feature Highlight", Frame = 10, X = 0.5, Y = 0.3});JWT Generation
Section titled “JWT Generation”Generate protected access tokens for secure file access.
var jwt = await client.GenerateJwtAsync(new JwtParams{ Filename = "/images/private-photo.jpg", ExpiresIn = 3600 // 1 hour});Console.WriteLine($"Protected URL: {jwt.Url}");Error Handling
Section titled “Error Handling”The SDK provides a SirvApiException class for API-specific exceptions.
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
Section titled “SirvApiException Properties”| Property | Description |
|---|---|
StatusCode | HTTP status code |
ErrorCode | Sirv-specific error code |
Message | Error message |
Dependency Injection
Section titled “Dependency Injection”Register the client in your DI container for application-wide availability:
// In Program.cs or Startup.csservices.AddSingleton(new SirvClient(new SirvClientConfig{ ClientId = Configuration["Sirv:ClientId"], ClientSecret = Configuration["Sirv:ClientSecret"]}));
// Or using options patternservices.AddSingleton(sp =>{ var config = sp.GetRequiredService<IOptions<SirvConfig>>().Value; return new SirvClient(new SirvClientConfig { ClientId = config.ClientId, ClientSecret = config.ClientSecret });});Cancellation Token Support
Section titled “Cancellation Token Support”All async methods support cancellation tokens:
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.
