Sync a register from a spreadsheet

Send the rows of a spreadsheet into a list register with a short script, and run it again without adding a row twice.

Guide
About 15 minutes

What you'll do

Export a spreadsheet as CSV and send its rows into a list register in batches of 50. Running the script again with the same file adds nothing.

Before you start

  • A list register whose column names match the spreadsheet's headings. A heading with no matching column is refused.
  • An API key with registers:rows:add. See Create and manage API keys.
  • Python 3 on the computer that runs the script.

Steps

  1. Open the register in Alchex and check its column names match your spreadsheet's headings exactly.
  2. In your spreadsheet app, save the sheet as CSV, with the headings in the first row.
  3. Save this script as sync.py next to the CSV file.
python
import csv, hashlib, json, os, sys, time, urllib.error, urllib.request
KEY = os.environ["ALCHEX_API_KEY"]URL = "https://app.alchex.com/api/v1/tools/write_record/add"
def send(register, rows):    body = json.dumps({"register": register, "rows": rows}).encode()    # The same batch always gets the same key, so a rerun adds nothing.    key = hashlib.sha256(body).hexdigest()[:64]    request = urllib.request.Request(URL, data=body, method="POST", headers={        "Authorization": f"Bearer {KEY}",        "Content-Type": "application/json",        "Idempotency-Key": key,    })    while True:        try:            with urllib.request.urlopen(request) as answer:                print(answer.status, json.load(answer).get("rowIds"))                return        except urllib.error.HTTPError as error:            if error.code == 429:                time.sleep(int(error.headers.get("Retry-After", "5")))                continue            sys.exit(f"{error.code} {error.read().decode()}")
path, register = sys.argv[1], sys.argv[2]with open(path, newline="", encoding="utf-8") as f:    rows = [{"cells": {k: v for k, v in r.items() if v != ""}} for r in csv.DictReader(f)]for start in range(0, len(rows), 50):    send(register, rows[start:start + 50])
  1. In a terminal, run the script with your key, the file and the register's name.
bash
ALCHEX_API_KEY=EXAMPLE_API_KEY python3 sync.py suppliers.csv "Suppliers"
  1. Open the register in Alchex and check the new rows.

What happens next

Each batch answers 201 with the new rowIds. A batch already sent answers 200, and nothing is added. The rows count at once, under the key's name.

The script adds rows; it does not change rows already there. A row you edited in the spreadsheet is a new batch, so it is added again. To update rows instead, read them with read_document/rows and send write_record/change; see Rows.

If something goes wrong

400 unknown_field. A heading is not a column of the register, and the message lists the columns. Rename the heading to match.

404 register_not_found. Check the register's name, or use its code.

403 missing_permission. The key lacks registers:rows:add. Create a key with it.

413 body_too_large. A batch is over 200 KB. Change 50 to a smaller number in both places.