# Writes: send, or preview first

---

## Overview

Every operation that changes data in the Fr8Labs API can be sent in **one call**:

* **Send it.** Send the request with an `Idempotency-Key` header. Every check runs on your **live** data first. Anything that blocks it is refused with nothing written. Anything you should know about comes back as a warning, and nothing is written until you send the request again acknowledging those warnings. Then the change is made **once**.

If you want to see what would happen before anything is written, **preview it first** (optional):


1. **Preview.** Send the same request to its dry run, `POST <path>/dry-runs`. It **writes nothing** and tells you what would happen, what blocks it, what you should know, and gives you a `dryRunId`.
2. **Send.** Send the real request with the `dryRunId` and the warnings you accept. The checks run again on fresh data, and exactly what was previewed is written.

If anything goes wrong in between (a timeout, a dropped connection), you send the **same request with the same** `**Idempotency-Key**` again. You get the stored answer back. You never create a second record by retrying.

Every write has a dry run. See the [Operations reference](https://docs.fr8labs.co/doc/operations-reference-hftBAXjsay) for each write's dry-run path.


---

## Is the dry run required?

No. The dry run is **optional on every write**: CRM, Freight operations and Accounting, including posting a draft.

A write sent without a dry run runs every check itself. It is still refused if something blocks it (`422 BLOCKED`), and it still needs every warning acknowledged: the first send answers `409 WARNINGS_NOT_ACKNOWLEDGED` with the **full warnings** in `details` (code, message and details), and nothing is written. Send the same request again, with the same `Idempotency-Key`, adding the codes you accept in `acknowledgedWarnings`.

Use a dry run when a person reviews the change before it is written, or when you need the document exactly as previewed (for example, the exchange rate it showed).

### Sending the same thing twice

If the **same request** (the same operation and the same body) was already written in the last **24 hours** under **another** `Idempotency-Key`, the write warns `DUPLICATE_REQUEST` and writes nothing. The warning names the earlier write (`meta.operationId`, `meta.sentAt`). If you really mean to write it again, acknowledge `DUPLICATE_REQUEST`. This protects you from a retry that used a new key by mistake.

`DUPLICATE_REQUEST` is not raised where sending twice is already harmless: accepting, cancelling or marking a quotation as sent (the second answers `alreadyApplied: true`), and `POST /partners` (the second answers the same party, `created: false`).


---

## Step 1 — The dry run

```
POST <path>/dry-runs
```

* Use the **same path** as the write (with the same ids in it), followed by `/dry-runs`. For example, the dry run of `PATCH /crm/leads/{name}` is `POST /crm/leads/{name}/dry-runs`.
* Send **exactly the body you will send on the write**. Do not include `dryRunId` or `acknowledgedWarnings` here: the dry run refuses them.
* The dry run needs no `Idempotency-Key`. On a write that changes an existing record, `If-Match` is optional on the dry run.

**Success Response (200):**

| Field | Meaning |
|-------|---------|
| `dryRunId` | The id to send on the write, for example `dr_` followed by 24 hex characters |
| `expiresAt` | When the dry run expires: **15 minutes** after it was made |
| `requestDigest` | A fingerprint of your request (`sha256:…`). The write must match it |
| `outcome` | `ready` (nothing blocks it) or `blocked` |
| `blocking` | What stops the write. Each item has a `code`, a `message`, and sometimes a `field` and `meta` |
| `warnings` | What you should know before you send it. Same shape. Each one must be acknowledged on the write |
| `preview` | What the write would do. Its shape depends on the operation |
| `sideEffects` | Anything else that happens when the write is made (for example, a number being used up) |
| `actingAs` | The API user the write acts as (`apiUser`), and `isAdmin`, which is always `false` |

> **Note**: A dry run answers `200` even when it is blocked. Check `outcome` and `blocking`. A blocked request sent as a write is refused with `422 BLOCKED`.

The codes each write can return in `blocking` and `warnings` are listed for that operation in the [live reference](https://notification-hub.fr8labs.co/api-docs).


---

## Step 2 — The write

Send the write to the operation's own method and path, with these headers and body.

| Header | Required | Value |
|--------|----------|-------|
| `Authorization` | Yes      | `Bearer fr8_live_<keyId>_<secret>` |
| `Content-Type` | Yes      | `application/json` |
| `Idempotency-Key` | Yes, on every write | 16 to 64 letters, digits or hyphens. A UUID works. Use a new one for each new change |
| `If-Match` | On writes that change an existing record | The record's current version. See [If-Match](#if-match-changing-an-existing-record) |

| Body field | Required | Meaning |
|------------|----------|---------|
| *(the operation's fields)* | As documented | **Exactly** what you sent to the dry run |
| `dryRunId` | Required for Freight operations and Accounting; optional for CRM | The `dryRunId` from step 1 |
| `acknowledgedWarnings` | When there are warnings | The **codes** of the warnings you accept, for example `["DUPLICATE_RECORD"]`. Up to 50, no repeats |

### What the write does, in order


1. Checks the `Idempotency-Key`. If you already used this key for this same request, you get the stored answer (see [Retrying safely](#retrying-safely)).
2. If you sent a `dryRunId`: checks the dry run. It must exist, belong to your key, be unused, be less than 15 minutes old, and match this request exactly.
3. Runs **every check on fresh data** (again, if you ran a dry run: something may have changed since).
   * Anything blocking → `422 BLOCKED`, with the findings in `details`.
   * A warning you did not acknowledge (including a **new** one that was not there at the dry run) → `409 WARNINGS_NOT_ACKNOWLEDGED`, and `details` carries each such warning in full (code, message, details). Review them, and send again acknowledging the codes you accept.
4. Makes the change, once.

### Answers

| Status | Meaning |
|--------|---------|
| `201 Created` | A new record was created. The body describes it |
| `200 OK` | An existing record was changed. Some writes answer `200` with `alreadyApplied: true` when the record was already in the state you asked for; nothing was changed |
| `202 Accepted` with `status: "OUTCOME_UNKNOWN"` | The change was sent, but its result is not known yet. See [When the outcome is unknown](#when-the-outcome-is-unknown) |
| `422 UPSTREAM_REJECTED` | The system of record refused the change. Read the `message`: usually nothing was changed, and you fix the request and start again with a new dry run and a new `Idempotency-Key`. Rarely, the message says the change **was** saved but not as intended (for example, a quotation edit whose rows came out differently); then check the record before you do anything else. This answer is stored: retrying the same `Idempotency-Key` returns it again |
| Any other error | See [Limits and errors](https://docs.fr8labs.co/doc/limits-and-errors-eC7kUPLFVj) |

A dry run can be used **once**. After a successful write (or a stored refusal), run a new dry run for the next change.


---

## If-Match: changing an existing record

Writes that change a record that already exists need an `If-Match` header carrying the record's version, exactly as the API returned it. This stops you from overwriting a change someone else made after you read the record.

| Writes | Version to send |
|--------|-----------------|
| CRM edits, status and owner changes | The record's `modified` value |
| Posting an accounting draft (`…/submit`) | The draft's `modified` value |
| Editing a quotation (`PATCH /quotations/{ref}`) | The quotation's `version` |
| Editing a master bill or a house bill | The job's or house bill's `version` (`GET /jobs/{id}` returns both) |

* The dry run's `preview` carries the version it saw (for CRM edits and accounting posts, `preview.modified`). Reading the record gives it too.
* No `If-Match` on the write → `428 PRECONDITION_REQUIRED`.
* A different current version → `412 PRECONDITION_FAILED`. Read the record again, run a new dry run, and send the new version.
* `If-Match` is not part of the request fingerprint, so a retry with the same `Idempotency-Key` gets its stored answer either way.


---

## Retrying safely

The `Idempotency-Key` makes a write safe to retry. Fr8Labs keeps the answer to each write for **7 days**, under the key that sent it (and its replacement after a rotation). Two different keys of your company never share idempotency records.

| You send | You get |
|----------|---------|
| The same `Idempotency-Key` and the same request, after it finished | The **stored answer**, with the header `Idempotent-Replayed: true`. Nothing is sent again |
| The same `Idempotency-Key` and the same request, while the first is still running | `409 IN_PROGRESS` with `Retry-After: 2`. Wait and retry with the same key |
| The same `Idempotency-Key` and the same request, when the outcome is unknown | `202 OUTCOME_UNKNOWN` again, with its `checkUrl` |
| The same `Idempotency-Key` with a **different** request | `422 IDEMPOTENCY_KEY_REUSED`. Use a new key for a new change |
| A new `Idempotency-Key` with a dry run that was already used | `409 DRY_RUN_USED`. Run a new dry run |
| A new `Idempotency-Key` with the same request, no dry run, within 24 hours of a write | `409 WARNINGS_NOT_ACKNOWLEDGED` with `DUPLICATE_REQUEST`, nothing written. Acknowledge it only if you mean a second record |

**The rule:** if you did not get an answer (a timeout, a dropped connection, a `503`), send the **same request with the same** `**Idempotency-Key**` again. Never switch to a new key to "try again": that is how duplicates happen.


---

## When the outcome is unknown

Sometimes a change has been sent but its result is not known, for example when a system it depends on timed out. Then the write answers:

```json
{ "status": "OUTCOME_UNKNOWN", "checkUrl": "/api/v1/operations/12345" }
```

* **Do not send the change again.** It may already have happened. Fr8Labs never re-sends it either.
* Ask for the outcome with `GET` on the `checkUrl` (add it to `https://notification-hub.fr8labs.co`), using the same key (or its replacement after a rotation):
  * the stored answer (`200`, `201` or `422`) once the outcome is known;
  * `202` again while it is still unknown;
  * `409 IN_PROGRESS` while the write is still running.
* Each call to `GET /operations/{id}` looks again. Poll it now and then, not in a tight loop.
* Some outcomes can only be settled by looking at the record itself. If `/operations` keeps answering `202`, check whether the record exists (for example with `GET /crm/search` or a list call) before you decide what to do next.


---

## Worked example: create a CRM lead

This example creates a lead, previews it first, and accepts a duplicate warning.

Which lead fields are required depends on your own CRM's lead form. Read it with `GET /crm/forms/lead`. A missing required field is reported in the dry run as the blocking code `MISSING_REQUIRED_FIELDS`, naming the fields. Values for fields with a fixed list of options (for example `source`, `status` or `industry`) must exist in your CRM.

### 1. Preview it

```bash
curl -X POST https://notification-hub.fr8labs.co/api/v1/crm/leads/dry-runs \
  -H "Authorization: Bearer fr8_live_<keyId>_<secret>" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Mei Ling",
    "last_name": "Tan",
    "email": "meiling.tan@example.com",
    "organization": "Example Trading Pte Ltd"
  }'
```

**Response (200)** (abridged; the `preview` shape depends on the operation):

```json
{
  "dryRunId": "dr_0123456789abcdef01234567",
  "expiresAt": "2026-10-16T08:15:00.000Z",
  "requestDigest": "sha256:…",
  "outcome": "ready",
  "blocking": [],
  "warnings": [
    {
      "code": "DUPLICATE_RECORD",
      "message": "A matching record already exists in your CRM. Acknowledge DUPLICATE_RECORD to create this one anyway.",
      "meta": { "matches": ["…"] }
    }
  ],
  "preview": { "action": "create", "type": "lead", "values": { "first_name": "Mei Ling", "…": "…" } },
  "sideEffects": [],
  "actingAs": { "apiUser": "<your API user's email>", "isAdmin": false }
}
```

The dry run found a matching lead. Look at `meta.matches`. If you still want a new lead, acknowledge `DUPLICATE_RECORD` on the write. If you do not, stop here: nothing was written.

### 2. Send it

Send the **same body**, plus `dryRunId` and `acknowledgedWarnings`, with a new `Idempotency-Key`:

```bash
curl -X POST https://notification-hub.fr8labs.co/api/v1/crm/leads \
  -H "Authorization: Bearer fr8_live_<keyId>_<secret>" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 6f1c2b9e-4d3a-4b8f-9c21-7e5a0d4f1b62" \
  -d '{
    "first_name": "Mei Ling",
    "last_name": "Tan",
    "email": "meiling.tan@example.com",
    "organization": "Example Trading Pte Ltd",
    "dryRunId": "dr_0123456789abcdef01234567",
    "acknowledgedWarnings": ["DUPLICATE_RECORD"]
  }'
```

**Response (201):**

```json
{
  "record": { "type": "lead", "name": "<lead name>" },
  "modified": "<the lead's modified value>",
  "confirmed": true,
  "readBack": { "attempts": 1, "matched": ["first_name", "last_name", "email"] }
}
```

* `record.name` is the lead's id. Use it for reads (`GET /crm/leads/{name}`) and edits.
* `modified` is the lead's version. Send it as `If-Match` on your next edit.
* `confirmed: true` means the new values were read back from the CRM. `confirmed: false` means the write was sent but the values could not be read back yet. It is **not** a failure.
* CRM writes also protect you against duplicates across keys: if the same content was already saved in the last 24 hours, the answer carries `alreadySaved: true` and no second record is created.

### The same flow in JavaScript (fetch)

Node.js 18 or later. Save it as an ES module (for example `create-lead.mjs`).

```javascript
import { randomUUID } from 'node:crypto';

const API_KEY = process.env.FR8LABS_API_KEY; // fr8_live_<keyId>_<secret>
const BASE_URL = 'https://notification-hub.fr8labs.co/api/v1';
const headers = { Authorization: `Bearer ${API_KEY}`, 'Content-Type': 'application/json' };

const lead = {
  first_name: 'Mei Ling',
  last_name: 'Tan',
  email: 'meiling.tan@example.com',
  organization: 'Example Trading Pte Ltd'
};

// 1. Preview
const dry = await (await fetch(`${BASE_URL}/crm/leads/dry-runs`, {
  method: 'POST', headers, body: JSON.stringify(lead)
})).json();

if (dry.outcome !== 'ready') throw new Error(`Blocked: ${JSON.stringify(dry.blocking)}`);
// Review dry.warnings here. Acknowledge only the codes you accept.
const acknowledgedWarnings = dry.warnings.map((w) => w.code);

// 2. Send, once. Keep the key: reuse it if you need to retry this same request.
const idempotencyKey = randomUUID();
const res = await fetch(`${BASE_URL}/crm/leads`, {
  method: 'POST',
  headers: { ...headers, 'Idempotency-Key': idempotencyKey },
  body: JSON.stringify({ ...lead, dryRunId: dry.dryRunId, acknowledgedWarnings })
});
const body = await res.json();

if (res.status === 202) {
  // Outcome unknown: do NOT re-send. Check later.
  console.log('Check later:', `https://notification-hub.fr8labs.co${body.checkUrl}`);
} else if (!res.ok) {
  console.error(res.status, body.error.code, body.error.message, body.error.requestId);
} else {
  console.log('Created lead', body.record.name);
}
```

### The same flow in Python (requests)

```python
import os
import uuid
import requests

API_KEY = os.environ["FR8LABS_API_KEY"]  # fr8_live_<keyId>_<secret>
BASE_URL = "https://notification-hub.fr8labs.co/api/v1"
headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}

lead = {
    "first_name": "Mei Ling",
    "last_name": "Tan",
    "email": "meiling.tan@example.com",
    "organization": "Example Trading Pte Ltd",
}

# 1. Preview
dry = requests.post(f"{BASE_URL}/crm/leads/dry-runs", headers=headers, json=lead).json()
if dry["outcome"] != "ready":
    raise SystemExit(f"Blocked: {dry['blocking']}")
# Review dry["warnings"] here. Acknowledge only the codes you accept.
acknowledged = [w["code"] for w in dry["warnings"]]

# 2. Send, once. Keep the key: reuse it if you need to retry this same request.
idempotency_key = str(uuid.uuid4())
res = requests.post(
    f"{BASE_URL}/crm/leads",
    headers={**headers, "Idempotency-Key": idempotency_key},
    json={**lead, "dryRunId": dry["dryRunId"], "acknowledgedWarnings": acknowledged},
)
body = res.json()

if res.status_code == 202:
    # Outcome unknown: do NOT re-send. Check later.
    print("Check later:", "https://notification-hub.fr8labs.co" + body["checkUrl"])
elif not res.ok:
    err = body["error"]
    print(res.status_code, err["code"], err["message"], err["requestId"])
else:
    print("Created lead", body["record"]["name"])
```

> **Note**: In real code, show the warnings to a person (or check them against a rule) before you acknowledge them. Acknowledging every warning automatically defeats the point of the preview.


---

## Common questions

**Can I change the body between the dry run and the write?** No. The write must match the dry run exactly (apart from `dryRunId` and `acknowledgedWarnings`). A different body is refused with `409 DRY_RUN_STALE`. Run a new dry run.

**My dry run expired.** Dry runs last 15 minutes. The write answers `409 DRY_RUN_EXPIRED`. Run the dry run again.

**Something changed between the dry run and the write.** The write runs its checks again. If the record moved on in a way that matters, the write is refused with `422 BLOCKED`, and `details` carries a code such as `CHANGED_SINCE_DRY_RUN`. Run a new dry run.

**Can I use the API access tile's "Try it" console to send writes?** On live, the console runs reads and dry runs only. A write sent from it is refused with `403 CONSOLE_LIVE_READ_ONLY`. Use a key from your own system to send writes.


---

Documentation owner: Fr8Labs Customer Success. Text reviewed: 18 October 2026.