Integrate with Sirv

Rapidly build fast, scalable imaging into your application. Sirv’s image upload API brings you file uploading and management to automate all your image management, optimization and delivery.

Being a high-availability platform, Sirv processes images in under 150 milliseconds at very high scale. Processed images are cached and subsequent requests are typically served within just 1 millisecond (0.001 seconds).

HTTP API & profiles

Sirv’s HTTP API is so simple, all you do is append a query string to an image URL to instantly generate a new image with your options. Refer to the Dynamic Imaging documentation for examples.

You can apply the same settings to many images by creating a profile. When you change the options, all images referencing that profile are changed, without editing any code in your site. Profiles are simple JSON files, applied as a query string in the URL e.g. https://example.sirv.com/test.jpg?profile=your-profile. More about profiles.

S3 API

For ultimate control when integrating with Sirv, use the Amazon S3 interface. Sirv supports the Amazon Web Services S3 REST API, allowing you to securely manage your images using either Signature Version v3 or Signature Version v4 authentication. You can control all your files and folders programmatically:

  • Query a folders’ contents
  • Check if a file exists
  • Fetch image meta data (Exif)
  • Create folders
  • Upload
  • Download
  • Edit
  • Move
  • Copy
  • Rename
  • Delete

Choose an SDK

To quickly connect and manage your files using S3, choose an official AWS SDK:

To learn more about S3, refer to the official S3 API documentation.

Connect to your Sirv bucket

Your S3 endpoint is s3.sirv.com and your S3 Bucket, S3 Key and S3 Secret can be found on your Settings page.

To use the S3cmd command line tool to connect to your Sirv account and upload/download/manage your files, use the following example. Replace the items in CAPITALS with your Sirv S3 connection details:

s3cmd --host=s3.sirv.com --host-bucket=s3.sirv.com --access_key=ENTER_YOUR_SIRV_S3_ACCESS_KEY_HERE --secret_key=ENTER_YOUR_SIRV_S3_SECRET_KEY_HERE ls s3://ENTER_YOUR_SIRV_S3_BUCKET_HERE/

 

AWS SDK for PHP

If you’re using PHP, you can manage your files with the AWS SDK for PHP.

Alternatively, you can use the simplified class below, which provides a basic API for working with Sirv storage.

  1. Download the latest version of the Sirv API class (zipped PHP file).
  2. Require the Sirv API class:
    require_once('sirv.api.class.php');
  3. Initialize the class instance with your Sirv S3 key, secret and bucket, from your Settings page.
    $sirvClient = new SirvClient(
      // S3 bucket
      'ENTER_YOUR_SIRV_S3_BUCKET_HERE',
      // S3 Access Key
      'ENTER_YOUR_SIRV_S3_KEY_HERE',
      // S3 Secret Key
      'ENTER_YOUR_SIRV_S3_SECRET_HERE'
    );
  4. Check that the connection is working:
    if ($sirvClient->testConnection()) {
      // Connection SUCCEEDED
    } else {
      // Connection FAILED
    }

Now you can perform the common actions below.

Check if a file/folder exists

// Check if a folder exists (example/folder)
$sirvClient->checkIfObjectExists('example/folder');

// Check if a file exists (example/folder/image.jpg)
$sirvClient->checkIfObjectExists('example/folder','image.jpg');

Get object list

$items = $sirvClient->getBucketContents('example/folder');

Upload files to Sirv

// Upload the local file local/folder/image.jpg to the folder example/folder/ on Sirv
$res = $sirvClient->uploadFile(
  // File path on Sirv
  'example/folder/image.jpg', 
  // Local file name
  'local/folder/image.jpg'
);

Create a folder

// Create the folder example/folder on Sirv
$sirvClient->createFolder('example/folder');

Delete a folder

// Delete the folder example/folder on Sirv
$sirvClient->deleteFile('example/folder/');

Delete a file

// Delete the file example/folder/image.jpg file from Sirv
$sirvClient->deleteFile('example/folder/image.jpg');

AWS SDK for .NET

Easily upload and manage files on your Sirv account with the AWS SDK for .NET.

Sirv supports current and historic versions of the AWS .NET SDK and Signature:

Signature Version 2Signature Version 3Signature Version 4
AWS SDK for .NET v2Full capabilityFull capabilityPartial capability (no upload)*
AWS SDK for .NET v3Full capabilityPartial capability (no upload)*Partial capability (no upload)*

*In a later update, Sirv will also support uploads using Signature Version 4.

1. Download and unzip the Sirv Console App for Visual Studio (zip).

2. Open the file SirvConsoleApp.csproj to install the console app. (Assuming you use Visual Studio).

3. Install either the S3 SDK v3 or the S3 SDK v2 from NuGet.

4. Connect to Sirv using the example script below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SirvConsoleApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Paste your S3 access keys and bucket name below, found on your Sirv settings page: https://my.sirv.com/#/account/settings
            var awsAccessKeyId = "ENTER_YOUR_SIRV_S3_KEY_HERE,";
            var awsSecretAccessKey = "ENTER_YOUR_SIRV_S3_SECRET_HERE,";
            var serviceUrl = "https://s3.sirv.com";
            var bucketName = "ENTER_YOUR_SIRV_S3_BUCKET_HERE";

            // Prepares your AWS credentials for connection
            Amazon.Runtime.AWSCredentials credentials = new Amazon.Runtime.BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey);

            // Prepares the Amazon S3 configuration for connection
            Amazon.S3.AmazonS3Config config = new Amazon.S3.AmazonS3Config
            {
                SignatureVersion = "2", // Note: versions 2, 3 and 4 are supported by s3.sirv.com
                AuthenticationRegion = "", // Important: should be empty to connect to s3.sirv.com
                ServiceURL = serviceUrl,
                ForcePathStyle = true
            };

            using (Amazon.S3.AmazonS3Client client = new Amazon.S3.AmazonS3Client(credentials, config))
            {
                // Enter your commands here - see below for example commands
            }
        }
    }
}

Now you can use the .NET commands below to perform common file actions such as check/copy/move/delete/upload files. You can also find these commands in the Program.cs file of the Sirv Console App for Visual Studio (zip).

List folder contents

// Fetch a list of all files in a folder
Amazon.S3.Model.ListObjectsRequest listObjectRequest = new Amazon.S3.Model.ListObjectsRequest
{
    BucketName = bucketName,
    Prefix = "examplefolder/examplesubfolder", // Enter the folder location or use "" to return files in the root
};

List objects = new List();
Amazon.S3.Model.ListObjectsResponse response;
do
{
    response = client.ListObjects(listObjectRequest);
    objects.AddRange(response.S3Objects);
    listObjectRequest.Marker = response.NextMarker; 
}
while (response.IsTruncated);
Amazon.S3.Model.S3Object firstObject = objects[1]; // If you set Prefix to "" then change the above to objects[0]. If you set Prefix as a folder, the first item returned will be the folder name, the second item returned will be the first file. If you set Prefix to a non-existing folder or path, an exception will be thrown: Amazon.S3.AmazonS3Exception: 'No such file or directory: /nosuchfolder/example/etc'.

Note: the .NET SDK sometimes provides an incomplete list, therefore if the list is truncated, the script fetches the next set of records.

Fetch file information

// Fetch the information for a particular file (this also permits downloading of the file)
Amazon.S3.Model.GetObjectResponse knownObjectDetails = client.GetObject(bucketName, "examplefolder/image.jpg");

// Check the file name and size, in bytes
long size = knownObjectDetails.ContentLength;

// Check the file last modified time
var lastModified = knownObjectDetails.LastModified;

Download a file

// Download a particular file
firstObjectDetails.WriteResponseStreamToFile(@"D:\examplefolder/image.jpg");
Console.WriteLine($@"{objectKey} downloaded to D:\examplefolder/image.jpg");

Upload a file

// Upload a local file
client.PutObject(new Amazon.S3.Model.PutObjectRequest() { FilePath = @"D:\examplefolder/image.jpg", BucketName = bucketName, Key = "image.jpg" });
Console.WriteLine($@"D:\examplefolder/image.jpg uploaded to image.jpg");

// Upload a local file to a particular folder (if the folder does not exist, it will be created)
client.PutObject(new Amazon.S3.Model.PutObjectRequest() { FilePath = @"D:\examplelocalfolder/image.jpg", BucketName = bucketName, Key = "examplefolder/image.jpg" });
Console.WriteLine($@"D:\examplelocalfolder/image.jpg uploaded to examplefolder/image.jpg");

Copy a file

// Copy a file, by specifying the existing file name and the copied file name
client.CopyObject(bucketName, "examplefolder/examplesubfolder/image.jpg", bucketName, "examplefolder/examplesubfolder/image copy.jpg");
Console.WriteLine($@"examplefolder/examplesubfolder/image.jpg copied to examplefolder/examplesubfolder/image copy.jpg");

Move a file

// Move a file (there is no S3 API command to move a file, so the original must be copied then deleted)
client.CopyObject(bucketName, "examplefolder/image.jpg", bucketName, "examplefolder/examplesubfolder/image.jpg");
client.DeleteObject(bucketName, "examplefolder/image.jpg");
Console.WriteLine($@"examplefolder/image.jpg moved to examplefolder/examplesubfolder/image.jpg");

Delete a file

// Delete a file (file will be sent to Trash in your Sirv account for 30 days)
client.DeleteObject(bucketName, "examplefolder/examplesubfolder/image.jpg");
Console.WriteLine($@"examplefolder/examplesubfolder/image.jpg sent to trash");

 

AWS SDK for JavaScript

Manage your images on Sirv through the browser using the AWS SDK for JavaScript.

The example HTML page below will help you get started. It will:

  1. Connect to your Sirv account.
  2. Show a form to upload files to your account.
  3. After upload, show a list of files in the root directory.

To use the script:

  1. Copy and paste the code into a new HTML file.
  2. Enter your Sirv S3 credentials into the following 3 places of the script (on lines 11, 12 and 18):
    YOUR_SIRV_S3_KEY
    YOUR_SIRV_S3_SECRET
    YOUR_SIRV_S3_BUCKET
  3. Save the HTML file and test it in your browser.
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.43.min.js"></script>



AWS SDK for Ruby

Use the well documented AWS SDK for Ruby to upload and manage your images on Sirv.

The code example below will list the Sirv buckets that a user has access to (each Sirv account has one bucket). When using the script, enter your Sirv S3 credentials in place of YOUR_SIRV_S3_KEY and YOUR_SIRV_S3_SECRET:

require 'aws-sdk'
s3 = Aws::S3::Resource.new(
  :endpoint =&gt; 'https://s3.sirv.com',
  :region =&gt; 'us-east-1',
  :force_path_style =&gt; true,
  :signature_version =&gt; 's3',
  :credentials =&gt; Aws::Credentials.new(
    'YOUR_SIRV_S3_KEY',
    'YOUR_SIRV_S3_SECRET'
  )
)
s3.buckets.limit(50).each do |b|
  puts "#{b.name}"
end

AWS SDK for Java

If you’re using Java, the sample code below will help you to:

  1. List the buckets in your account
  2. List objects in a bucket with a certain prefix
  3. Create a folder

In the code, look for the references to YOUR_SIRV_S3_KEY, YOUR_SIRV_S3_SECRET and YOUR_SIRV_S3_BUCKET and replace them with your S3 credentials located on your account page.

import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.S3ClientOptions;
public class S3Sample {
  public static void main(String[] args) throws IOException {
    AWSCredentials credentials = new BasicAWSCredentials("YOUR_SIRV_S3_KEY", "YOUR_SIRV_S3_SECRET");
    String bucketName = "YOUR_SIRV_S3_BUCKET";
    String endpoint = "https://s3.sirv.com";
    System.out.println("AccessKey: " + credentials.getAWSAccessKeyId() + " | Secret Key: " + credentials.getAWSSecretKey());
    ClientConfiguration clientConfig = new ClientConfiguration();
    clientConfig.withSignerOverride("S3SignerType");
    AmazonS3 s3 = new AmazonS3Client(credentials, clientConfig);
    s3.setEndpoint(endpoint);
    s3.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
    try {
      // List the buckets
      System.out.println("Listing buckets");
      for (Bucket bucket : s3.listBuckets()) {
        System.out.println(" - " + bucket.getName());
      }
      System.out.println();
      // List objects in the bucket with a certain prefix
      System.out.println("Listing objects");
      ObjectListing objectListing = s3.listObjects(new ListObjectsRequest().withBucketName(bucketName)
        .withPrefix("/Photos"));
      for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
        System.out.println(" - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
      }
      System.out.println();
      // Create a folder
      try {
        // Create metadata for your folder and set content-length to 0
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(0);
        // Create empty content
        InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
        // Create a PutObjectRequest passing the folder name suffixed by /
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, "EXAMPLE-FOLDER/", emptyContent, metadata);
        // Send request to S3 to create a folder
        s3.putObject(putObjectRequest);
      } catch(Exception e) {
        e.printStackTrace();
      }
    } catch (AmazonServiceException ase) {
      System.out.println("Error Message:    " + ase.getMessage());
      System.out.println("HTTP Status Code: " + ase.getStatusCode());
      System.out.println("AWS Error Code:   " + ase.getErrorCode());
      System.out.println("Error Type:       " + ase.getErrorType());
      System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
      System.out.println("Error Message: " + ace.getMessage());
    }
  }
}

Was this article helpful?