# API examples

> Call the GetIntel API from curl, JavaScript and Python, and export your topic scores to a CSV file every day.

Source: https://getintel.ai/docs/api/examples/

## Read your topics

<Tabs syncKey="api-lang">
<TabItem label="curl">
```sh
curl "https://app.getintel.ai/api/v1/topics?days=30" \
  -H "Authorization: Bearer $GETINTEL_API_KEY"
```
</TabItem>
<TabItem label="JavaScript">
```js
const res = await fetch('https://app.getintel.ai/api/v1/topics?days=30', {
  headers: { Authorization: `Bearer ${process.env.GETINTEL_API_KEY}` },
})
const body = await res.json()
if (!res.ok) throw new Error(`${body.error.code}: ${body.error.message}`)

for (const topic of body.data.topics) {
  console.log(topic.name, topic.visibility)
}
```
</TabItem>
<TabItem label="Python">
```python

res = requests.get(
    "https://app.getintel.ai/api/v1/topics",
    params={"days": 30},
    headers={"Authorization": f"Bearer {os.environ['GETINTEL_API_KEY']}"},
    timeout=30,
)
body = res.json()
if not res.ok:
    raise RuntimeError(f"{body['error']['code']}: {body['error']['message']}")

for topic in body["data"]["topics"]:
    print(topic["name"], topic["visibility"])
```
</TabItem>
</Tabs>

## Every brand on an agency account

<Tabs syncKey="api-lang">
<TabItem label="JavaScript">
```js
const api = (path) =>
  fetch(`https://app.getintel.ai/api/v1/${path}`, {
    headers: { Authorization: `Bearer ${process.env.GETINTEL_API_KEY}` },
  }).then((r) => r.json())

const { data: brands } = await api('brands')
for (const brand of brands) {
  const { data } = await api(`overview?brand_id=${brand.id}&days=7`)
  console.log(brand.name, data.visibility)
}
```
</TabItem>
<TabItem label="Python">
```python

session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['GETINTEL_API_KEY']}"
base = "https://app.getintel.ai/api/v1"

for brand in session.get(f"{base}/brands", timeout=30).json()["data"]:
    overview = session.get(f"{base}/overview", params={"brand_id": brand["id"], "days": 7}, timeout=30).json()
    print(brand["name"], overview["data"]["visibility"])
```
</TabItem>
</Tabs>

## Export topic scores to CSV every day

Run this once a day (for example from cron after 10am IST, once the daily scan has finished) to keep a history in your own storage:

```python

res = requests.get(
    "https://app.getintel.ai/api/v1/topics",
    params={"days": 1},
    headers={"Authorization": f"Bearer {os.environ['GETINTEL_API_KEY']}"},
    timeout=30,
)
res.raise_for_status()
today = datetime.date.today().isoformat()

with open("topic_scores.csv", "a", newline="") as f:
    writer = csv.writer(f)
    for topic in res.json()["data"]["topics"]:
        writer.writerow([today, topic["name"], topic["visibility"]])
```

## Handle limits

Check the error code, and back off on `429`:

```js
async function getintel(path, tries = 3) {
  const res = await fetch(`https://app.getintel.ai/api/v1/${path}`, {
    headers: { Authorization: `Bearer ${process.env.GETINTEL_API_KEY}` },
  })
  if (res.status === 429 && tries > 0) {
    const body = await res.json()
    if (body.error.code === 'quota_exceeded') throw new Error(body.error.message) // wait for next month
    const wait = Number(res.headers.get('Retry-After') || 30)
    await new Promise((r) => setTimeout(r, wait * 1000))
    return getintel(path, tries - 1)
  }
  return res.json()
}
```
