GROperator

Create a shipment with an API key

You create shipments with an API key and secret sent as the X-API-Key and X-API-Secret headers: no login and no user token. This page walks through it with a complete example, a Google Sheet that creates shipments in bulk.

The script turns the sheet into a bulk shipment creator. It reads every row that has no tracking number yet, creates the shipment through the API, and writes back the tracking number, the status and a link to the label, or the error code and message so you can fix the row and run it again.

It uses an API key with the scopes shipments:write (create) and shipments:read (read a shipment again on a replay, and download the label). The key stays in the script's private properties: it is never in a cell. Create the key as described in Enable the API.

Create a sheet named Shipments. Row 1 holds headers; data starts at row 2. The script finds each column by its header text (case does not matter), so the order does not matter. Optional columns can be left out of the sheet.

Header Notes
Reference Your order number. Required. Becomes the shipment reference and the idempotency key
Merchant Optional. Merchant id or exact account name. When filled, the shipment is sent for that merchant and the merchant's primary saved address is the pickup
Sender name, Sender phone Required when Merchant is empty (an external one-off sender). Format the phone column as Plain text
Pickup city, Pickup district, Pickup address line, Pickup short address Required when Merchant is empty, except the short address, which is required for pickups in Saudi Arabia. On a merchant row, filling Pickup city sends this pickup address instead of the saved one. Format the short-address column as Plain text
Recipient name Required
Recipient phone Required. Format the column as Plain text so leading zeros stay
City Arabic or English name. Required
District Arabic or English name. Required
Address line Street, building, landmark. Required
Short address Saudi national short address, for example RNBA6769. Required for recipients in Saudi Arabia. Plain text
Weight kg, Length cm, Width cm, Height cm Required, numbers
COD amount Optional, defaults to 0
Description Optional
Tracking number, Status, Error code, Error message, Label Written by the script. If a header is missing, the script adds it after the last column. Label is a link to the label PDF in Google Drive: open it to download or print

The headers the script needs in every sheet are Reference, Recipient name, Recipient phone, City, District, Address line, Weight kg, Length cm, Width cm and Height cm. If one is missing, the script stops and tells you which.

  • Merchant row (Merchant filled). The shipment belongs to that merchant and the courier collects from the merchant's primary saved address. Fill Pickup city and the other pickup columns only when this parcel must be collected somewhere else.
  • External-sender row (Merchant empty). For a person or business that is not one of your merchants. The shipment is sent as a custom sender and booked on the company's shared walk-in account. It needs the sender name and phone and a full pickup address.

The script never sends a branch. The system picks the branch that covers the pickup address.

Arabic names such as جده and حي البرية work: spelling variants are tolerated (Places by name). The script sends the country as SA, for both pickup and recipient; change the COUNTRY constant at the top of the script if you ship elsewhere.

After each shipment is created, the script downloads its label, the 100x150 mm waybill as a PDF, and saves it in a Google Drive folder named LastMile labels (created on the first run) as <trackingNumber>.pdf. The link goes in the Label column. A link straight to the API would not open, because the request needs the key headers, so the script keeps the PDFs in Drive for you. The first run asks for Google Drive permission as well.

If a label could not be downloaded, the shipment is still created and the error is written in Error code and Error message with the prefix Label:. Use the LastMile, Download missing labels menu item to fetch labels for every row that has a tracking number and an empty Label. It also covers sheets you filled before the Label column existed.

Open Extensions, Apps Script, paste the script, save, and set three script properties (Project Settings): LASTMILE_API_URL, LASTMILE_API_KEY and LASTMILE_API_SECRET. Reload the sheet: a LastMile menu appears. The first run asks you to authorise the script.

Apps Script
/**
 * Create LastMile shipments from a Google Sheet.
 *
 * Setup: Extensions > Apps Script, paste this file, then Project Settings > Script properties:
 *   LASTMILE_API_URL     base address of the API, no trailing slash
 *   LASTMILE_API_KEY     lmc_live_...
 *   LASTMILE_API_SECRET  the secret shown once when the key was created
 * The key needs the scopes shipments:write (create) and shipments:read (replays and labels). The first run also asks
 * for permission to use Google Drive: label PDFs are saved there.
 *
 * Sheet "Shipments", row 1 = headers, data from row 2. Columns are found by header text (any order, any case).
 * Format the phone and short-address columns as Plain text.
 *   Required headers: Reference, Recipient name, Recipient phone, City, District, Address line,
 *                     Weight kg, Length cm, Width cm, Height cm
 *   Optional headers: Merchant, Sender name, Sender phone, Pickup city, Pickup district, Pickup address line,
 *                     Pickup short address, Short address, COD amount, Description
 *   Written by the script (added after the last column when missing): Tracking number, Status, Error code, Error message, Label
 *   Label is a link to the shipping label PDF in the Drive folder LABEL_FOLDER.
 *
 * Two kinds of rows:
 *   Merchant filled  -> sent for that merchant; its primary saved address is the pickup. Fill Pickup city (and the
 *                       other Pickup columns) only to use a different pickup address.
 *   Merchant empty   -> one-off external sender: Sender name, Sender phone, Pickup city, Pickup district and
 *                       Pickup address line are required.
 * The script never sends a branch: the system picks the branch that covers the pickup address.
 * Menu: "Create shipments" creates shipments and saves their labels; "Download missing labels" saves labels for rows
 * that have a tracking number and an empty Label cell.
 */
const SHEET_NAME = "Shipments";
const LABEL_FOLDER = "LastMile labels";
const COUNTRY = "SA";
const REQUIRED = ["Reference", "Recipient name", "Recipient phone", "City", "District", "Address line",
  "Weight kg", "Length cm", "Width cm", "Height cm"];
const OPTIONAL = ["Merchant", "Sender name", "Sender phone", "Pickup city", "Pickup district", "Pickup address line",
  "Pickup short address", "Short address", "COD amount", "Description"];
const RESULTS = ["Tracking number", "Status", "Error code", "Error message", "Label"];

function onOpen() {
  SpreadsheetApp.getUi().createMenu("LastMile").addItem("Create shipments", "createShipments")
    .addItem("Download missing labels", "downloadMissingLabels").addToUi();
}

/** Reads the settings and the header row; stops with an alert when a required header is missing. */
function openSheet() {
  const props = PropertiesService.getScriptProperties();
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME);
  if (!sheet) {
    SpreadsheetApp.getUi().alert('Create a sheet named "' + SHEET_NAME + '" first.');
    return null;
  }
  const titles =sheet.getRange(1, 1, 1, Math.max(sheet.getLastColumn(), 1)).getDisplayValues()[0].map((t) => String(t).trim().toLowerCase());
  const columnOf = (title) => titles.indexOf(title.toLowerCase()); // 0-based, -1 when absent

  const absent = REQUIRED.filter((title) => columnOf(title) < 0);
  if (absent.length) {
    SpreadsheetApp.getUi().alert("Add these headers to row 1: " + absent.join(", "));
    return null;
  }

  // Result columns: append the missing ones after the last used column.
  RESULTS.forEach((title) => {
    if (columnOf(title) < 0) {
      titles.push(title.toLowerCase());
      if (titles.length > sheet.getMaxColumns()) sheet.insertColumnAfter(sheet.getMaxColumns());
      sheet.getRange(1, titles.length).setValue(title);
    }
  });

  let folder = null; // looked up once per run, created when absent
  return {
    sheet, columnOf, titles,
    api: props.getProperty("LASTMILE_API_URL") + "/api/public/v1",
    headers: {
      "X-API-Key": props.getProperty("LASTMILE_API_KEY"),
      "X-API-Secret": props.getProperty("LASTMILE_API_SECRET"),
      "Accept-Language": "en",
    },
    labelFolder: () => {
      if (!folder) {
        const found = DriveApp.getFoldersByName(LABEL_FOLDER);
        folder = found.hasNext() ? found.next() : DriveApp.createFolder(LABEL_FOLDER);
      }
      return folder;
    },
  };
}

function createShipments() {
  const ctx = openSheet();
  if (!ctx) return;
  const { sheet, columnOf, titles, api, headers } = ctx;

  const lastRow = sheet.getLastRow();
  if (lastRow < 2) return;

  // getDisplayValues keeps phone numbers and short addresses exactly as typed (no lost leading zero).
  const rows = sheet.getRange(2, 1, lastRow - 1, titles.length).getDisplayValues();

  rows.forEach((row, index) => {
    const get = (title) => {
      const column = columnOf(title);
      return column < 0 ? "" : String(row[column]).trim();
    };
    if (!get("Reference") || get("Tracking number")) return;

    const merchant = get("Merchant");
    const external = !merchant;
    const needed = REQUIRED.slice(1).concat(external ? ["Sender name", "Sender phone", "Pickup city", "Pickup district", "Pickup address line"] : []);
    const missing = needed.filter((title) => !get(title));
    if (missing.length) {
      writeResult(ctx, index + 2, { code: "missing_fields", message: "Fill in: " + missing.join(", ") });
      return;
    }

    const body = {
      reference: get("Reference"),
      sender: external
        ? { type: "custom", name: get("Sender name"), phone: get("Sender phone") }
        : { type: "merchant", merchant: merchant },
      recipient: {
        country: COUNTRY,
        city: get("City"),
        district: get("District"),
        addressLine: get("Address line"),
        shortAddress: get("Short address") || undefined,
        name: get("Recipient name"),
        phone: get("Recipient phone"),
      },
      parcel: {
        weightKg: Number(get("Weight kg")),
        lengthCm: Number(get("Length cm")),
        widthCm: Number(get("Width cm")),
        heightCm: Number(get("Height cm")),
        description: get("Description") || undefined,
      },
      payment: { codAmount: Number(get("COD amount") || 0) },
    };
    // External senders always need a pickup; a merchant row sends one only to override the saved address.
    if (external || get("Pickup city")) {
      body.pickup = {
        country: COUNTRY,
        city: get("Pickup city"),
        district: get("Pickup district"),
        addressLine: get("Pickup address line"),
        shortAddress: get("Pickup short address") || undefined,
      };
    }

    // One key per row, derived from the reference: running the script twice never creates a second shipment.
    const idempotencyKey = ("sheet-" + body.reference).replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 128);
    const response = send("post", api + "/shipments", headers, body, idempotencyKey);
    const data = parseJson(response);

    if (response.getResponseCode() === 201 || response.getResponseCode() === 200) {
      // The shipment is saved first: a label problem never hides a created shipment.
      writeResult(ctx, index + 2, { tracking: data.trackingNumber, status: data.statusLabelEn });
      saveLabel(ctx, index + 2, data.trackingNumber);
    } else {
      writeResult(ctx, index + 2, { code: data.code || "http_" + response.getResponseCode(), message: describeError(data) });
    }
  });
}

/** Request with one automatic wait when the rate limit (120 requests per minute) is hit. */
function send(method, url, headers, body, idempotencyKey) {
  const options = { method: method, headers: Object.assign({}, headers), muteHttpExceptions: true };
  if (body) {
    options.contentType = "application/json";
    options.payload = JSON.stringify(body);
    options.headers["Idempotency-Key"] = idempotencyKey;
  }
  let response = UrlFetchApp.fetch(url, options);
  if (response.getResponseCode() === 429) {
    const wait = Number(response.getHeaders()["Retry-After"] || 30);
    Utilities.sleep(Math.min(wait, 60) * 1000);
    response = UrlFetchApp.fetch(url, options);
  }
  return response;
}

/** Saves the label PDF in Drive (reusing a file of the same name) and writes its link to the Label cell. */
function saveLabel(ctx, rowNumber, trackingNumber) {
  const folder = ctx.labelFolder();
  const name = trackingNumber + ".pdf";
  const existing = folder.getFilesByName(name);
  if (existing.hasNext()) {
    writeResult(ctx, rowNumber, { label: existing.next().getUrl() });
    return;
  }
  const response = send("get", ctx.api + "/shipments/" + encodeURIComponent(trackingNumber) + "/label", ctx.headers);
  if (response.getResponseCode() !== 200) {
    const data = parseJson(response);
    writeResult(ctx, rowNumber, { code: data.code || "http_" + response.getResponseCode(), message: "Label: " + describeError(data) });
    return;
  }
  const file = folder.createFile(response.getBlob().setName(name));
  writeResult(ctx, rowNumber, { label: file.getUrl() });
}

/** Saves the label for every row that has a tracking number but no Label yet. */
function downloadMissingLabels() {
  const ctx = openSheet();
  if (!ctx) return;
  const { sheet, columnOf, titles } = ctx;
  const lastRow = sheet.getLastRow();
  if (lastRow < 2) return;
  const rows = sheet.getRange(2, 1, lastRow - 1, titles.length).getDisplayValues();
  rows.forEach((row, index) => {
    const tracking = String(row[columnOf("Tracking number")]).trim();
    if (tracking && !String(row[columnOf("Label")]).trim()) saveLabel(ctx, index + 2, tracking);
  });
}

/** The JSON body, or an empty object when the answer is not JSON (a proxy error page, for example). */
function parseJson(response) {
  try {
    return JSON.parse(response.getContentText() || "{}") || {};
  } catch (e) {
    return {};
  }
}

/** A readable message: the API text, the failing fields, or "did you mean" suggestions for places. */
function describeError(data) {
  const parts = [data.message || "Request failed"];
  const details = data.details || {};
  if (details.errors) {
    Object.keys(details.errors).forEach((field) => parts.push(field + ": " + details.errors[field].join(" ")));
  }
  if (details.candidates && details.candidates.length) {
    parts.push("Did you mean: " + details.candidates.map((c) => c.nameAr + " / " + c.nameEn).join(", ") + "?");
  }
  return parts.join(" | ");
}

/** Writes only the result cells that are given, found by header text. A tracking number or label clears old errors. */
function writeResult(ctx, rowNumber, result) {
  const cells = { "Tracking number": result.tracking, "Status": result.status, "Error code": result.code,
    "Error message": result.message, "Label": result.label };
  if (result.code === undefined && (result.tracking !== undefined || result.label !== undefined)) {
    cells["Error code"] = "";
    cells["Error message"] = "";
  }
  Object.keys(cells).forEach((title) => {
    if (cells[title] !== undefined) ctx.sheet.getRange(rowNumber, ctx.columnOf(title) + 1).setValue(cells[title]);
  });
  SpreadsheetApp.flush();
}
  • One idempotency key per row, built from the reference (sheet-ORD-1001). If the script stops half way, or you run it again, rows that were already created are not duplicated: the API replays the first answer. A row that failed can be corrected and sent again with the same key, because failed attempts are not remembered.
  • If you change a row after it succeeded and clear its tracking number to resend it, the API answers 409 idempotency_key_reused because the body changed. Use a new reference for a new shipment.
  • Errors are written back as a code and a message. Validation errors list the failing fields (recipient.phone: ...). A place that does not match lists the closest candidates ("Did you mean: جدة / Jeddah?"), so you can correct the cell.
  • Rate limit. The API allows 120 requests per minute per key. On 429 the script waits for Retry-After and tries once more. For thousands of rows, run it in batches.
  • Apps Script time limit. A script run stops after a few minutes. The script skips rows that already have a tracking number, so just run it again.
  • Refresh the Status column: loop over rows that have a tracking number and call GET /shipments/{trackingNumber} from a daily trigger, or receive webhooks in a deployed web app.
  • Add a Quote column that calls POST /pricing/quote before you create, to review prices first.