Skip to content

.NET SDK for Sirv REST API

By , Head of Sirv StudioUpdated

Open this page in a new chat

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

Install the SDK via NuGet:

dotnet add package Sirv.RestApi

Or using the Package Manager Console:

Install-Package Sirv.RestApi

Or add to your .csproj file:

<PackageReference Include="Sirv.RestApi" Version="1.0.0" />
  • .NET 6, 7, or 8
  • .NET Standard 2.0 or 2.1
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);
}

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 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();
OptionTypeDefaultDescription
ClientIdstringrequiredYour API client ID
ClientSecretstringrequiredYour API client secret
BaseUrlstringhttps://api.sirv.comAPI endpoint
AutoRefreshTokenbooltrueAuto-refresh token before expiry
TokenRefreshBufferint60Seconds before expiry to refresh token
Timeoutint30000Request timeout in milliseconds
MaxRetriesint3Retry 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
});

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

CategoryMethods
File OperationsReadFolderContentsAsync(), GetFileInfoAsync(), UploadFileAsync(), UploadFileFromPathAsync(), DownloadFileAsync(), DownloadFileToAsync(), CopyFileAsync(), RenameFileAsync(), DeleteFileAsync(), BatchDeleteAsync(), CreateFolderAsync(), FetchUrlAsync(), BatchZipAsync()
MetadataGetFileMetaAsync(), SetFileMetaAsync(), GetApprovalFlagAsync(), SetApprovalFlagAsync(), GetFileTitleAsync(), SetFileTitleAsync(), GetFileTagsAsync(), AddFileTagsAsync(), RemoveFileTagsAsync(), GetProductMetaAsync(), SetProductMetaAsync()
Search & IterationSearchFilesAsync(), IterateSearchResultsAsync(), IterateFolderContentsAsync()
// 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
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);
}
// Iterate through folder contents (auto-pagination with IAsyncEnumerable)
await foreach (var item in client.IterateFolderContentsAsync("/images"))
{
Console.WriteLine(item.Filename);
}
// 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);

Manage your Sirv account settings and retrieve account information.

MethodDescription
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
// 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" });

Retrieve usage statistics for your account.

MethodDescription
GetHttpStatsAsync()Get HTTP transfer statistics
GetSpinViewsStatsAsync()Get spin viewer statistics (max 5 days)
GetStorageStatsAsync()Get storage statistics
// 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);

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

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

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}");

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}");
}
PropertyDescription
StatusCodeHTTP status code
ErrorCodeSirv-specific error code
MessageError message

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

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

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.

Back to top