# REST API Node.js Examples

Use the Sirv [REST API](/help/rest-api/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.

Using an AI coding agent?

Install the [`sirv-api`](https://www.skills.sh/sirv/image-optimization-skill/sirv-api) skill, and your agent can call the Sirv API for you. Ask in plain words, such as “Upload the photos in /shoots/spring and tag them by product.” [See all 8 skills](/help/rest-api/sirv-skills-for-ai-agents/)

Visit the [REST API reference](/help/rest-api/reference/) for a list of all methods.

## Connect to Sirv with Node.js

First, you should [create an API client](https://app.sirv.com/settings/api) 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:

```js
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](/help/rest-api/reference/).

## 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.

-   Endpoint: `https://api.sirv.com/v2/files/upload`
-   Documentation: [Upload file](/help/rest-api/reference/upload-download/upload-file/)

Example upload script:

```js
import { readFile } from 'node:fs/promises';

// Your bearer token, from POST /v2/token, in the SIRV_TOKEN environment variable
const 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

-   Endpoint: `https://api.sirv.com/v2/files/search`
-   Documentation: [Search files](/help/rest-api/reference/files/search-files/#search-files)
-   Search options: [Search files with the API](/help/rest-api/search-files-with-the-api/)

This Node.js example script will search for all .[spin files](/help/spin/getting-started/how-spin-files-are-created/):

```js
// Your bearer token, from POST /v2/token, in the SIRV_TOKEN environment variable
const 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:

```js
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:

```js
const query = 'basename:pine AND dirname.paths:\\/furniture\\/tables';
```

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

```js
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:

```js
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:

```js
const query = 'contentType:image\\/jpeg AND dirname.paths:\\/products AND size:>3000000';
```

### JWT protected URLs

-   Endpoint: `https://api.sirv.com/v2/files/jwt`
-   Documentation: [Get JWT protected URL](/help/rest-api/reference/folder-settings/jwt-protected-url/)

After enabling [JWT signed URLs on a folder](/help/guides/protected-urls-with-json-web-tokens/) - 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):

```js
'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());
```

Open the URL in a browser to check that the protected image loads.
