# Examples

> Copy and run recipes: ask an engine from a country and read citations, track a brand across engines, compare countries, use webhooks and export CSV.

Complete recipes for the jobs people build with PromptGale. Each one runs as it is once `PROMPTGALE_API_KEY` holds your API key. The fields are the ones in [Request fields](https://promptgale.com/docs/payload.md) and [Results](https://promptgale.com/docs/results.md); every task costs its engine's price in [credits](https://promptgale.com/docs/plans-and-credits.md), and a failed task is refunded.

## Ask ChatGPT from a country and read the citations

`POST /v1/sync/task` waits for the answer. `result.sources` lists every source the engine showed; `cited` is true for the ones the answer cites, with `citationNumber` when it numbers them.

**curl** (with `jq` to print the cited sources)

```bash
curl -s -X POST https://promptgale.com/v1/sync/task \
  -H "Authorization: Bearer $PROMPTGALE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"taskType":"CHATGPT","payload":{"prompt":"best running shoes for flat feet","country":"GB"}}' \
  | jq '.data.result.sources[] | select(.cited) | {position, domain, url}'
```

**Python**

```python
import os
import requests

res = requests.post(
    "https://promptgale.com/v1/sync/task",
    headers={"Authorization": f"Bearer {os.environ['PROMPTGALE_API_KEY']}"},
    json={"taskType": "CHATGPT", "payload": {"prompt": "best running shoes for flat feet", "country": "GB"}},
    timeout=300,
)
task = res.json()["data"]
if task["status"] == "COMPLETED":
    print(task["result"]["text"][:300])
    for source in task["result"]["sources"]:
        if source["cited"]:
            print(source["position"], source["domain"], source["url"])
else:
    # FAILED (refunded), or still running after the wait (HTTP 202): read GET /v1/tasks/{id} later.
    print(task["id"], task["status"], task.get("error"))
```

**Node.js**

```js
const res = await fetch('https://promptgale.com/v1/sync/task', {
  method: 'POST',
  headers: { Authorization: `Bearer ${process.env.PROMPTGALE_API_KEY}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ taskType: 'CHATGPT', payload: { prompt: 'best running shoes for flat feet', country: 'GB' } }),
});
const { data: task } = await res.json();
if (task.status === 'COMPLETED') {
  console.log(task.result.text.slice(0, 300));
  for (const s of task.result.sources.filter((s) => s.cited)) console.log(s.position, s.domain, s.url);
} else {
  console.log(task.id, task.status, task.error);
}
```

## Track a brand across every engine with a batch

One batch item per prompt and engine. Each item names your brand, its domains and your competitors, so every result carries `analysis.brands`: whether the brand is mentioned, its rank among the brands named, whether a source is on its domains, and its share of voice. Batches need a paid plan (Starter allows up to 100 items per batch).

**curl** (create the batch)

```bash
curl -s -X POST https://promptgale.com/v1/batches \
  -H "Authorization: Bearer $PROMPTGALE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "idempotencyKey": "acme-2026-11-27",
    "items": [
      { "customId": "p1:CHATGPT", "taskType": "CHATGPT", "payload": { "prompt": "best crm for a small agency", "country": "US", "brand": "Acme", "competitors": ["Globex", "Initech"] } },
      { "customId": "p1:GEMINI", "taskType": "GEMINI", "payload": { "prompt": "best crm for a small agency", "country": "US", "brand": "Acme", "competitors": ["Globex", "Initech"] } },
      { "customId": "p1:PERPLEXITY", "taskType": "PERPLEXITY", "payload": { "prompt": "best crm for a small agency", "country": "US", "brand": "Acme", "competitors": ["Globex", "Initech"] } },
      { "customId": "p1:BING_COPILOT_SEARCH", "taskType": "BING_COPILOT_SEARCH", "payload": { "prompt": "best crm for a small agency", "country": "US", "brand": "Acme", "competitors": ["Globex", "Initech"] } },
      { "customId": "p1:META_AI", "taskType": "META_AI", "payload": { "prompt": "best crm for a small agency", "country": "US", "brand": "Acme", "competitors": ["Globex", "Initech"] } },
      { "customId": "p1:GOOGLE_AIO", "taskType": "GOOGLE_AIO", "payload": { "prompt": "best crm for a small agency", "country": "US", "brand": "Acme", "competitors": ["Globex", "Initech"] } },
      { "customId": "p1:GOOGLE_AIMODE", "taskType": "GOOGLE_AIMODE", "payload": { "prompt": "best crm for a small agency", "country": "US", "brand": "Acme", "competitors": ["Globex", "Initech"] } }
    ]
  }'
```

**Python** (create, wait, read every item)

```python
import os
import time
import requests

API = "https://promptgale.com"
HEADERS = {"Authorization": f"Bearer {os.environ['PROMPTGALE_API_KEY']}"}
ENGINES = ["CHATGPT", "GEMINI", "PERPLEXITY", "BING_COPILOT_SEARCH", "META_AI", "GOOGLE_AIO", "GOOGLE_AIMODE"]
PROMPTS = ["best crm for a small agency", "crm with the best email automation"]

items = [
    {
        "customId": f"{i}:{engine}",
        "taskType": engine,
        "payload": {"prompt": prompt, "country": "US", "brand": "Acme", "brandDomains": ["acme.com"], "competitors": ["Globex", "Initech"]},
    }
    for i, prompt in enumerate(PROMPTS)
    for engine in ENGINES
]
batch = requests.post(f"{API}/v1/batches", headers=HEADERS, json={"items": items, "idempotencyKey": "acme-2026-11-27"}).json()["data"]

while batch["status"] != "COMPLETED":
    time.sleep(15)
    batch = requests.get(f"{API}/v1/batches/{batch['id']}", headers=HEADERS).json()["data"]

cursor = None
while True:
    params = {"include": "result", "limit": 100, **({"cursor": cursor} if cursor else {})}
    page = requests.get(f"{API}/v1/batches/{batch['id']}/items", headers=HEADERS, params=params).json()["data"]
    for item in page["items"]:
        result = (item.get("task") or {}).get("result")
        if not result or "analysis" not in result:
            print(item["customId"], item["status"])
            continue
        acme = next(b for b in result["analysis"]["brands"] if b["role"] == "target")
        print(item["customId"], acme["mentioned"], acme.get("rank"), acme["cited"], acme.get("shareOfVoice"))
    if not page["hasMore"]:
        break
    cursor = page["nextCursor"]
```

Instead of polling, pass `webhookUrl` with the batch: it receives `batch.completed` once every item has finished.

## Compare the same prompt across countries

`POST /v1/tasks/bulk` queues up to 500 tasks at once (all or none). Here the same prompt goes to one engine from four countries, then the script compares the domains each answer cites. `GET /v1/countries?taskType=CHATGPT` lists the countries that engine is served from.

**Python**

```python
import os
import time
import requests

API = "https://promptgale.com"
HEADERS = {"Authorization": f"Bearer {os.environ['PROMPTGALE_API_KEY']}"}
COUNTRIES = ["US", "GB", "DE", "MX"]

tasks = [{"taskType": "CHATGPT", "payload": {"prompt": "best project management software", "country": c}} for c in COUNTRIES]
created = requests.post(f"{API}/v1/tasks/bulk", headers=HEADERS, json={"tasks": tasks}).json()["data"]["tasks"]

for task in created:
    while task["status"] not in ("COMPLETED", "FAILED"):
        time.sleep(3)
        task = requests.get(f"{API}/v1/tasks/{task['id']}", headers=HEADERS).json()["data"]
    if task["status"] == "COMPLETED":
        cited = sorted({s["domain"] for s in task["result"]["sources"] if s["cited"]})
        print(task["country"], ", ".join(cited))
    else:
        print(task["country"], task["error"]["code"])
```

**Node.js**

```js
const API = 'https://promptgale.com';
const headers = { Authorization: `Bearer ${process.env.PROMPTGALE_API_KEY}`, 'Content-Type': 'application/json' };
const countries = ['US', 'GB', 'DE', 'MX'];

const res = await fetch(`${API}/v1/tasks/bulk`, {
  method: 'POST',
  headers,
  body: JSON.stringify({ tasks: countries.map((country) => ({ taskType: 'CHATGPT', payload: { prompt: 'best project management software', country } })) }),
});
const { data } = await res.json();

for (let task of data.tasks) {
  while (task.status !== 'COMPLETED' && task.status !== 'FAILED') {
    await new Promise((r) => setTimeout(r, 3000));
    task = (await (await fetch(`${API}/v1/tasks/${task.id}`, { headers })).json()).data;
  }
  const cited = task.result ? [...new Set(task.result.sources.filter((s) => s.cited).map((s) => s.domain))] : [task.error.code];
  console.log(task.country, cited.join(', '));
}
```

## Get the Google AI Overview for a query

`GOOGLE_AIO` searches Google from the country (and, if you want, the city) you choose and returns the AI Overview: its text and its sources. `aiOverviewPresent` is `false` when Google showed no overview for that query and place; that task still completes and is charged.

**curl**

```bash
curl -s -X POST https://promptgale.com/v1/sync/task \
  -H "Authorization: Bearer $PROMPTGALE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"taskType":"GOOGLE_AIO","payload":{"prompt":"how to clean white sneakers","country":"US","city":"Chicago, Illinois"}}' \
  | jq '{present: .data.result.aiOverviewPresent, text: .data.result.text, sources: [.data.result.sources[].url]}'
```

**Python**

```python
import os
import requests

res = requests.post(
    "https://promptgale.com/v1/sync/task",
    headers={"Authorization": f"Bearer {os.environ['PROMPTGALE_API_KEY']}"},
    json={"taskType": "GOOGLE_AIO", "payload": {"prompt": "how to clean white sneakers", "country": "US"}},
    timeout=300,
)
task = res.json()["data"]
result = task["result"]
if task["status"] != "COMPLETED":
    print(task["id"], task["status"], task.get("error"))
elif result["aiOverviewPresent"]:
    print(result["text"])
    for source in result["sources"]:
        print(source["position"], source["url"])
else:
    print("No AI Overview for this query and place.")
```

**Node.js**

```js
const res = await fetch('https://promptgale.com/v1/sync/task', {
  method: 'POST',
  headers: { Authorization: `Bearer ${process.env.PROMPTGALE_API_KEY}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ taskType: 'GOOGLE_AIO', payload: { prompt: 'how to clean white sneakers', country: 'US' } }),
});
const { data: task } = await res.json();
if (task.status !== 'COMPLETED') console.log(task.id, task.status, task.error);
else console.log(task.result.aiOverviewPresent ? task.result.text : 'No AI Overview for this query and place.');
```

## Receive results by webhook and verify the signature

Pass `webhookUrl` and PromptGale POSTs the finished task to it, signed with the signing secret shown when you created the API key.

**curl** (queue a task with a webhook)

```bash
curl -s -X POST https://promptgale.com/v1/tasks \
  -H "Authorization: Bearer $PROMPTGALE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"taskType":"CHATGPT","payload":{"prompt":"best crm for a small agency","country":"US"},"webhookUrl":"https://example.com/hooks/promptgale"}'
```

**Node.js** (the receiver, with Express)

```js
import crypto from 'node:crypto';
import express from 'express';

const app = express();
const SECRET = process.env.PROMPTGALE_SIGNING_SECRET;

app.post('/hooks/promptgale', express.raw({ type: 'application/json' }), (req, res) => {
  const raw = req.body.toString('utf8');
  const timestamp = req.header('promptgale-webhook-timestamp');
  const given = (req.header('promptgale-webhook-signature') ?? '').replace(/^v1,/, '');
  const event = JSON.parse(raw);
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return res.sendStatus(400);
  const expected = crypto.createHmac('sha256', SECRET).update(`${event.data.id}.${timestamp}.${raw}`).digest('base64');
  if (given.length !== expected.length || !crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected))) return res.sendStatus(401);
  console.log(event.event, event.data.id, event.data.status);
  res.sendStatus(200);
});

app.listen(3000);
```

**Python** (the receiver, with Flask)

```python
import base64
import hashlib
import hmac
import json
import os
import time

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["PROMPTGALE_SIGNING_SECRET"].encode()

@app.post("/hooks/promptgale")
def promptgale_webhook():
    raw = request.get_data()
    timestamp = request.headers.get("promptgale-webhook-timestamp", "")
    given = request.headers.get("promptgale-webhook-signature", "").removeprefix("v1,")
    event = json.loads(raw)
    if abs(time.time() - int(timestamp or 0)) > 300:
        abort(400)
    message = event["data"]["id"].encode() + b"." + timestamp.encode() + b"." + raw
    expected = base64.b64encode(hmac.new(SECRET, message, hashlib.sha256).digest()).decode()
    if not hmac.compare_digest(given, expected):
        abort(401)
    print(event["event"], event["data"]["id"], event["data"]["status"])
    return "", 200
```

Retries, headers and deduplication are in [Webhooks](https://promptgale.com/docs/webhooks.md).

## Export a batch to CSV

Page through `GET /v1/batches/{id}/items?include=result` (up to 100 items per page with results) and write one row per item. The dashboard's batch page also has a CSV download.

**Python**

```python
import csv
import os
import sys
import requests

API = "https://promptgale.com"
HEADERS = {"Authorization": f"Bearer {os.environ['PROMPTGALE_API_KEY']}"}
batch_id = sys.argv[1]  # bat_...

with open(f"{batch_id}.csv", "w", newline="", encoding="utf-8") as f:
    out = csv.writer(f)
    out.writerow(["index", "custom_id", "engine", "status", "country", "answer", "cited_domains", "brand_mentioned", "brand_rank"])
    cursor = None
    while True:
        params = {"include": "result", "limit": 100, **({"cursor": cursor} if cursor else {})}
        page = requests.get(f"{API}/v1/batches/{batch_id}/items", headers=HEADERS, params=params).json()["data"]
        for item in page["items"]:
            task = item.get("task") or {}
            result = task.get("result") or {}
            target = next((b for b in result.get("analysis", {}).get("brands", []) if b["role"] == "target"), {})
            cited = sorted({s["domain"] for s in result.get("sources", []) if s["cited"]})
            out.writerow([item["index"], item["customId"], item["taskType"], item["status"], task.get("country"), result.get("text", ""), " ".join(cited), target.get("mentioned"), target.get("rank")])
        if not page["hasMore"]:
            break
        cursor = page["nextCursor"]
```

**Node.js**

```js
import { writeFileSync } from 'node:fs';

const API = 'https://promptgale.com';
const headers = { Authorization: `Bearer ${process.env.PROMPTGALE_API_KEY}` };
const batchId = process.argv[2]; // bat_...
const cell = (v) => `"${String(v ?? '').replace(/"/g, '""')}"`;

const rows = [['index', 'custom_id', 'engine', 'status', 'answer', 'cited_domains']];
let cursor = null;
do {
  const qs = new URLSearchParams({ include: 'result', limit: '100', ...(cursor ? { cursor } : {}) });
  const { data } = await (await fetch(`${API}/v1/batches/${batchId}/items?${qs}`, { headers })).json();
  for (const item of data.items) {
    const result = item.task?.result;
    const cited = result ? [...new Set(result.sources.filter((s) => s.cited).map((s) => s.domain))].join(' ') : '';
    rows.push([item.index, item.customId, item.taskType, item.status, result?.text, cited]);
  }
  cursor = data.hasMore ? data.nextCursor : null;
} while (cursor);

writeFileSync(`${batchId}.csv`, rows.map((r) => r.map(cell).join(',')).join('\n'));
```

---

Docs index: https://promptgale.com/llms.txt · Full reference: https://promptgale.com/llms-full.txt · OpenAPI: https://promptgale.com/v1/openapi.json
