API/Usare l'API da Google Sheets

Usare l'API da Google Sheets

Importa una riga per libro — royalty, spesa pubblicitaria, profitto netto — in un foglio Google Sheets con un breve Apps Script, senza mai mettere la chiave API nel foglio.

Questo script compila una scheda chiamata Books con una riga per libro degli ultimi 30 giorni: titolo, ASIN, formato, marketplace, unità, royalty, spesa pubblicitaria, profitto netto e TACOS.

1. Crea una chiave

Impostazioni → API → Crea una chiave. Chiamala «Google Sheets» e copiala. Come funzionano le chiavi: Autenticazione e chiavi API.

2. Salva la chiave nelle proprietà dello script

  1. Nel tuo foglio Google Sheets, apri Estensioni → Apps Script.
  2. Fai clic su Impostazioni progetto (l'ingranaggio), poi su Aggiungi proprietà script.
  3. Proprietà: TRUEROYALTIES_API_KEY. Valore: la tua chiave. Salva.

Non incollare mai la chiave in una cella: chiunque abbia accesso al foglio potrebbe leggerla. E mai nell'URL: l'API rifiuta la richiesta.

3. Incolla lo script

Nell'Editor, sostituisci il contenuto di Code.gs con:

const API_URL = "https://author.trueroyalties.com/api/v1/reports/books";

function importBooks() {
  const key = PropertiesService.getScriptProperties().getProperty(
    "TRUEROYALTIES_API_KEY",
  );
  if (!key) {
    throw new Error("Add TRUEROYALTIES_API_KEY in Project Settings.");
  }

  const rows = [];
  let cursor = null;
  let currency = "";

  while (true) {
    let url = API_URL + "?range=last_30_days&limit=100";
    if (cursor) url += "&cursor=" + encodeURIComponent(cursor);

    const response = UrlFetchApp.fetch(url, {
      headers: { Authorization: "Bearer " + key },
      muteHttpExceptions: true,
    });
    const status = response.getResponseCode();

    // Limit reached: wait as long as the API asks, then retry the same page.
    if (status === 429) {
      const headers = response.getHeaders();
      const wait = Number(headers["Retry-After"] || headers["retry-after"] || 1);
      Utilities.sleep(wait * 1000);
      continue;
    }

    const body = JSON.parse(response.getContentText());
    if (status !== 200) {
      throw new Error(body.code + ": " + body.detail + " (" + body.request_id + ")");
    }

    currency = body.currency;
    for (const line of body.data) {
      rows.push([
        line.book.title,
        line.book.asin,
        line.book.format,
        line.book.marketplace,
        line.units,
        line.revenue,
        line.ad_spend,
        line.net_profit,
        line.tacos === null ? "" : line.tacos,
      ]);
    }

    if (!body.has_more) break;
    cursor = body.next_cursor;
  }

  const spreadsheet = SpreadsheetApp.getActive();
  const sheet =
    spreadsheet.getSheetByName("Books") || spreadsheet.insertSheet("Books");
  sheet.clearContents();
  sheet.getRange(1, 1, 1, 9).setValues([[
    "Title", "ASIN", "Format", "Marketplace", "Units",
    "Royalties (" + currency + ")", "Ad spend", "Net profit", "TACOS",
  ]]);
  if (rows.length > 0) {
    sheet.getRange(2, 1, rows.length, 9).setValues(rows);
  }
}

4. Eseguilo

  1. Scegli importBooks nella barra degli strumenti e fai clic su Esegui.
  2. La prima volta Google ti chiede di autorizzare lo script a contattare un servizio esterno e a modificare il tuo foglio. Accetta.
  3. Torna al foglio: la scheda Books è compilata.

Per aggiornarlo da solo, apri Attivatori (l'orologio), Aggiungi attivatore, scegli importBooks e un attivatore basato sul tempo, una volta al giorno.

Cambiare cosa importi

Modifica la query nella riga url:

VuoiAggiungi o cambia
Un altro periodorange=last_month, oppure start_date=2026-01-01&end_date=2026-06-30
Tutte le vendite dall'iniziorange=all_time
Un'altra valuta&currency=EUR
Un altro ordine&sort=revenue (anche ad_spend, units, title; net_profit di default)

Buono a sapersi:

  • I libri senza attività nel periodo compaiono comunque, con degli zeri, come nella pagina Libri.
  • Ogni pagina da 100 libri è una richiesta. Lo script aspetta da solo quando raggiunge il limite di 60 richieste al minuto: un catalogo grande richiede solo un po' più di tempo.
  • Lo script non controlla meta.truncated. Se è true, alcune righe non sono state lette: importa un periodo più breve.