> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usequotable.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Export to a spreadsheet

> Page through every brand, prompt, citation, article and demand term a key can read and write them to CSV files for Excel, Google Sheets or your warehouse.

This recipe exports everything a key can read into one CSV file per resource. It follows every `next_cursor`, paces itself with the rate-limit headers, and skips resources the key has no scope for, so you can run it with any key.

## What you need

| Requirement | Value |
| - | - |
| Scopes | `read:projects`, `read:visibility`, `read:content` and `read:demand`. New keys include them all; with an older key, files it has no scope for are skipped. |
| Endpoints | `/projects`, `/prompts`, `/citations`, `/articles`, `/demand/terms` |
| Environment | `QUOTABLE_API_KEY` |
| Requests per run | About 1 per 100 rows, per brand |

## Output files

| File | One row per | Needs |
| - | - | - |
| `brands.csv` | Brand | `read:projects` |
| `prompts.csv` | Tracked prompt | `read:visibility` |
| `citations.csv` | Cited URL | `read:visibility` |
| `articles.csv` | Article (metadata only, no HTML) | `read:content` |
| `demand_terms.csv` | Demand term with its latest monthly AI volume | `read:demand` and a plan with Prompt Volumes |
| `demand_months.csv` | Term and month, up to 12 months per term | `read:demand` and a plan with Prompt Volumes |

Every file except `brands.csv` starts with a `project_id` column, so you can join them.

## Code

```javascript export-quotable.mjs theme={"system"}
// Node.js 20+. Run: node export-quotable.mjs [output-directory]
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";

const API = "https://app.usequotable.com/api/v1";
const KEY = process.env.QUOTABLE_API_KEY;
const OUT = process.argv[2] ?? "quotable-export";

const sleep = (s) => new Promise((r) => setTimeout(r, s * 1000));

class SkipResource extends Error {}

async function get(path) {
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(`${API}${path}`, { headers: { Authorization: `Bearer ${KEY}` } });
    if (res.status === 429 && attempt < 5) {
      await sleep(Number(res.headers.get("retry-after") ?? "1"));
      continue;
    }
    // Missing scope (403) or not available on this plan (404): skip, don't fail.
    if (res.status === 403 || res.status === 404) throw new SkipResource((await res.json()).title);
    if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
    // Pace bulk work: wait out the window instead of hitting a 429.
    if (res.headers.get("x-ratelimit-remaining") === "0") {
      await sleep(Number(res.headers.get("x-ratelimit-reset") ?? "1"));
    }
    return res.json();
  }
}

async function all(path) {
  const rows = [];
  let cursor = null;
  do {
    const sep = path.includes("?") ? "&" : "?";
    const page = await get(`${path}${sep}limit=100${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
    rows.push(...page.data);
    cursor = page.next_cursor;
  } while (cursor);
  return rows;
}

// RFC 4180 quoting, plus a guard against spreadsheet formula injection.
function cell(value) {
  if (value === null || value === undefined) return "";
  let text = Array.isArray(value) ? value.join("|") : String(value);
  if (typeof value === "string" && /^[=+\-@\t\r]/.test(text)) text = `'${text}`;
  return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
}

async function writeCsv(name, columns, rows) {
  const lines = [columns.join(","), ...rows.map((row) => columns.map((c) => cell(row[c])).join(","))];
  await writeFile(join(OUT, name), lines.join("\r\n") + "\r\n");
  console.log(`${name.padEnd(18)} ${String(rows.length).padStart(6)} rows`);
}

await mkdir(OUT, { recursive: true });

const brands = await all("/projects");
await writeCsv(
  "brands.csv",
  ["id", "name", "domain", "brand_name", "location_code", "language", "engines", "paused", "created_at"],
  brands.map((b) => ({ ...b, location_code: b.market.location_code, language: b.market.language })),
);

const files = {
  "prompts.csv": {
    path: (id) => `/projects/${id}/prompts`,
    columns: ["project_id", "id", "text", "topic", "active", "location_code", "language", "demand_score", "created_at"],
    map: (r) => ({ ...r, location_code: r.market.location_code, language: r.market.language }),
  },
  "citations.csv": {
    path: (id) => `/projects/${id}/citations`,
    columns: ["project_id", "id", "url", "domain", "times_cited", "times_retrieved", "first_seen", "last_seen"],
  },
  "articles.csv": {
    path: (id) => `/projects/${id}/articles`,
    columns: ["project_id", "id", "title", "status", "format", "target_prompt", "target_prompt_id",
      "published_url", "published_at", "scheduled_for", "created_at", "updated_at"],
  },
  "demand_terms.csv": {
    path: (id) => `/projects/${id}/demand/terms`,
    columns: ["project_id", "id", "term", "normalized", "location_code", "language", "status", "ai_volume", "period", "fetched_at"],
    map: (r) => ({ ...r, location_code: r.market.location_code, language: r.market.language }),
  },
};

const collected = Object.fromEntries(Object.keys(files).map((name) => [name, []]));
for (const brand of brands) {
  for (const [name, spec] of Object.entries(files)) {
    try {
      const rows = await all(spec.path(brand.id));
      collected[name].push(...rows.map((r) => ({ project_id: brand.id, ...(spec.map ? spec.map(r) : r) })));
    } catch (error) {
      if (!(error instanceof SkipResource)) throw error;
      if (!collected[name].skipped) console.log(`${name.padEnd(18)} skipped (${error.message})`);
      collected[name].skipped = true;
    }
  }
}

for (const [name, spec] of Object.entries(files)) {
  if (!collected[name].skipped || collected[name].length > 0) await writeCsv(name, spec.columns, collected[name]);
}

const months = collected["demand_terms.csv"].flatMap((t) =>
  t.months.map((m) => ({ project_id: t.project_id, term_id: t.id, term: t.term, ...m })),
);
if (months.length > 0) {
  await writeCsv("demand_months.csv", ["project_id", "term_id", "term", "month", "ai_volume", "observed_at"], months);
}

console.log(`\nWrote ${OUT}/`);
```

```python export_quotable.py theme={"system"}
# Python 3.10+, pip install requests. Run: python export_quotable.py [output-directory]
import csv
import os
import sys
import time

import requests

API = "https://app.usequotable.com/api/v1"
OUT = sys.argv[1] if len(sys.argv) > 1 else "quotable-export"

session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['QUOTABLE_API_KEY']}"

class SkipResource(Exception):
    pass

def get(path, params=None):
    for attempt in range(6):
        res = session.get(f"{API}{path}", params=params, timeout=60)
        if res.status_code == 429 and attempt < 5:
            time.sleep(int(res.headers.get("Retry-After", "1")))
            continue
        # Missing scope (403) or not available on this plan (404): skip, don't fail.
        if res.status_code in (403, 404):
            raise SkipResource(res.json().get("title"))
        res.raise_for_status()
        # Pace bulk work: wait out the window instead of hitting a 429.
        if res.headers.get("X-RateLimit-Remaining") == "0":
            time.sleep(int(res.headers.get("X-RateLimit-Reset", "1")))
        return res.json()

def all_rows(path):
    rows, cursor = [], None
    while True:
        page = get(path, {"limit": 100, **({"cursor": cursor} if cursor else {})})
        rows.extend(page["data"])
        cursor = page["next_cursor"]
        if not cursor:
            return rows

def cell(value):
    if value is None:
        return ""
    if isinstance(value, bool):
        return "true" if value else "false"
    if isinstance(value, list):
        return "|".join(map(str, value))
    if isinstance(value, str) and value[:1] in ("=", "+", "-", "@", "\t", "\r"):
        return "'" + value  # guard against spreadsheet formula injection
    return value

def write_csv(name, columns, rows):
    with open(os.path.join(OUT, name), "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(columns)
        for row in rows:
            writer.writerow([cell(row.get(c)) for c in columns])
    print(f"{name:<18} {len(rows):>6} rows")

def flat_market(row):
    return {**row, "location_code": row["market"]["location_code"], "language": row["market"]["language"]}

os.makedirs(OUT, exist_ok=True)

brands = all_rows("/projects")
write_csv("brands.csv",
          ["id", "name", "domain", "brand_name", "location_code", "language", "engines", "paused", "created_at"],
          [flat_market(b) for b in brands])

files = {
    "prompts.csv": ("prompts", ["project_id", "id", "text", "topic", "active", "location_code", "language",
                                "demand_score", "created_at"], flat_market),
    "citations.csv": ("citations", ["project_id", "id", "url", "domain", "times_cited", "times_retrieved",
                                    "first_seen", "last_seen"], None),
    "articles.csv": ("articles", ["project_id", "id", "title", "status", "format", "target_prompt",
                                  "target_prompt_id", "published_url", "published_at", "scheduled_for",
                                  "created_at", "updated_at"], None),
    "demand_terms.csv": ("demand/terms", ["project_id", "id", "term", "normalized", "location_code", "language",
                                          "status", "ai_volume", "period", "fetched_at"], flat_market),
}

collected = {name: [] for name in files}
skipped = set()
for brand in brands:
    for name, (path, _columns, mapper) in files.items():
        try:
            rows = all_rows(f"/projects/{brand['id']}/{path}")
        except SkipResource as reason:
            if name not in skipped:
                print(f"{name:<18} skipped ({reason})")
            skipped.add(name)
            continue
        collected[name].extend({"project_id": brand["id"], **(mapper(r) if mapper else r)} for r in rows)

for name, (_path, columns, _mapper) in files.items():
    if name not in skipped or collected[name]:
        write_csv(name, columns, collected[name])

months = [
    {"project_id": t["project_id"], "term_id": t["id"], "term": t["term"], **m}
    for t in collected["demand_terms.csv"]
    for m in t["months"]
]
if months:
    write_csv("demand_months.csv", ["project_id", "term_id", "term", "month", "ai_volume", "observed_at"], months)

print(f"\nWrote {OUT}/")
```

## Expected output

With a new key, on a workspace with two brands:

```text theme={"system"}
brands.csv              2 rows
prompts.csv            79 rows
citations.csv         354 rows
articles.csv           23 rows
demand_terms.csv       42 rows
demand_months.csv     504 rows

Wrote quotable-export/
```

With an older key that lacks `read:content`, the articles line reads `articles.csv skipped (Insufficient scope)` instead, and the rest of the export still runs.

## Tips

* **Open in Google Sheets or Excel.** Files are UTF-8 with a header row. In Excel, use **Data → From Text/CSV** so non-English prompts keep their characters.
* **Load into a warehouse.** The columns map one-to-one to API fields, so the API reference doubles as your schema documentation.
* **Visibility history** isn't a list endpoint, so it's not in this export. Add it per brand with `GET /projects/{project_id}/visibility` (up to 366 days per request), as in [Visibility over time](https://docs.usequotable.com/guides/weekly-visibility-trend.md).
* **Articles** are the ones stored for each brand by the articles endpoints. Documents Quotable Agent writes are kept in the [Library](https://docs.usequotable.com/actions/library.md) and aren't part of this export.
* **Article HTML** is left out on purpose: list responses don't include it. Fetch `GET /projects/{project_id}/articles/{article_id}` for the articles whose content you need.
* **Formula guard.** Text cells that start with `=`, `+`, `-` or `@` get a leading `'` so spreadsheets don't run them as formulas. Remove that guard if you load the files into a database instead.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.