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

# First pre-test

> From zero to PDF: create a key, upload a creative and read the result.

In this guide you create an out-of-home (OOH) pre-test and download the PDF. The values in the examples are made up.

> [!WARNING]
>
> The API key is a server secret. Keep it in an environment variable on your back end. Never put it in browser code, in a mobile app or in a repository.

## 1. Create the key in the dashboard

1. Sign in to the Unite dashboard with a workspace **administrator** account.
2. Open the workspace administration area and go to **API keys**.
3. Click **Create key**.
4. Give it a name (for example, "CRM integration"), choose the **Read pre-tests** and **Create pre-tests** permissions and set the expiry.
5. Click **Create key** and copy the value. It is shown only once.

If the screen says the API is not yet enabled for the workspace, contact the Unite team.

In the examples below, the key lives in the `UNITE_API_KEY` variable. The value has the format `unite_live_YOUR_KEY_HERE`.

```bash theme={null}
export UNITE_API_KEY="unite_live_YOUR_KEY_HERE"
```

The blocks for each language form a single script: you can paste steps 2 to 7 into one file, in order. In curl, each step stores the values the next one needs in shell variables (requires `jq`). The JavaScript examples use `node` 18 or newer, as an ES module (`.mjs`).

## 2. Read the catalog

The catalog lists the OOH formats, the digital platforms and the workspace brands. Keep the `key` of the format you will use.

```bash curl theme={null}
curl -s https://myunite.ai/api/v1/catalog \
  -H "Authorization: Bearer $UNITE_API_KEY" -o catalog.json

export FORMAT_KEY=$(jq -r '.ooh.formats[0].key' catalog.json)
echo "$FORMAT_KEY"
```

```javascript JavaScript theme={null}
import { readFile } from "node:fs/promises";

const catalogRes = await fetch("https://myunite.ai/api/v1/catalog", {
  headers: { Authorization: `Bearer ${process.env.UNITE_API_KEY}` },
});
const catalog = await catalogRes.json();
const formatKey = catalog.ooh.formats[0].key;
console.log(formatKey);
```

```python Python theme={null}
import os
import time
import requests

API = "https://myunite.ai/api/v1"
AUTH = {"Authorization": f"Bearer {os.environ['UNITE_API_KEY']}"}

catalog = requests.get(f"{API}/catalog", headers=AUTH).json()
format_key = catalog["ooh"]["formats"][0]["key"]
print(format_key)
```

## 3. Request the upload address

Provide the file type and size. The response contains the `uploadId` and an upload URL valid for 15 minutes.

```bash curl theme={null}
SIZE=$(wc -c < summer-urban-clock.png | tr -d ' ')

curl -s -X POST https://myunite.ai/api/v1/uploads \
  -H "Authorization: Bearer $UNITE_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"contentType\":\"image/png\",\"sizeBytes\":$SIZE,\"filename\":\"summer-urban-clock.png\"}" \
  -o upload.json

export UPLOAD_ID=$(jq -r '.uploadId' upload.json)
export UPLOAD_URL=$(jq -r '.uploadUrl' upload.json)
export CACHE_CONTROL=$(jq -r '.headers["Cache-Control"]' upload.json)
```

```javascript JavaScript theme={null}
const file = await readFile("summer-urban-clock.png");

const uploadRes = await fetch("https://myunite.ai/api/v1/uploads", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.UNITE_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    contentType: "image/png",
    sizeBytes: file.length,
    filename: "summer-urban-clock.png",
  }),
});
const target = await uploadRes.json();
```

```python Python theme={null}
with open("summer-urban-clock.png", "rb") as f:
    file_bytes = f.read()

target = requests.post(
    f"{API}/uploads",
    headers=AUTH,
    json={
        "contentType": "image/png",
        "sizeBytes": len(file_bytes),
        "filename": "summer-urban-clock.png",
    },
).json()
```

Response (made-up values; the real `uploadUrl` is long and changes with every request):

```json theme={null}
{
  "uploadId": "upl_0123456789abcdef0123456789abcdef.png",
  "uploadUrl": "https://storage.example/...",
  "method": "PUT",
  "headers": {
    "Content-Type": "image/png",
    "Cache-Control": "public, max-age=31536000, immutable"
  },
  "expiresAt": "2026-11-16T14:15:00.000Z"
}
```

## 4. Upload the file

Make a `PUT` of the file to the `uploadUrl`, with **all** the returned headers, with exactly the same values. This call does not carry the API key. See the details in [File uploads](https://docs.myunite.ai/en/uploads.md).

```bash curl theme={null}
curl -X PUT "$UPLOAD_URL" \
  -H "Content-Type: image/png" \
  -H "Cache-Control: $CACHE_CONTROL" \
  --data-binary @summer-urban-clock.png
```

```javascript JavaScript theme={null}
const putRes = await fetch(target.uploadUrl, {
  method: target.method,
  headers: target.headers, // all of them, unchanged
  body: file,
});
if (!putRes.ok) throw new Error(`Upload failed: ${putRes.status}`);
```

```python Python theme={null}
put_res = requests.put(target["uploadUrl"], headers=target["headers"], data=file_bytes)
put_res.raise_for_status()
```

## 5. Create the pre-test

Send the `uploadId` and the channel. The `Idempotency-Key` header is required: use a new value for each pre-test and reuse it only to repeat the same call. See [Idempotency](https://docs.myunite.ai/en/idempotency.md).

```bash curl theme={null}
curl -s -X POST https://myunite.ai/api/v1/pretests \
  -H "Authorization: Bearer $UNITE_API_KEY" \
  -H "Idempotency-Key: summer-urban-clock-001" \
  -H "Content-Type: application/json" \
  -d "{
    \"uploadId\": \"$UPLOAD_ID\",
    \"title\": \"Summer · urban clock\",
    \"channel\": \"ooh\",
    \"ooh\": { \"format\": \"$FORMAT_KEY\" }
  }" -o pretest.json

export PRETEST_ID=$(jq -r '.id' pretest.json)
jq -r '.status' pretest.json   # queued
```

```javascript JavaScript theme={null}
const createRes = await fetch("https://myunite.ai/api/v1/pretests", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.UNITE_API_KEY}`,
    "Idempotency-Key": "summer-urban-clock-001",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    uploadId: target.uploadId,
    title: "Summer · urban clock",
    channel: "ooh",
    ooh: { format: formatKey },
  }),
});
const pretest = await createRes.json(); // status 202, pretest.status === "queued"
```

```python Python theme={null}
create_res = requests.post(
    f"{API}/pretests",
    headers={**AUTH, "Idempotency-Key": "summer-urban-clock-001"},
    json={
        "uploadId": target["uploadId"],
        "title": "Summer · urban clock",
        "channel": "ooh",
        "ooh": {"format": format_key},
    },
)
pretest = create_res.json()  # status 202, pretest["status"] == "queued"
```

The response is `202` and carries the `Location` header with the pre-test address.

## 6. Poll until `completed`

```bash curl theme={null}
while true; do
  STATUS=$(curl -s "https://myunite.ai/api/v1/pretests/$PRETEST_ID" \
    -H "Authorization: Bearer $UNITE_API_KEY" | jq -r '.status')
  echo "$STATUS"
  if [ "$STATUS" = "completed" ] || [ "$STATUS" = "failed" ]; then break; fi
  sleep 10
done
```

```javascript JavaScript theme={null}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

let current = pretest;
while (current.status === "queued" || current.status === "processing") {
  await sleep(10_000);
  const statusRes = await fetch(`https://myunite.ai/api/v1/pretests/${pretest.id}`, {
    headers: { Authorization: `Bearer ${process.env.UNITE_API_KEY}` },
  });
  current = await statusRes.json();
}
console.log(current.status, current.result?.score);
```

```python Python theme={null}
current = pretest
while current["status"] in ("queued", "processing"):
    time.sleep(10)
    current = requests.get(f"{API}/pretests/{pretest['id']}", headers=AUTH).json()
print(current["status"], (current.get("result") or {}).get("score"))
```

Poll every 10 seconds or more. With `completed`, the `result` field carries the score, pillars and findings (see [Results](https://docs.myunite.ai/en/results.md)). With `failed`, the `error.code` field gives the reason. If it ends in `failed`, stop here: there is no PDF to download.

## 7. Download the PDF

The PDF is generated on demand. If it is still being generated, the response is `202` with `Retry-After`: wait that many seconds and try again. With `200` and `status: "ready"`, download the file from `url`. That second call is a plain `GET` on the `url`, without the API key.

```bash curl theme={null}
while true; do
  CODE=$(curl -s -o report.json -D report-headers.txt -w "%{http_code}" \
    "https://myunite.ai/api/v1/pretests/$PRETEST_ID/report" \
    -H "Authorization: Bearer $UNITE_API_KEY")
  if [ "$CODE" = "200" ]; then break; fi
  if [ "$CODE" != "202" ]; then break; fi
  WAIT=$(grep -i '^retry-after:' report-headers.txt | tr -dc '0-9')
  sleep "${WAIT:-15}"
done

if [ "$CODE" = "200" ]; then
  curl -s -o analysis.pdf "$(jq -r '.url' report.json)"
else
  echo "Failed to generate the PDF: HTTP $CODE"; cat report.json
fi
```

```javascript JavaScript theme={null}
import { writeFile } from "node:fs/promises";

let report;
while (true) {
  const reportRes = await fetch(`https://myunite.ai/api/v1/pretests/${pretest.id}/report`, {
    headers: { Authorization: `Bearer ${process.env.UNITE_API_KEY}` },
  });
  if (reportRes.status === 200) {
    report = await reportRes.json();
    break;
  }
  if (reportRes.status !== 202) throw new Error(`Failed to generate the PDF: ${reportRes.status}`);
  await sleep(Number(reportRes.headers.get("Retry-After") ?? "15") * 1000);
}

const pdfRes = await fetch(report.url); // no Authorization
await writeFile("analysis.pdf", Buffer.from(await pdfRes.arrayBuffer()));
```

```python Python theme={null}
while True:
    report_res = requests.get(f"{API}/pretests/{pretest['id']}/report", headers=AUTH)
    if report_res.status_code == 200:
        report = report_res.json()
        break
    if report_res.status_code != 202:
        raise RuntimeError(f"Failed to generate the PDF: {report_res.status_code}")
    time.sleep(int(report_res.headers.get("Retry-After", "15")))

pdf_res = requests.get(report["url"])  # no Authorization
with open("analysis.pdf", "wb") as f:
    f.write(pdf_res.content)
```

Fetch the link when you need the file, and do not count on the URL staying the same: request the PDF again instead of storing the link.

## Next steps

* Choose the channel: [OOH](https://docs.myunite.ai/en/pretests/ooh.md), [Digital](https://docs.myunite.ai/en/pretests/digital.md) or [Email](https://docs.myunite.ai/en/pretests/email.md).
* Handle failures with the list of [errors](https://docs.myunite.ai/en/errors.md).
* Learn about the [rate limits](https://docs.myunite.ai/en/rate-limits.md).


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