Sirv REST API – Node.js examples

On this page

Use the Sirv REST API to perform over 40 common tasks on your Sirv account, such as uploading, searching, converting videos to spins, adding meta, fetching a remote image by URL and more.

Visit the REST API reference for a list of all methods.

Connect to Sirv with Node.js

First, you should create an API client in your Sirv account. You'll be given a client ID and client Secret.

Use your client ID and secret in the script below to request a token:

'use strict';

const http = require('https');

const options = {
  'method': 'POST',
  'hostname': 'api.sirv.com',
  'path': '/v2/token',
  'headers': {
  'content-type': 'application/json'
  }
};

const clientId = 'ENTER_CLIENT_ID_HERE';
const clientSecret = 'ENTER_CLIENT_SECRET_HERE';

const req = http.request(options, (res) => {
  const chunks = [];

  res.on('data', (chunk) => {
  chunks.push(chunk);
  });

  res.on('end', () => {
  const body = Buffer.concat(chunks);
  const apiResponse = JSON.parse(body.toString());

  console.log('token:', apiResponse.token);
  console.log('expiresIn:', apiResponse.expiresIn);
  console.log('scope:', apiResponse.scope);
  });
});

req.write(JSON.stringify({
  clientId,
  clientSecret
}));

req.end();

Once you have a token, you can perform any of the 40+ REST API methods.

Example scripts

The sample scripts below will show you some typical uses of the REST API.

Upload file

Upload a file to your Sirv account.

Example upload script:

var request = require("request");
var fs = require("fs");

fs.readFile('/path/to/local-file.jpg', (err, data) => {
 if (err) throw err;

 var options = {
  method: 'POST',
  url: 'https://api.sirv.com/v2/files/upload',
  qs: {filename: '/path/to/uploaded-image.jpg'},
  headers: {
   'content-type': 'image/jpeg',
   authorization: 'Bearer eyJhb...BZCSg'
  },
  body: data
 };

 request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
 });

});

This Node.js example script will search for all .spin files:

var http = require("https");

var options = {
 "method": "POST",
 "hostname": "api.sirv.com",
 "port": null,
 "path": "/v2/files/search",
 "headers": {
  "content-type": "application/json",
  "content-length": "30",
  "authorization": "Bearer RECEIVED_AUTH_TOKEN_HERE"
 }
};

var req = http.request(options, function (res) {
 var chunks = [];

 res.on("data", function (chunk) {
  chunks.push(chunk);
 });

 res.on("end", function () {
  var body = Buffer.concat(chunks);
  console.log(body.toString());
 });
});

req.write(JSON.stringify({ query: 'extension:.spin' }));
req.end();

Change the req.write line to search by different parameters. The following will search for files with the name "pine" in the /furniture/tables folder only:

req.write(JSON.stringify({ query: 'basename:pine AND dirname.raw:\\/furniture\\/tables' }));

This will also search for files named "pine" but in /furniture/tables and also its subfolders:

req.write(JSON.stringify({ query: 'basename:pine AND dirname.paths:\\/furniture\\/tables' }));

This will search for all files uploaded between 15/10/2022 and 25/10/2022:

req.write(JSON.stringify({ query: 'mtime:[2022-10-15 TO 2022-10-25]' }));

This will search for all JPEG files in the /products folder with size greater than 3MB:

req.write(JSON.stringify({ query: 'contentType:image\\/jpeg AND dirname.raw:\\/products AND size:>3000000' }));

This will perform the same search as above but also with all sub-folders of the /products folder:

req.write(JSON.stringify({ query: 'contentType:image\\/jpeg AND dirname.paths:\\/products AND size:>3000000' }));

JWT protected URLs

After enabling JWT signed URLs on a folder - to protect its content - you can generate a signed URL allowing the file to be served with restrictions, such as an expiry date or certain image transformations. Parameters can be secure (uneditable) or insecure (editable).

The following Node.js script applies width of 500px, height of 25%, some secure (irremovable) text of "Hello!" and an expiry of 1 year (31536000 seconds):

'use strict';

const { URLSearchParams } = require('url');
const jwt = require('jsonwebtoken');

const filename = '/DSC_5118.JPG';

const params = new URLSearchParams({ // put insecure parameters here
  w: '500',
  h: '25%'
});

const data = {
  args: { // put secure parameters here
    text: 'Hello!'
    }
};

const key = 'topsecret';

// generate token
const token = jwt.sign(data, key, {
  algorithm: 'HS256',
  expiresIn: 31536000, // seconds
  audience: filename,
  keyid: 'key1' // optional
});

params.append('jwt', token);

console.log('http://exampleaccount.sirv.com' + filename + '?' + params.toString());

Support

If you need help connecting with Node.js or using any of the Sirv REST API methods, please contact the Sirv support team.

Was this article helpful?

Get help from a Sirv expert

help ukraine help ukraine Powered by Ukrainian determination and British ingenuity

How can you support Ukraine