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

# Enrich a column of domains

> Enrich Shopify domains in batches of 100 and preserve the retry key for each batch.

Send up to 100 storefront domains or URLs per request to `POST /v1/stores/enrich`. The response keeps input order and includes an outcome for every row, including repeats. A match includes a store record. A miss has outcome `not_found` and a null store.

Use a [team key](/docs/authentication.md) with `stores:read`. The team is charged once per distinct store in the billing period. See [usage and billing](/docs/usage.md) for how to check the remaining allowance.

## Run the recipe

1. Save the column as `domains.txt` with one domain or URL per line and no header. The scripts skip blank lines.
2. Export `SHOPLIST_API_KEY` from your secret store. Choose a unique run ID and save it with your input file.
3. Save and run one script below. Each writes one JSON object per input line to the output file, in input order.

```bash theme={null}
node enrich-domains.mjs domains.txt march-prospects-01 > enriched.jsonl
```

```bash theme={null}
python3 -m pip install requests
python3 enrich_domains.py domains.txt march-prospects-01 > enriched.jsonl
```

Restart a failed run with the same file and run ID to reuse its batch keys. On a restart, write to a fresh output file or replace the previous one so you keep one result per input. Start a new run ID for a changed input file. Each script retries transient errors with the same request and key. It honors `Retry-After` when present and applies backoff between attempts. On `402 allowance_exceeded`, check your team's allowance before restarting.

```javascript JavaScript theme={null}
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { setTimeout as sleep } from 'node:timers/promises';

const [file, runId] = process.argv.slice(2);
const apiKey = process.env.SHOPLIST_API_KEY;
if (!file || !runId || !apiKey) {
    throw new Error('Set SHOPLIST_API_KEY and pass a domain file and run ID.');
}

async function enrich(domains, key) {
    const body = JSON.stringify({ domains });
    const retryable = [409, 429, 500, 503];

    for (let attempt = 0; attempt < 5; attempt++) {
        const lastAttempt = attempt === 4;
        const backoff = 2 ** attempt;
        let response;
        let text;
        try {
            response = await fetch('https://api.shoplist.co/v1/stores/enrich', {
                method: 'POST',
                headers: {
                    Authorization: `Bearer ${apiKey}`,
                    'Content-Type': 'application/json',
                    'Idempotency-Key': key,
                },
                body,
                signal: AbortSignal.timeout(30_000),
            });
            text = await response.text();
        } catch (error) {
            if (lastAttempt) throw error;
            await sleep(backoff * 1000);
            continue;
        }
        if (response.ok) {
            const { data } = JSON.parse(text);
            return data;
        }
        if (lastAttempt || !retryable.includes(response.status)) {
            throw new Error(`HTTP ${response.status}: ${text}`);
        }
        const retryAfter = Number(response.headers.get('Retry-After'));
        const seconds = Number.isFinite(retryAfter) ? Math.max(backoff, retryAfter) : backoff;
        await sleep(seconds * 1000);
    }
}

const domains = (await readFile(file, 'utf8'))
    .split(/\r?\n/)
    .map((line) => line.trim())
    .filter(Boolean);

for (let offset = 0; offset < domains.length; offset += 100) {
    const key = createHash('sha256').update(`${runId}:${offset}`).digest('hex');
    const results = await enrich(domains.slice(offset, offset + 100), key);
    for (const result of results) console.log(JSON.stringify(result));
}
```

```python Python theme={null}
import hashlib
import json
import os
from pathlib import Path
import sys
import time

import requests


def enrich(domains, key, api_key):
    retryable = {409, 429, 500, 503}
    for attempt in range(5):
        last_attempt = attempt == 4
        backoff = 2**attempt
        try:
            response = requests.post(
                "https://api.shoplist.co/v1/stores/enrich",
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Idempotency-Key": key,
                },
                json={"domains": domains},
                timeout=30,
            )
        except (requests.ConnectionError, requests.Timeout):
            if last_attempt:
                raise
            time.sleep(backoff)
            continue
        if response.ok:
            return response.json()["data"]
        if last_attempt or response.status_code not in retryable:
            raise RuntimeError(f"HTTP {response.status_code}: {response.text}")
        retry_after = response.headers.get("Retry-After", "")
        seconds = int(retry_after) if retry_after.isascii() and retry_after.isdecimal() else 0
        time.sleep(max(backoff, seconds))


def main():
    api_key = os.environ.get("SHOPLIST_API_KEY")
    if len(sys.argv) != 3 or not sys.argv[2] or not api_key:
        raise SystemExit("Set SHOPLIST_API_KEY and pass a domain file and run ID.")

    file, run_id = sys.argv[1:]
    lines = Path(file).read_text(encoding="utf-8").splitlines()
    domains = [line.strip() for line in lines if line.strip()]
    for offset in range(0, len(domains), 100):
        key = hashlib.sha256(f"{run_id}:{offset}".encode()).hexdigest()
        for result in enrich(domains[offset : offset + 100], key, api_key):
            print(json.dumps(result))


if __name__ == "__main__":
    main()
```

See [idempotency](/docs/idempotency.md) for replay and [rate limits](/docs/rate-limits.md) for the retry headers.


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