# Code Examples

> Start with cURL, JavaScript, Python, PHP, Postman, BI tools, and scheduled jobs.

> Start API integrations with copyable cURL, JavaScript, Python, PHP, Postman, BI, and scheduled-job patterns.

Never place a real API key in documentation, browser code, screenshots, or client-side configuration.

Use `YOUR_KOMMON_POLL_API_KEY` only as a placeholder.

---

## Starter Examples

::tabs[API Code Examples]
:::tab[cURL]
Set the key as an environment variable:

```bash
export KOMMON_POLL_API_KEY="YOUR_KOMMON_POLL_API_KEY"
```

List saved searches:

```bash
curl https://api.kommonpoll.com/v4/list \
  -H "Authorization: Bearer $KOMMON_POLL_API_KEY"
```

Request a 7-day overview:

```bash
curl "https://api.kommonpoll.com/v4/search?aid=<AID>&duration=7d&timezone=Asia%2FColombo" \
  -H "Authorization: Bearer $KOMMON_POLL_API_KEY"
```

Request the first page of newest mentions:

```bash
curl "https://api.kommonpoll.com/v4/search?aid=<AID>&duration=30d&dataFrom=0&dataSize=50&sortBy=dateDesc" \
  -H "Authorization: Bearer $KOMMON_POLL_API_KEY"
```
:::

:::tab[JavaScript]
```javascript
const API_KEY = process.env.KOMMON_POLL_API_KEY;
const BASE_URL = "https://api.kommonpoll.com/v4";

async function request(path) {
  const response = await fetch(`${BASE_URL}${path}`, {
    headers: {
      Authorization: `Bearer ${API_KEY}`,
    },
  });

  if (!response.ok) {
    throw new Error(`Kommon Poll API request failed: ${response.status}`);
  }

  return response.json();
}

async function run() {
  const list = await request("/list");
  const aid = list.savedSearches?.[0]?.aid || list.teamSavedSearches?.[0]?.aid;

  if (!aid) {
    throw new Error("No saved search aid was available to this API key.");
  }

  const overview = await request(`/search?aid=${encodeURIComponent(aid)}&duration=7d`);
  const mentions = await request(`/search?aid=${encodeURIComponent(aid)}&duration=7d&dataFrom=0&dataSize=50&sortBy=dateDesc`);

  console.log({ overview, mentions });
}

run().catch((error) => {
  console.error(error.message);
  process.exitCode = 1;
});
```
:::

:::tab[Python]
```python
import os
import requests

API_KEY = os.environ["KOMMON_POLL_API_KEY"]
BASE_URL = "https://api.kommonpoll.com/v4"


def request(path, params=None):
    response = requests.get(
        f"{BASE_URL}{path}",
        headers={"Authorization": f"Bearer {API_KEY}"},
        params=params,
        timeout=30,
    )
    response.raise_for_status()
    return response.json()


searches = request("/list")
aid = (searches.get("savedSearches") or searches.get("teamSavedSearches") or [{}])[0].get("aid")

if not aid:
    raise RuntimeError("No saved search aid was available to this API key.")

overview = request("/search", {"aid": aid, "duration": "7d", "timezone": "Asia/Colombo"})
mentions = request(
    "/search",
    {
        "aid": aid,
        "duration": "7d",
        "dataFrom": 0,
        "dataSize": 50,
        "sortBy": "dateDesc",
    },
)

print(overview)
print(mentions)
```
:::

:::tab[PHP]
```php
<?php

$apiKey = getenv('KOMMON_POLL_API_KEY');
$baseUrl = 'https://api.kommonpoll.com/v4';

function kp_api_get(string $path, array $params = []): array
{
    global $apiKey, $baseUrl;

    $url = $baseUrl . $path;
    if ($params !== []) {
        $url .= '?' . http_build_query($params);
    }

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
        ],
    ]);

    $body = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($status < 200 || $status >= 300) {
        throw new RuntimeException('Kommon Poll API request failed: ' . $status);
    }

    return json_decode((string) $body, true, 512, JSON_THROW_ON_ERROR);
}

$list = kp_api_get('/list');
$aid = $list['savedSearches'][0]['aid'] ?? $list['teamSavedSearches'][0]['aid'] ?? null;

if ($aid === null) {
    throw new RuntimeException('No saved search aid was available to this API key.');
}

$overview = kp_api_get('/search', [
    'aid' => $aid,
    'duration' => '7d',
    'timezone' => 'Asia/Colombo',
]);

$mentions = kp_api_get('/search', [
    'aid' => $aid,
    'duration' => '7d',
    'dataFrom' => 0,
    'dataSize' => 50,
    'sortBy' => 'dateDesc',
]);
```
:::

:::tab[Postman]
Recommended setup:

1. Create an environment variable named `KOMMON_POLL_API_KEY`.
2. Create another variable named `AID` after calling `GET /v4/list`.
3. Set Authorization type to **Bearer Token**.
4. Use `{{KOMMON_POLL_API_KEY}}` as the token value.
5. Add a `GET` request for `https://api.kommonpoll.com/v4/list`.
6. Add a `GET` request for `https://api.kommonpoll.com/v4/search?aid={{AID}}&duration=7d`.
7. Add a mentions request with `dataFrom=0`, `dataSize=50`, and `sortBy=dateDesc`.

Do not sync environments that contain production keys unless your organization allows that storage model.
:::

:::tab[BI Tools]
For Power BI, warehouse ingestion, or similar tools:

- Use `GET /v4/list` during configuration to map saved searches to `aid` values.
- Store the API key in the BI tool's approved credential store or a secure server-side connector.
- Use `GET /v4/search` on a schedule.
- Paginate mentions with `dataFrom` and `dataSize`.
- Keep overview refreshes separate from full mention exports.
- Preserve `aid`, request period, timezone, and filters in the downstream dataset.

When a BI tool cannot protect bearer credentials safely, use a trusted backend job to retrieve data and load the downstream system.
:::

:::tab[Scheduled Jobs]
A scheduled server or serverless job should:

- Load the API key from a secure runtime secret.
- Store the selected `aid` in application configuration.
- Run `GET /v4/search` with an explicit `duration` and `timezone`.
- Paginate mention pages when needed.
- Create email, PDF, DOCX, slides, BI, or warehouse outputs downstream.
- Log status codes, request IDs if returned, and job duration.
- Redact the `Authorization` header and API key.
- Retry only `429` and temporary `5xx` responses.
:::
::endtabs

---

## Production Notes

- Start with `GET /v4/list` to confirm authentication and discover an `aid`.
- Use `GET /v4/search?aid=<AID>` for overview analytics.
- Add `dataFrom` and a positive `dataSize` when you need mention records.
- Keep `dataSize` at or below `500`.
- Set `duration` and `timezone` explicitly for scheduled jobs.
- Redact API keys and bearer headers from logs.
