Post to social media from Google Sheets with Ampost

By Published Updated

An Apps Script in your sheet can call Ampost's REST API: each row becomes a post, published now or at the time in its Schedule column, and the script writes the result back into the row. Paste the script below, add your API key as a script property, and use the Ampost menu.

What you'll build

  • A Posts sheet where each row is a post: text, networks, an optional link, image or video, and an optional time.
  • An Ampost menu in the sheet to post pending rows, and an optional trigger that checks every 15 minutes.
  • Status and Post ID columns that the script fills in, so you can see what was posted and what failed.

Before you start

  • An Ampost account. The Free plan includes the REST API (2 social accounts and 15 posts every 30 days); scheduling needs the Pro plan or higher, and X the Max and Scale plans. See pricing.
  • An API key from Settings, API keys. The key is shown once, so copy it when you create it. Treat it like a password.
  • At least one connected social account, under Settings, Connections in the dashboard.
  • A Google account and a Google Sheet you can edit.

Download

Free to use and change. The file is shown in full below, so you can read it before you run it.

ampost-sheets.gs
/**
 * Post to social media from Google Sheets with the Ampost API.
 *
 * Each row of the "Posts" sheet is one post. The script sends every row whose
 * Status is empty to Ampost and writes the result back into the row.
 *
 * Columns (row 1 is the header, this order):
 *   A Text           the post text (required)
 *   B Platforms      comma-separated, e.g. bluesky,threads,discord (required)
 *   C Link           optional link (linkUrl)
 *   D Media URL      optional public https URL of an image or video
 *   E Media type     image or video (default image)
 *   F Schedule (UTC) optional ISO 8601 time, e.g. 2027-01-14T15:00:00Z; empty posts now
 *   G Status         written by the script: the post's status, or the error
 *   H Post ID        written by the script
 *
 * Setup (guide: https://ampost.io/how-to/post-to-social-media-from-google-sheets):
 *   1. Extensions > Apps Script, paste this file, save.
 *   2. Project Settings > Script properties: add AMPOST_API_KEY with an API key from
 *      https://ampost.io/app/settings/api-keys
 *   3. Reload the sheet and use the Ampost menu: "Set up the Posts sheet", then
 *      "Post pending rows". "Check every 15 minutes" posts new rows automatically.
 */

var AMPOST_API_URL = "https://api.ampost.io";
var SHEET_NAME = "Posts";
var HEADERS = ["Text", "Platforms", "Link", "Media URL", "Media type", "Schedule (UTC)", "Status", "Post ID"];
var COL = { text: 0, platforms: 1, link: 2, mediaUrl: 3, mediaType: 4, schedule: 5, status: 6, postId: 7 };

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu("Ampost")
    .addItem("Set up the Posts sheet", "setUpSheet")
    .addItem("Post pending rows", "postPendingRows")
    .addItem("Check every 15 minutes", "installTrigger")
    .addToUi();
}

/** Creates the Posts sheet with its header row. */
function setUpSheet() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName(SHEET_NAME) || spreadsheet.insertSheet(SHEET_NAME);
  sheet.getRange(1, 1, 1, HEADERS.length).setValues([HEADERS]).setFontWeight("bold");
  sheet.setFrozenRows(1);
}

/** Sends every row with an empty Status to Ampost; returns how many rows it sent. */
function postPendingRows() {
  var apiKey = PropertiesService.getScriptProperties().getProperty("AMPOST_API_KEY");
  if (!apiKey) throw new Error("Add the AMPOST_API_KEY script property (Project Settings > Script properties).");

  var lock = LockService.getScriptLock();
  if (!lock.tryLock(30000)) return 0; // another run is still posting
  try {
    var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = spreadsheet.getSheetByName(SHEET_NAME);
    if (!sheet) throw new Error('No "' + SHEET_NAME + '" sheet. Use Ampost > Set up the Posts sheet.');
    var lastRow = sheet.getLastRow();
    if (lastRow < 2) return 0;

    var rows = sheet.getRange(2, 1, lastRow - 1, HEADERS.length).getValues();
    var sent = 0;
    for (var i = 0; i < rows.length; i++) {
      var row = rows[i];
      if (String(row[COL.text]).trim() === "" || String(row[COL.status]).trim() !== "") continue;
      var rowNumber = i + 2;
      var result = createPost(apiKey, buildBody(row), idempotencyKey(spreadsheet.getId(), rowNumber, row));
      if (result.retry) break; // rate limited or Ampost unavailable: the row stays pending for the next run
      sheet.getRange(rowNumber, COL.status + 1, 1, 2).setValues([[result.status, result.postId]]);
      SpreadsheetApp.flush();
      sent++;
    }
    return sent;
  } finally {
    lock.releaseLock();
  }
}

/** The POST /api/posts body for one row. */
function buildBody(row) {
  var platforms = String(row[COL.platforms])
    .split(",")
    .map(function (platform) { return platform.trim().toLowerCase(); })
    .filter(function (platform) { return platform !== ""; });
  var body = { targets: [{ platforms: platforms }], text: String(row[COL.text]) };
  var link = String(row[COL.link]).trim();
  if (link) body.linkUrl = link;
  var mediaUrl = String(row[COL.mediaUrl]).trim();
  if (mediaUrl) body.media = [{ url: mediaUrl, type: String(row[COL.mediaType]).trim().toLowerCase() || "image" }];
  var schedule = row[COL.schedule];
  // A date cell is a Date; a typed time stays text.
  if (Object.prototype.toString.call(schedule) === "[object Date]") body.scheduledFor = schedule.toISOString();
  else if (String(schedule).trim()) body.scheduledFor = String(schedule).trim();
  else body.publishNow = true;
  return body;
}

/** Same row, same content: the same key, so Ampost never posts a row twice. */
function idempotencyKey(spreadsheetId, rowNumber, row) {
  var digest = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, JSON.stringify([spreadsheetId, rowNumber, row.slice(0, COL.status)]));
  return "sheets-" + Utilities.base64EncodeWebSafe(digest).replace(/=+$/, "");
}

/**
 * Calls Ampost and returns { status, postId } for the Status and Post ID columns,
 * or { retry: true } when the request should be sent again later.
 */
function createPost(apiKey, body, key) {
  var response = UrlFetchApp.fetch(AMPOST_API_URL + "/api/posts", {
    method: "post",
    contentType: "application/json",
    headers: { Authorization: "Bearer " + apiKey, "Idempotency-Key": key },
    payload: JSON.stringify(body),
    muteHttpExceptions: true,
  });
  var code = response.getResponseCode();
  var json = {};
  try { json = JSON.parse(response.getContentText()); } catch (error) { /* not JSON */ }
  if (code === 200 || code === 201) return { status: json.status, postId: json.id };
  if (code === 429 || code >= 500) return { retry: true };
  var error = json.error || {};
  return { status: "Error " + code + ": " + (error.code || "") + " " + (error.message || response.getContentText()).slice(0, 300), postId: "" };
}

/** Runs postPendingRows every 15 minutes. */
function installTrigger() {
  var triggers = ScriptApp.getProjectTriggers();
  for (var i = 0; i < triggers.length; i++) {
    if (triggers[i].getHandlerFunction() === "postPendingRows") return;
  }
  ScriptApp.newTrigger("postPendingRows").timeBased().everyMinutes(15).create();
}

Steps

  1. 1. Paste the script into the sheet

    In your sheet, open Extensions, Apps Script. Replace the editor's contents with ampost-sheets.gs from the download above and click Save.

  2. 2. Add your API key as a script property

    In the Apps Script editor, open Project Settings (the gear), Script properties, Add script property: AMPOST_API_KEY with your key. Anyone who can edit the sheet can open its Apps Script project and read the key, so give edit access only to people you would trust with the key.

    Project Settings > Script properties
    Property  AMPOST_API_KEY
    Value     amp_live_your_key_here
  3. 3. Set up the Posts sheet

    Reload the sheet. An Ampost menu appears; choose Set up the Posts sheet. Google asks you to authorize the script the first time: it needs your spreadsheet and external requests (to call Ampost).

    The Posts sheet gets its header row: Text, Platforms, Link, Media URL, Media type, Schedule (UTC), Status, Post ID.

  4. 4. Add your posts

    Write one post per row. Platforms is a comma-separated list: instagram (Instagram), facebook (Facebook), linkedin (LinkedIn), tiktok (TikTok), threads (Threads), twitter (X), discord (Discord), telegram (Telegram), bluesky (Bluesky), youtube (YouTube), pinterest (Pinterest). Leave Schedule empty to post at once, or put a UTC time such as 2027-01-14T15:00:00Z (a date cell works too). Leave Status empty: the script fills it in.

    Posts
    Text                           | Platforms       | Link                     | Media URL | Media type | Schedule (UTC)
    Our spring sale starts today!  | bluesky,threads | https://example.com/sale |           |            |
    Behind the scenes at the shop  | instagram       |                          | https://example.com/shop.jpg | image |
  5. 5. Post the pending rows

    Choose Ampost, Post pending rows. Each row with an empty Status is sent to Ampost, and the row gets the post's status and id, or the error. To post new rows automatically, choose Check every 15 minutes once.

How the script avoids double posts

A row is sent only while its Status is empty, a lock stops two runs from overlapping, and each request carries an Idempotency-Key made from the sheet, the row and its content: if a run is interrupted after Ampost got the post, the next run gets the same post back instead of a second one.

If Ampost answers 429 or a server error, the row stays pending and the next run retries it. Other errors are written into Status, for example Error 400: VALIDATION_FAILED ...; fix the row and clear its Status to send it again.

FAQ

Do I need a Google Sheets add-on?

No. The script runs in your own sheet's Apps Script project, with your own API key, so nothing is installed from the Marketplace.

Why do I need a paid plan for the Schedule column?

The sheet hands scheduled rows to Ampost at once and Ampost publishes them at their time, which is the scheduling feature. On the Free plan, leave Schedule empty and turn on the 15-minute trigger instead.

Which social networks can I post to from Google Sheets?

Every network you connect to Ampost: Instagram, Facebook, LinkedIn, TikTok, Threads, X, Discord, Telegram, Bluesky, YouTube, Pinterest. Name them by key in targets[].platforms; X is twitter. LinkedIn and TikTok are coming soon.

Can I schedule a post instead of publishing it now?

Yes. Send scheduledFor with an ISO 8601 time (for example 2027-01-14T15:00:00Z) instead of publishNow: true, and Ampost publishes it then. Scheduling needs the Pro plan or higher.

What happens if the same request is sent twice?

The templates send an Idempotency-Key header. A retry with the same key within 24 hours returns the first post instead of creating a second one, so a retried step never posts twice.