---
title: "Send Envelopes From Google Sheets Rows"
description: "Send a SignatureAPI envelope for every new Google Sheets row with Apps Script, and write each status back with a time-driven trigger."
canonical: "https://signatureapi.com/docs/integrations/google-apps-script"
source: "https://signatureapi.com/docs/integrations/google-apps-script.md"
last_verified_api_version: "1.18.0"
---

# Send Envelopes From Google Sheets Rows

Send a SignatureAPI envelope for every new Google Sheets row with Apps Script, and write each status back with a time-driven trigger.

_Last verified against API version 1.18.0._

Google Apps Script runs inside the sheet and calls the SignatureAPI REST API with `UrlFetchApp`. No SignatureAPI app is needed: a menu item creates an envelope for each new row, and a time-driven trigger writes each envelope's status back.

Full code on GitHub: [`no-code/apps-script`](https://github.com/signatureapi/examples/tree/main/no-code/apps-script).

## Before you start

- A SignatureAPI [test API key](https://signatureapi.com/docs/api/test-mode) (it starts with `key_test_`).
- The document you send, at a URL on a [supported host](https://signatureapi.com/docs/api/resources/documents/url#external-store), or [uploaded to SignatureAPI](https://signatureapi.com/docs/api/resources/uploads/create) first. The examples use a sample PDF.
- A Google Sheet with this header in row 1: `name`, `email`, `role`, `envelope_id`, `status`. One row is one signer.

## Send the envelopes

1. **Open the script editor**

   In the sheet, choose **Extensions**, then **Apps Script** ([Apps Script overview](https://developers.google.com/apps-script/overview)). Create two files, `Core.gs` and `Code.gs`, and paste the code below.

2. **Store the key**

   In **Project Settings**, under **Script Properties**, click **Add script property**. Enter `SIGNATUREAPI_KEY` as the **Property** and your key as the **Value**, then click **Save script properties** ([Properties Service](https://developers.google.com/apps-script/guides/properties)). Script properties are shared by everyone who uses the script, so share the script with care.

3. **Set the scopes**

   The script calls `UrlFetchApp`, which needs the `https://www.googleapis.com/auth/script.external_request` scope. Apps Script usually detects it. If you set scopes in the manifest, add it yourself ([UrlFetchApp](https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app)).

4. **Run it**

   Reload the sheet and open the **SignatureAPI** menu. The menu comes from an `onOpen` function in a script bound to the sheet ([Custom menus](https://developers.google.com/apps-script/guides/menus)). Choose **Send envelopes for new rows** and approve the authorization prompt. Each row with no `envelope_id` gets an envelope, and the id and status are written into columns D and E.

```javascript Core.gs
// Platform-agnostic core. No Google services are used here: the HTTP call is injected.

var SIGNATUREAPI_DOC_URL = 'https://pub-9cb75390636c4a8a83a6f76da33d7f45.r2.dev/docs-samples/service-agreement.pdf';
var SIGNATUREAPI_BASE_URL = 'https://api.signatureapi.com';
var SIGNATUREAPI_CLIENT_LINE = { page: 1, top: 172, left: 210 };

// One sheet row -> one CreateEnvelope request body.
function buildEnvelopePayload_(rec) {
  return {
    title: 'Service Agreement - ' + rec.name,
    message: 'Please review and sign the service agreement.',
    metadata: { source: 'google_sheets', sheet_row: String(rec.rowNumber) },
    topics: ['no_code', 'sheets'],
    documents: [
      {
        key: 'service_agreement',
        url: SIGNATUREAPI_DOC_URL,
        format: 'pdf',
        fixed_positions: [
          { place_key: 'signer_signature', page: SIGNATUREAPI_CLIENT_LINE.page, top: SIGNATUREAPI_CLIENT_LINE.top, left: SIGNATUREAPI_CLIENT_LINE.left },
        ],
        places: [{ key: 'signer_signature', type: 'signature', recipient_key: 'signer' }],
      },
    ],
    recipients: [{ type: 'signer', key: 'signer', name: rec.name, email: rec.email }],
  };
}

// values = sheet.getDataRange().getValues(). Header row: name, email, role, envelope_id, status.
// Returns the rows that still need an envelope (empty envelope_id, name and email present).
function pendingRows_(values) {
  var header = values[0].map(function (h) { return String(h).trim().toLowerCase(); });
  var col = {};
  ['name', 'email', 'role', 'envelope_id', 'status'].forEach(function (n) {
    col[n] = header.indexOf(n);
    if (col[n] < 0) throw new Error('Missing column: ' + n);
  });
  var out = [];
  for (var i = 1; i < values.length; i += 1) {
    var row = values[i];
    if (String(row[col.envelope_id]).trim() === '' && String(row[col.email]).trim() !== '' && String(row[col.name]).trim() !== '') {
      out.push({ rowNumber: i + 1, name: String(row[col.name]).trim(), email: String(row[col.email]).trim(), role: String(row[col.role]).trim(), col: col });
    }
  }
  return out;
}

// http(url, { method, headers, contentType, body }) -> { status, body }  (synchronous)
function apiCall_(apiKey, baseUrl, http, method, path, json) {
  var opts = { method: method, headers: { 'X-API-Key': apiKey } };
  if (json !== undefined) {
    opts.contentType = 'application/json';
    opts.body = JSON.stringify(json);
  }
  var res = http((baseUrl || SIGNATUREAPI_BASE_URL) + path, opts);
  var data = null;
  try { data = res.body ? JSON.parse(res.body) : null; } catch (e) { data = { raw: res.body }; }
  if (res.status < 200 || res.status >= 300) {
    throw new Error(method + ' ' + path + ' failed with ' + res.status + ': ' + ((data && (data.detail || data.title)) || res.body));
  }
  return data;
}

function createEnvelope_(apiKey, payload, http, baseUrl) {
  return apiCall_(apiKey, baseUrl, http, 'POST', '/v1/envelopes', payload);
}

function getEnvelope_(apiKey, id, http, baseUrl) {
  if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id)) throw new Error('Not an envelope id');
  return apiCall_(apiKey, baseUrl, http, 'GET', '/v1/envelopes/' + id);
}
```

```javascript Code.gs
// Thin Google Apps Script shim around Core.gs. Everything here talks to Google services.

function onOpen() {
  SpreadsheetApp.getUi().createMenu('SignatureAPI').addItem('Send envelopes for new rows', 'sendEnvelopesFromSheet').addToUi();
}

function apiKey_() {
  return PropertiesService.getScriptProperties().getProperty('SIGNATUREAPI_KEY');
}

function httpFetch_(url, opts) {
  var params = { method: opts.method, headers: opts.headers, muteHttpExceptions: true };
  if (opts.body !== undefined) {
    params.payload = opts.body;
    params.contentType = opts.contentType;
  }
  var res = UrlFetchApp.fetch(url, params);
  return { status: res.getResponseCode(), body: res.getContentText() };
}

// Sends one envelope for every row that has no envelope_id yet, then writes the id and status back.
function sendEnvelopesFromSheet() {
  var key = apiKey_();
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = pendingRows_(sheet.getDataRange().getValues());
  rows.forEach(function (rec) {
    try {
      var envelope = createEnvelope_(key, buildEnvelopePayload_(rec), httpFetch_);
      sheet.getRange(rec.rowNumber, rec.col.envelope_id + 1, 1, 2).setValues([[envelope.id, envelope.status]]);
    } catch (e) {
      sheet.getRange(rec.rowNumber, rec.col.status + 1).setValue('error: ' + e.message);
    }
    Utilities.sleep(200); // stay inside the rate limit
  });
}

// Reads every unfinished envelope on the first sheet and writes its current status into the row.
function refreshStatuses() {
  var key = apiKey_();
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
  var values = sheet.getDataRange().getValues();
  var header = values[0].map(function (h) { return String(h).trim().toLowerCase(); });
  var idCol = header.indexOf('envelope_id');
  var statusCol = header.indexOf('status');
  for (var i = 1; i < values.length; i += 1) {
    var id = String(values[i][idCol]).trim();
    var status = String(values[i][statusCol]);
    if (id === '' || ['completed', 'canceled', 'failed'].indexOf(status) >= 0) continue;
    try {
      sheet.getRange(i + 1, statusCol + 1).setValue(getEnvelope_(key, id, httpFetch_).status);
    } catch (e) {
      sheet.getRange(i + 1, statusCol + 1).setValue('error: ' + e.message);
    }
    Utilities.sleep(200); // stay inside the rate limit
  }
}

// Run once from the editor: refreshes the statuses every hour.
function installRefreshTrigger() {
  ScriptApp.newTrigger('refreshStatuses').timeBased().everyHours(1).create();
}
```

HTTP request step settings for the "Sheet row" request:

1. **Method**: POST
2. **URL**: `https://api.signatureapi.com/v1/envelopes`
3. **Header**: `X-API-Key: YOUR_API_KEY`

   Store the key in your tool's secret or credential storage when it has one.
4. **Header**: `Content-Type: application/json`
5. **Body (raw JSON)**:

   ```json
   {
     "title": "Service Agreement - Jane Doe",
     "message": "Please review and sign the service agreement.",
     "metadata": {
       "source": "google_sheets",
       "sheet_row": "2"
     },
     "topics": [
       "no_code",
       "sheets"
     ],
     "documents": [
       {
         "key": "service_agreement",
         "url": "https://pub-9cb75390636c4a8a83a6f76da33d7f45.r2.dev/docs-samples/service-agreement.pdf",
         "format": "pdf",
         "fixed_positions": [
           {
             "place_key": "signer_signature",
             "page": 1,
             "top": 172,
             "left": 210
           }
         ],
         "places": [
           {
             "key": "signer_signature",
             "type": "signature",
             "recipient_key": "signer"
           }
         ]
       }
     ],
     "recipients": [
       {
         "type": "signer",
         "key": "signer",
         "name": "Jane Doe",
         "email": "jane.doe@example.com"
       }
     ]
   }
   ```

The script sends exactly this request for sheet row 2: `Core.gs` builds it, and `httpFetch_` sends it with `muteHttpExceptions` set, so an API error comes back as a status and body. A failing row gets `error: ...` in its status cell and the loop continues. The 200 ms pause between rows keeps you inside the [rate limit](https://signatureapi.com/docs/api/rate-limiting). The `sheets` topic and `metadata.sheet_row` let you find these envelopes later.

## Get the result back

SignatureAPI counts a webhook delivery as successful only when the endpoint answers with a `2XX` status. An Apps Script web app answers through a redirect to a one-time URL on `script.googleusercontent.com` ([Content service](https://developers.google.com/apps-script/guides/content)), so it can't acknowledge a webhook. Read the statuses on a schedule instead.

1. **Install the time-driven trigger**

   In the editor, select `installRefreshTrigger` and click **Run** once. It creates an installable trigger that runs `refreshStatuses` every hour ([Installable triggers](https://developers.google.com/apps-script/guides/triggers/installable)).

2. **Read each open envelope**

   `refreshStatuses` skips rows without an id and rows already `completed`, `canceled` or `failed`. For every other row it reads the envelope with your key and writes the current `status`:

   HTTP request step settings for the "Completed envelope" request:

   1. **Method**: GET
   2. **URL**: `https://api.signatureapi.com/v1/envelopes/eb4cf433-a8af-4161-b37b-7ef57d423e56`
   3. **Header**: `X-API-Key: YOUR_API_KEY`

      Store the key in your tool's secret or credential storage when it has one.

Each read counts toward the [rate limit](https://signatureapi.com/docs/api/rate-limiting), so the function pauses 200 ms between rows. When a row turns `completed`, check `deliverable.status` in the same response before you download: `deliverable.url` is `null` until the deliverable is `generated`, and the link expires after an hour. If your account uses [authenticated deliverable URLs](https://signatureapi.com/docs/api/resources/deliverables/object#url), send your API key with the download. The script skips completed rows on later runs, so if you add a download, run it on every row that doesn't have its PDF yet, not only on rows that just turned `completed`.

## Related

- [Create an envelope](https://signatureapi.com/docs/api/resources/envelopes/create): every field of the request body.
- [Send bulk envelopes](https://signatureapi.com/docs/api/guides/use-cases/bulk-envelopes).
- [Forms to envelopes](https://signatureapi.com/docs/integrations/forms-to-envelope): Google Forms can start the same script.

### Example: Sheet row

The body the Apps Script core builds for sheet row 2.

```http
POST /v1/envelopes HTTP/1.1
Host: api.signatureapi.com
X-API-Key: YOUR_API_KEY
Content-Type: application/json

{
  "title": "Service Agreement - Jane Doe",
  "message": "Please review and sign the service agreement.",
  "metadata": {
    "source": "google_sheets",
    "sheet_row": "2"
  },
  "topics": [
    "no_code",
    "sheets"
  ],
  "documents": [
    {
      "key": "service_agreement",
      "url": "https://pub-9cb75390636c4a8a83a6f76da33d7f45.r2.dev/docs-samples/service-agreement.pdf",
      "format": "pdf",
      "fixed_positions": [
        {
          "place_key": "signer_signature",
          "page": 1,
          "top": 172,
          "left": 210
        }
      ],
      "places": [
        {
          "key": "signer_signature",
          "type": "signature",
          "recipient_key": "signer"
        }
      ]
    }
  ],
  "recipients": [
    {
      "type": "signer",
      "key": "signer",
      "name": "Jane Doe",
      "email": "jane.doe@example.com"
    }
  ]
}
```

Response 201 Created:

```json
{
  "id": "eb4cf433-a8af-4161-b37b-7ef57d423e56",
  "title": "Service Agreement - Jane Doe",
  "label": null,
  "message": "Please review and sign the service agreement.",
  "status": "processing",
  "attestation": "none",
  "language": "en",
  "mode": "test",
  "routing": "sequential",
  "timezone": "UTC",
  "timestamp_format": "MM/DD/YYYY HH:mm:ss",
  "snapshot_url": null,
  "branding": {
    "logo": null,
    "accent_color": "#2463EB",
    "email": {
      "footer": null,
      "logo_position": "left",
      "from": "noreply@signatureapi.com"
    }
  },
  "deliverable": {
    "id": "del_6FF89lKNyTNamOJCJd1tLL",
    "envelope_id": "eb4cf433-a8af-4161-b37b-7ef57d423e56",
    "name": null,
    "status": "pending",
    "type": "standard",
    "url": null,
    "password": null,
    "created_at": "2026-11-02T14:03:11.000Z",
    "generated_at": null,
    "timezone": "UTC",
    "language": "en",
    "timestamp_format": "MM/DD/YYYY HH:mm:ss",
    "included_documents": [
      "service_agreement"
    ]
  },
  "metadata": {
    "source": "google_sheets",
    "sheet_row": "2"
  },
  "sender": {
    "name": "Acme Corp Legal",
    "email": "legal@acme.example",
    "organization": "Acme Corp"
  },
  "captures": {},
  "documents": [
    {
      "id": "doc_HVl3Nj7XzTzX7jN3lVH5vn",
      "envelope_id": "eb4cf433-a8af-4161-b37b-7ef57d423e56",
      "key": "service_agreement",
      "title": null,
      "page_count": 1,
      "url": "https://pub-9cb75390636c4a8a83a6f76da33d7f45.r2.dev/docs-samples/service-agreement.pdf",
      "format": "pdf",
      "fixed_positions": [
        {
          "page": 1,
          "top": 172,
          "left": 210,
          "place_key": "signer_signature"
        }
      ],
      "places": [
        {
          "key": "signer_signature",
          "type": "signature",
          "recipient_key": "signer",
          "height": 60
        }
      ]
    }
  ],
  "recipients": [
    {
      "id": "re_49r1R2jpPDz8hSpP75ZkPp",
      "envelope_id": "eb4cf433-a8af-4161-b37b-7ef57d423e56",
      "type": "signer",
      "key": "signer",
      "email": "jane.doe@example.com",
      "name": "Jane Doe",
      "ceremony": {
        "authentication": [
          {
            "type": "email_link",
            "subject_override": null,
            "message_override": null
          }
        ],
        "embeddable_in": [],
        "redirect_url": null,
        "redirect_delay": 3,
        "url": null,
        "url_variant": "standard"
      },
      "ceremony_creation": "automatic",
      "delivery_type": "email",
      "signature_options": [
        "typed",
        "drawn"
      ],
      "status": "pending",
      "status_updated_at": "2026-11-02T14:03:11.000Z",
      "completed_at": null
    }
  ],
  "topics": [
    "no_code",
    "sheets"
  ],
  "created_at": "2026-11-02T14:03:11.000Z",
  "completed_at": null
}
```

Response 422 Unprocessable Content:

```json
{
  "type": "https://signatureapi.com/docs/v1/errors/validation-error",
  "title": "Validation Error",
  "status": 422,
  "errors": [
    "recipients[0].email must be a valid email address."
  ]
}
```

Errors that any request can return (authentication, rate limits, server errors) are on the [Errors](https://signatureapi.com/docs/api/errors) and [Authentication](https://signatureapi.com/docs/api/authentication) pages.
