# Quickstart

This walks the entire loop: name a target, review its prompts, run a measurement, and read the
result. Everything here uses one API key and no SDK.

You need a `bkt_` key from **Settings → Developer & AI → API keys**, on a paid plan (a free plan reaches only the Zapier endpoints). See [Authentication](/docs/guides/authentication/)
if you do not have one yet.

```bash
export BEKET_API_KEY="bkt_..."
```

## The shape of the loop

```
  1  POST /audits                       name the target     →  auditId, status PENDING
  2  POST /audits/:id/prepare           explore + profile   →  202; poll to AWAITING_CONFIG
  3  POST /audits/:id/prompts/generate  generate prompts    →  costs money, once per audit
  4  GET  /audits/:id/config-options    what your plan allows
  5  POST /audits/:id/start             begin measuring     →  202 + estimate
  6  GET  /audits/:id/run               poll                →  respect retryAfterMs
  7  GET  /audits/:id/snapshots         a run finished      →  cheap, poll this over time
  8  POST /graphql                      read the report     →  one section at a time
```

Steps 1–5 are setup and happen once. Steps 7–8 are the part a long-running integration repeats.

:::caution[Step 2 is not optional]
A new audit is created `PENDING`, which has no brand profile — and prompts are generated from that
profile. Both `prompts/generate` and `start` reject a `PENDING` audit with a **409**. Preparing is
what moves it to `AWAITING_CONFIG`, and it is asynchronous, so you must wait for that status before
continuing.
:::

1. ### Create an audit

   The fastest path is a bare domain. To map a market instead of a brand, send `topic` in place of
   `domain`.

   **curl**

   ```bash
   curl -X POST "https://api.beket.ai/api/v1/audits" \
     -H "Authorization: Bearer $BEKET_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{"domain": "example.com"}'
   ```

   **TypeScript**

   ```ts
   const BASE = 'https://api.beket.ai/api/v1';

   const headers = {
     Authorization: `Bearer ${process.env.BEKET_API_KEY}`,
     'Content-Type': 'application/json',
   };

   const created = await fetch(`${BASE}/audits`, {
     method: 'POST',
     headers,
     body: JSON.stringify({ domain: 'example.com' }),
   });

   const { data: audit } = await created.json();
   const auditId = audit.id;
   ```

   **Python**

   ```python
   import os, requests

   BASE = "https://api.beket.ai/api/v1"
   headers = {"Authorization": f"Bearer {os.environ['BEKET_API_KEY']}"}

   created = requests.post(f"{BASE}/audits", headers=headers, json={"domain": "example.com"})
   created.raise_for_status()
   audit_id = created.json()["data"]["id"]
   ```

   The audit is created `PENDING`. Nothing is measured and nothing is billed yet.

2. ### Prepare it, and wait for `AWAITING_CONFIG`

   Preparing explores the target, infers the brand profile, and selects the angles. Everything
   after this depends on it.

   **curl**

   ```bash
   curl -X POST "https://api.beket.ai/api/v1/audits/AUDIT_ID/prepare" \
     -H "Authorization: Bearer $BEKET_API_KEY"

   # 202 Accepted. Now poll until the status reaches AWAITING_CONFIG:
   curl "https://api.beket.ai/api/v1/audits/AUDIT_ID" \
     -H "Authorization: Bearer $BEKET_API_KEY"
   ```

   **TypeScript**

   ```ts
   await fetch(`${BASE}/audits/${auditId}/prepare`, { method: 'POST', headers });

   // 202 Accepted — the work runs on a queue, so wait for the status rather than
   // assuming the next call will succeed.
   async function waitForConfig(auditId: string) {
     for (;;) {
       const response = await fetch(`${BASE}/audits/${auditId}`, { headers });
       const { data } = await response.json();

       if (data.status === 'AWAITING_CONFIG' || data.status === 'AWAITING_PROMPTS') return data;
       if (data.status === 'FAILED') throw new Error('Preparation failed');

       await new Promise((resolve) => setTimeout(resolve, 5_000));
     }
   }

   await waitForConfig(auditId);
   ```

   **Python**

   ```python
   import time

   requests.post(f"{BASE}/audits/{audit_id}/prepare", headers=headers).raise_for_status()

   # 202 Accepted — the work runs on a queue, so wait for the status.
   def wait_for_config(audit_id):
       while True:
           response = requests.get(f"{BASE}/audits/{audit_id}", headers=headers)
           response.raise_for_status()
           data = response.json()["data"]

           if data["status"] in ("AWAITING_CONFIG", "AWAITING_PROMPTS"):
               return data
           if data["status"] == "FAILED":
               raise RuntimeError("Preparation failed")

           time.sleep(5)

   wait_for_config(audit_id)
   ```

   This one also costs money — it crawls the target and runs an LLM. Prepare an audit once; do not
   re-prepare one that is past `PENDING`, because that redoes the work and clobbers configuration
   you have already set.

3. ### Generate the prompts

   Prompts are the questions the audit asks the AI surfaces. They are generated from the brand
   profile, once per audit.

   :::caution[This call costs money]
   It runs an LLM generation. Treat it as a one-time setup step, not something to retry in a loop.
   :::

   **curl**

   ```bash
   curl -X POST "https://api.beket.ai/api/v1/audits/AUDIT_ID/prompts/generate" \
     -H "Authorization: Bearer $BEKET_API_KEY"
   ```

   **TypeScript**

   ```ts
   const generated = await fetch(`${BASE}/audits/${auditId}/prompts/generate`, {
     method: 'POST',
     headers,
   });

   const { data: prompts } = await generated.json();
   ```

   **Python**

   ```python
   generated = requests.post(f"{BASE}/audits/{audit_id}/prompts/generate", headers=headers)
   generated.raise_for_status()
   prompts = generated.json()["data"]
   ```

   The audit is now awaiting prompt review. Read the set back with
   `GET /audits/{auditId}/prompts` — `maxQueries` there is your plan's ceiling on how many may be
   selected, and selecting more is rejected when the run starts, not when you select them.

4. ### Check what your plan allows

   Connector availability and the connector ceiling are plan-dependent. Reading this first is
   cheaper than having a selection silently clamped.

   ```bash
   curl "https://api.beket.ai/api/v1/audits/AUDIT_ID/config-options" \
     -H "Authorization: Bearer $BEKET_API_KEY"
   ```

5. ### Start the run

   **curl**

   ```bash
   curl -X POST "https://api.beket.ai/api/v1/audits/AUDIT_ID/start" \
     -H "Authorization: Bearer $BEKET_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{"connectorTypes": ["OPENAI"]}'
   ```

   **TypeScript**

   ```ts
   const started = await fetch(`${BASE}/audits/${auditId}/start`, {
     method: 'POST',
     headers,
     body: JSON.stringify({ connectorTypes: ['OPENAI'] }),
   });

   // 202 Accepted. `effectiveConnectors` is what the plan actually kept.
   const { data: estimate } = await started.json();
   ```

   **Python**

   ```python
   started = requests.post(
       f"{BASE}/audits/{audit_id}/start",
       headers=headers,
       json={"connectorTypes": ["OPENAI"]},
   )
   started.raise_for_status()
   estimate = started.json()["data"]
   ```

   This answers **202**, not 200 — the run is enqueued, not finished. The response carries an
   estimate of the run's size and, importantly, `effectiveConnectors` and `droppedConnectors`:
   your selection is **clamped to the plan's ceiling rather than rejected**, so read back what was
   actually kept instead of assuming you got what you asked for.

6. ### Poll until it finishes

   Use the server's own guidance on when to poll again. `retryAfterMs` varies with the phase the
   run is in, and polling faster does not make a run finish sooner.

   **curl**

   ```bash
   curl "https://api.beket.ai/api/v1/audits/AUDIT_ID/run" \
     -H "Authorization: Bearer $BEKET_API_KEY"
   ```

   **TypeScript**

   ```ts
   async function waitForRun(auditId: string) {
     for (;;) {
       const response = await fetch(`${BASE}/audits/${auditId}/run`, { headers });
       const { data } = await response.json();

       if (data.runStatus === 'COMPLETED' || data.runStatus === 'FAILED') return data;

       // The server tells you when to come back. Do not replace this with a fixed interval.
       await new Promise((resolve) => setTimeout(resolve, data.retryAfterMs ?? 10_000));
     }
   }
   ```

   **Python**

   ```python
   import time

   def wait_for_run(audit_id):
       while True:
           response = requests.get(f"{BASE}/audits/{audit_id}/run", headers=headers)
           response.raise_for_status()
           data = response.json()["data"]

           if data["runStatus"] in ("COMPLETED", "FAILED"):
               return data

           # The server tells you when to come back. Do not replace this with a fixed interval.
           time.sleep((data["retryAfterMs"] or 10_000) / 1000)
   ```

7. ### Find the snapshot

   A completed run produces a **snapshot**. Snapshots are the cheap thing to watch: each carries
   summary metrics and `reportAvailable`, and the list is cursor-paginated newest-first.

   ```bash
   curl "https://api.beket.ai/api/v1/audits/AUDIT_ID/snapshots?limit=1" \
     -H "Authorization: Bearer $BEKET_API_KEY"
   ```

   The report's written analysis lands shortly after the run. `GET /audits/{auditId}/synthesis`
   answers `llm: true` once it has.

8. ### Read the report

   The report is read through GraphQL, one section at a time — note the path is `/graphql` at the
   API's origin, not under `/api/v1`:

   ```bash
   curl -X POST "https://api.beket.ai/graphql" \
     -H "Authorization: Bearer $BEKET_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{"query": "query ($auditId: String!) { reportOverview(auditId: $auditId) { brandName executiveSummary headline { visibility shareOfVoice } } }", "variables": {"auditId": "AUDIT_ID"}}'
   ```

   [Reading the report](/docs/guides/reading-the-report/) lists every section — winnable prompts,
   the content roadmap, the market leaderboard — and how each one refuses.

## Watching an audit over time

Once the first run is done, the recurring shape of an integration is small:

```
  poll  GET  /audits/:id/snapshots          ← cheap, summary metrics per snapshot
        ↓  a new snapshot appeared
  diff  GET  /audits/:id/snapshots/compare  ← what moved since the one before
  read  POST /graphql                       ← the report sections you show
```

The report changes only when a run completes, so reading it on a timer is wasted transfer on both
sides. Poll the snapshot list, notice a new entry, and read then.

For "what moved since last time", `GET /audits/{auditId}/snapshots/compare?b=SNAPSHOT_ID` compares a
snapshot with the baseline it was taken against: prompts, metrics, competitors, cited sources and
recommendations. Send its `ETag` back as `If-None-Match` and an unchanged comparison costs a
**304**.

For the raw material — every answer, one row each — page through
`GET /audits/{auditId}/answers/export` with a date range, or fetch the same as CSV from
`answers/export.csv`.

## Next

- [Reading the report](/docs/guides/reading-the-report/) — every report section, in GraphQL
- [Core concepts](/docs/guides/concepts/) — what an audit, a run, and a snapshot each are
- [Errors](/docs/guides/errors/) — the envelope, the status codes, and which are worth retrying
- [API reference](/docs/reference/audits/) — every documented endpoint
