Integrate with Sirv

Why build upon Sirv?

Sirv provides everything you need to rapidly build fast and scalable imaging into your application. Never again will you need to manually edit or optimize images.

Being a high-availability platform, Sirv delivers images in a fraction of a second at very high scale. It provides you with unlimited volume of dynamic imaging, on-the-fly. Each image processing request is completed within ~0.15 seconds. Images are then cached and subsequent requests are normally complete within 1 millisecond (0.001 seconds).

HTTP API & profiles

For fast integration, the HTTP API has everything you need. Simply append a query string to an image URL and it will be instantly generated with the options you request. Refer to the Dynamic Imaging documentation for examples.

For greater control, create a profile, allowing you to change image settings in future without editing your HTML. Profiles are JSON files containing image settings and are applied as a query string in the URL e.g. https://example.sirv.com/test.jpg?profile=your-profile. When profile settings are changed, all images referencing that profile are changed. 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 v3 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 YOUR_ACCESS_KEY, YOUR_SECRET_KEY and ACCOUNT_NAME with your Sirv S3 connection details:

s3cmd --host=s3.sirv.com --host-bucket=s3.sirv.com --access_key=YOUR_ACCESS_KEY --secret_key=YOUR_SECRET_KEY ls s3://ACCOUNT_NAME/

AWS SDK for PHP

If you’re using PHP, the following instructions will help you work with the AWS SDK for PHP.

  1. Download the latest version of the AWS SDK for PHP.
  2. Require the AWS SDK for PHP library:
    require 'aws_sdk/aws-autoloader.php';
    use AwsS3S3Client;
    use AwsS3ExceptionS3Exception;
  3. Define your key, secret and bucket – get these from your Settings page.
    define('AWS_KEY', 'ENTER_YOUR_SIRV_S3_KEY_HERE');
    define('AWS_SECRET_KEY', 'ENTER_YOUR_SIRV_S3_SECRET_HERE');
    define("BUCKET", 'ENTER_YOUR_SIRV_S3_BUCKET_HERE');
    define('HOST', 'http://s3.sirv.com');
  4. Initialize the S3 client:
    /**
    * Create and return new S3 Client
    *
    * @param string $host usually http://s3.sirv.com
    * @param string $aws_key your AWS Key
    * @param string $aws_secret_key your AWS SECRET KEY
    *
    * @return S3Client object
    */
    function get_s3client($host, $aws_key, $aws_secret_key) {
      return S3Client::factory(array(
        'base_url' => $host,
        'key' => $aws_key,
        'secret' => $aws_secret_key)
      );
    }
    $s3client = get_s3client(HOST, AWS_KEY, AWS_SECRET_KEY);
  5. Get a list of the objects:
    /**
    * Get information about all files in folder
    *
    * @param string $bucket Your bucket name.
    * @param string $folder Folder name you wish to get list of objects from. Using format "folder1/" or "Spin/11/".
    * @param S3Client $s3client
    * @param boolean $isIterable if True then return Iterator. By default set to false.
    *
    * @return object or Iterator
    */
    function get_object_list($bucket, $folder, $s3client, $isIterable = false) {
      $command = $s3client ->
      getCommand('ListObjects', array(
        'Bucket' => BUCKET,
        'Prefix' => $folder,
      ));
      if ($isIterable) {
        return $s3client ->
        getIterator($command);
      } else {
        return $command ->
        getResult();
      }
    }
    $iterator = get_object_list(BUCKET, 'folder-name/', $s3client);
    foreach($iterator as $object) {
      echo "{$object['Key']}t{$object['Size']}t{$object['LastModified']}";
    }

Now you can perform some common actions.

Upload files to Sirv

/**
* Upload files to the Sirv cloud
*
* @param string $bucket Your bucket name.
* @param string $folder Folder name where files will be uploaded. Using format "folder1/" or "Spin/11/".
* @param S3Client $s3client
* @param Array[] $array_paths_to_files Array of file paths to be uploaded to server e.g. "/var/www/images/image1.jpg".
*/
function upload_files($bucket, $folder, $s3client, $array_paths_to_files){
  foreach ($array_paths_to_files as $file_path) {
    $commands[] = $s3client->getCommand('PutObject', array(
      'Bucket' => $bucket,
      'Key' => $folder.basename($file_path),
      'SourceFile' => $file_path
    ));
  }
  try{
    $s3client->execute($commands);
    //or in loop
    /* foreach ($commands as $command) {
    $result = $command->getResult();
      // Do something with result
    }*/
  }catch(S3Exception $e){
    echo $e->getMessage();
  }
}
$images = array('image1.jpg','image2.jpg','image3.jpg');
upload_files(BUCKET, 'folder-name/sub-folder/', $s3client, $images);

Check if a file exists

/**
* Check if file exists on server or not
*
* @param string $bucket Your bucket name.
* @param string $folder Folder name where file should exist. Using format like "folder1/" or "Spin/11/".
* @param S3Client $s3client
* @param string $filenane File name that you're looking for e.g. "image.png".
*
* @return boolean true if file exists or false if not
*/
function isFileExists($bucket, $folder, $s3client, $filenane){
  $iter_object = get_object_list($bucket, $folder, $s3client, true);
  foreach ($iter_object as $object) {
    if ($object['Key'] === $filenane){
      return true;
    }
  }
  return false;
}
$fname = "image.jpg";
if(isFileExists(BUCKET, 'folder-name/', $s3client, $fname)) {
  // File exists
}else{
  // File does not exist
}

Create a folder

/**
* Create folder on the Sirv cloud
*
* @param string $bucket Your bucket name.
* @param string $folder Folder name to be created e.g. to create a folder in another folder "other/New_folder/",
*
* @return string message if folder already exists or nothing
*/
function create_folder($bucket, $folder, $s3client){
  try{
    $result = $s3client->putObject(array(
      'Bucket' => $bucket,
      'Key' => $folder,
      'Body' => "",
    ));
    print_r($result);
  }catch(S3Exception $e){
    echo $e->getMessage();
  }
}
create_folder(BUCKET, "folder-name/new-folder-name/", $s3client);

Delete a folder

/**
* Delete all files in folder and optionally delete files in subfolders
*
* @param string $bucket Your bucket name.
* @param string $folder Folder name where files should be deleted. Using format "folder1/" or "Spin/11/".
* @param S3Client $s3client
* @param boolean $isRecursive True if you need to delete files in subfolders. By default isRecursive = false.
*/
function delete_folder($bucket, $folder, $s3client, $isRecursive=false){
  $filenames = $s3client->listObjects(array(
    'Bucket' => $bucket,
    'Prefix' => $folder
  ))->getPath('Contents/*/Key');
  delete_files($bucket, $folder, $s3client, $filenames);
  if ($isRecursive){
    $prefixes = $s3client->listObjects(array(
      'Bucket' => $bucket,
      'Prefix' => $folder
    ))->getPath('CommonPrefixes/*/Prefix');
    if (count($prefixes) > 0){
      foreach ($prefixes as $prefix) {
        delete_folder($bucket, $folder.$prefix, $s3client, $isRecursive=true);
      }
    }
  }
}
delete_folder(BUCKET, 'folder-name/folder-to-delete/', $s3client, true);

Delete files

$images = array('image1.jpg','image2.jpg','image3.jpg');
delete_files(BUCKET, 'folder-name/', $s3client, $images);

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 some 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 meta-data 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, "TEST/", emptyContent, metadata);
        // send request to S3 to create 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());
    }
  }
}

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.
<html>
<head>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.43.min.js"></script>
</head>
<body>
  <div id="results"></div>
  <input type="file" id="file-chooser" />
  <button id="upload-button">Upload to S3</button>
  <script>
    AWS.config.update({
      'accessKeyId': 'YOUR_SIRV_S3_KEY',
      'secretAccessKey': 'YOUR_SIRV_S3_SECRET',
      s3ForcePathStyle: true
    });
    var s3 = new AWS.S3({
      endpoint: new AWS.Endpoint('https://s3.sirv.com'),
      params: {
        Bucket: 'YOUR_SIRV_S3_BUCKET'
      }
    });
    var fileChooser = document.getElementById('file-chooser');
    var button = document.getElementById('upload-button');
    var results = document.getElementById('results');
    button.addEventListener('click', function () {
      var file = fileChooser.files[0];
      if (file) {
        results.innerHTML = '';
        var objKey = file.name;
        var params = {
          Key: objKey,
          ContentType: file.type,
          Body: file
        };
        s3.putObject(params, function (err, data) {
          if (err) {
            results.innerHTML = 'ERROR: ' + err;
          } else {
            listObjs();
          }
        });
      } else {
        results.innerHTML = 'Nothing to upload.';
      }
    }, false);
    function listObjs() {
      var prefix = '';
      s3.listObjects({
        Prefix: prefix
      }, function (err, data) {
        if (err) {
          results.innerHTML = 'ERROR: ' + err;
        } else {
          var objKeys = "";
          data.Contents.forEach(function (obj) {
            objKeys += obj.Key + "<br>";
          });
          results.innerHTML = objKeys;
        }
      });
    }
  // listObjs();
  </script>
</body>
</html>

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 => 'https://s3.sirv.com',
  :region => 'us-east-1',
  :force_path_style => true,
  :signature_version => 's3',
  :credentials => Aws::Credentials.new(
    'YOUR_SIRV_S3_KEY',
    'YOUR_SIRV_S3_SECRET'
  )
)
s3.buckets.limit(50).each do |b|
  puts "#{b.name}"
end

Was this article helpful?