REST API Node.js Examples
Short answer
Create an API client in your Sirv account and use its client ID and secret in a Node.js script to request a bearer token. Every other API call sends that token. The example scripts show common tasks such as uploading, searching, converting videos to spins, adding meta and fetching remote images.
After reading this you will know
- How to get a bearer token with Node.js
- Which tasks the Node.js example scripts cover
- Where to find every REST API method
Use the Sirv REST API to perform more than 60 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
Section titled “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.
Keep your client ID and secret in the SIRV_CLIENT_ID and SIRV_CLIENT_SECRET environment variables, not in the code. This script (Node.js 18+) gets a token with them:
const res = await fetch('https://api.sirv.com/v2/token', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ clientId: process.env.SIRV_CLIENT_ID, clientSecret: process.env.SIRV_CLIENT_SECRET, }),});const { token, expiresIn, scope } = await res.json();
console.log('token:', token);console.log('expiresIn:', expiresIn);console.log('scope:', scope);Save the token in the SIRV_TOKEN environment variable. Then you can perform any of the more than 60 REST API methods.
Example scripts
Section titled “Example scripts”The sample scripts below will show you some typical uses of the REST API.
Upload file
Section titled “Upload file”Upload a file to your Sirv account.
- Endpoint: https://api.sirv.com/v2/files/upload
- Documentation: Upload file
Example upload script:
import { readFile } from 'node:fs/promises';
// Your bearer token, from POST /v2/token, in the SIRV_TOKEN environment variableconst filename = encodeURIComponent('/path/to/uploaded-image.jpg');const res = await fetch(`https://api.sirv.com/v2/files/upload?filename=${filename}`, { method: 'POST', headers: { authorization: `Bearer ${process.env.SIRV_TOKEN}`, 'content-type': 'image/jpeg' }, body: await readFile('/path/to/local-file.jpg'),});console.log(res.status, await res.text());Search
Section titled “Search”- Endpoint: https://api.sirv.com/v2/files/search
- Documentation: Search files
- Search options: Search files with the API
This Node.js example script will search for all .spin files:
// Your bearer token, from POST /v2/token, in the SIRV_TOKEN environment variableconst query = 'extension:.spin';
const res = await fetch('https://api.sirv.com/v2/files/search', { method: 'POST', headers: { authorization: `Bearer ${process.env.SIRV_TOKEN}`, 'content-type': 'application/json' }, body: JSON.stringify({ query }),});console.log(await res.json());Change the query line to search by different parameters. The following will search for files with the name “pine” in the /furniture/tables folder only:
const query = 'basename:pine AND dirname.raw:\\/furniture\\/tables';This will also search for files named “pine” but in /furniture/tables and also its subfolders:
const query = 'basename:pine AND dirname.paths:\\/furniture\\/tables';This will search for all files uploaded between 15/10/2022 and 25/10/2022:
const 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:
const 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:
const query = 'contentType:image\\/jpeg AND dirname.paths:\\/products AND size:>3000000';JWT protected URLs
Section titled “JWT protected URLs”- Endpoint: https://api.sirv.com/v2/files/jwt
- Documentation: Get JWT protected URL
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 tokenconst 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());Open the URL in a browser to check that the protected image loads.
