# Upload large recordings in chunks

> Send a meeting or transcription recording, or a video to translate, in chunks, then make the job from it. A broken connection costs one chunk, not the whole file, and files can be larger than one request allows. Sequence: `POST /api/v1/uploads` → `PUT /api/v1/uploads/{uploadId}/chunks/{index}` for every chunk (any order, retry freely) → `POST /api/v1/meetings/jobs`, `POST /api/v1/transcription/jobs` or `POST /api/v1/video/jobs` with a JSON body `{ "uploadId": "upl_..." }`.

## At a glance

- Base path: `/api/v1/uploads`
- Auth: `Authorization: Bearer fara_sk_...` ([Authentication](https://faraatarjomeh.com/api/v1/docs/authentication.md))
- Scope: `read` for GET, `write` for everything else
- Spends Fara: no. Uploading is free. Fara is held only when the job is created, exactly as for a direct upload.
- Largest file: 1 GB. The length limit of the job (4 hours for a recording; the video limit for a video) still applies and is checked when the job is created.
- Chunk size: 8 MB unless you ask for less. Send `chunkSize` in the Start body (262144 to 8388608 bytes, that is 256 KB to 8 MB) for smaller chunks on a slow or unstable line; at 50 KB/s, 1 MB chunks take about 20 seconds each. The Start answer's `chunkSize` is the one to use. Every chunk except the last is exactly `chunkSize` bytes.
- Life: an upload not used within 24 hours (`expiresAt`) is deleted with its chunks.
- One upload makes one job.
- Open uploads per account: at most 10 at a time.
- Rate limits: Start counts as one upload (300 uploads per hour per account). Chunk PUTs count only toward the per-key limit (120 requests per 60 s). The job create made from an upload does not count again.
- Webhooks: none for uploads. The job's own events work as usual.
- Any account can use chunked uploads.

## Steps

### 1. Start the upload

```http
POST /api/v1/uploads HTTP/1.1
Authorization: Bearer fara_sk_...
Content-Type: application/json
Idempotency-Key: 0f6b1e0e-2a8c-4c1f-9d7b-5e3a2c1b0a99

{
  "purpose": "meeting",
  "filename": "weekly-sync.m4a",
  "contentType": "audio/mp4",
  "size": 312475648,
  "sha256": "9f2c5b1e8a7d6c4b3a291807f6e5d4c3b2a19087f6e5d4c3b2a19087f6e5d4c3"
}
```

Response `201 Created` (with `Location: /api/v1/uploads/upl_66f5b7e1c3a2d4f6e8b01a2c`):

```json
{
  "uploadId": "upl_66f5b7e1c3a2d4f6e8b01a2c",
  "purpose": "meeting",
  "filename": "weekly-sync.m4a",
  "size": 312475648,
  "chunkSize": 8388608,
  "totalChunks": 38,
  "received": [],
  "status": "open",
  "jobId": null,
  "createdAt": "2026-09-26T10:00:00.000Z",
  "expiresAt": "2026-09-27T10:00:00.000Z"
}
```

```bash
curl -sS -X POST "https://faraatarjomeh.com/api/v1/uploads" \
  -H "Authorization: Bearer $FARA_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{"purpose":"meeting","filename":"weekly-sync.m4a","contentType":"audio/mp4","size":312475648}'
```

| Field | Type | Required | Notes |
|---|---|---|---|
| `purpose` | string | yes | `meeting` (for `POST /api/v1/meetings/jobs`), `transcription` (for `POST /api/v1/transcription/jobs`) or `video` (for `POST /api/v1/video/jobs` and `POST /api/v1/video/jobs/estimate`). An upload makes only a job of its purpose. |
| `size` | integer | yes | The whole file in bytes, at most 1 GB (`FILE_TOO_LARGE` otherwise, with `maxBytes`). |
| `filename` | string | no | Kept as the job's file name. Default `audio`. For a video, the name without its extension becomes the job's title. |
| `contentType` | string | no | An `audio/...` or `video/...` type. The content itself is checked when the job is created. |
| `sha256` | string | no | SHA-256 of the whole file, 64 hex characters. When given, the joined file is checked against it when the job is created. |

When we are short of room for a very large file, Start answers `503 SERVICE_UNAVAILABLE` with `Retry-After`. Nothing was created; send it again later.

### 2. Send the chunks

```http
PUT /api/v1/uploads/upl_66f5b7e1c3a2d4f6e8b01a2c/chunks/0 HTTP/1.1
Authorization: Bearer fara_sk_...
Content-Type: application/octet-stream
Content-Length: 8388608
Content-Digest: sha-256=:X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=:

<bytes 0 to 8388607 of the file>
```

Response `200 OK`: the upload, with the new index in `received`.

```bash
# chunk 3 of the file (8 MB chunks)
dd if=weekly-sync.m4a of=chunk.bin bs=8388608 skip=3 count=1 status=none
curl -sS -X PUT "https://faraatarjomeh.com/api/v1/uploads/upl_66f5b7e1c3a2d4f6e8b01a2c/chunks/3" \
  -H "Authorization: Bearer $FARA_API_KEY" \
  -H "Content-Type: application/octet-stream" \
  -H "Content-Digest: sha-256=:$(openssl dgst -sha256 -binary chunk.bin | base64):" \
  --data-binary @chunk.bin
```

- Index `i` holds bytes `i × chunkSize` up to `(i + 1) × chunkSize - 1`. Indexes run from 0 to `totalChunks - 1`.
- Every chunk is exactly `chunkSize` bytes, except the last, which is the rest of the file. A wrong length or index answers `400 BAD_CHUNK` (with `expectedBytes`).
- Chunks can arrive in any order, and in parallel (keep it to a few at a time).
- Sending the same index again replaces it. A retry after a timeout is always safe and needs no `Idempotency-Key`.
- `Content-Digest` ([RFC 9530](https://www.rfc-editor.org/rfc/rfc9530), `sha-256` or `sha-512`) is optional. When sent, a chunk that does not match is not stored: `422 CHUNK_DIGEST_MISMATCH`. Send the same chunk again.
- Do not send chunks after you create the job.

### 3. Resume after a lost connection

```http
GET /api/v1/uploads/upl_66f5b7e1c3a2d4f6e8b01a2c HTTP/1.1
Authorization: Bearer fara_sk_...
```

Returns the same object. Send only the indexes missing from `received`. A used upload shows `"status": "used"` and the `jobId` it made.

### 4. Create the job

Same endpoint, fields, hold and answer as a direct upload; the file part is replaced by `uploadId` in a JSON body.

```http
POST /api/v1/meetings/jobs HTTP/1.1
Authorization: Bearer fara_sk_...
Content-Type: application/json
Idempotency-Key: 8c0f5e2a-1d7b-4b8e-9f3a-6e2d4c1b0a97

{ "uploadId": "upl_66f5b7e1c3a2d4f6e8b01a2c", "language": "auto" }
```

```http
POST /api/v1/transcription/jobs HTTP/1.1
Authorization: Bearer fara_sk_...
Content-Type: application/json
Idempotency-Key: 5b1d7e2f-3c4a-4e8b-9a6d-0f1e2d3c4b5a

{ "uploadId": "upl_7a1c2e3f4b5d6a7c8e9f0a1b", "sourceLanguage": "auto", "targetLanguage": "fa" }
```

```http
POST /api/v1/video/jobs HTTP/1.1
Authorization: Bearer fara_sk_...
Content-Type: application/json
Idempotency-Key: 2e7a9c1d-4b3f-4a6e-8d2c-1f0e9b8a7c65

{ "uploadId": "upl_8b2d3f4a5c6e7b8d9f0a1b2c", "outputMode": "farsi_subs" }
```

Response `201 Created`, as in [Meeting minutes](https://faraatarjomeh.com/api/v1/docs/guides/meeting-minutes.md), [Transcription](https://faraatarjomeh.com/api/v1/docs/guides/transcription.md) and [Video](https://faraatarjomeh.com/api/v1/docs/guides/video.md). A meeting job answers:

```json
{
  "jobId": "66f5e0c1d2e3f4a5b6c7d8e9",
  "cost": { "faraCharged": 96, "minutesBilled": 187 },
  "durationSeconds": 11203.4
}
```

At this point we check that every chunk is there, the `sha256` (if you sent one), that the file is audio or video, and its length; then Fara is held. A video upload must be an MP4, MOV, MKV, WebM or AVI file with a sound track, else `400 UNSUPPORTED_VIDEO_FILE`. To price a video upload first, send its `uploadId` to `POST /api/v1/video/jobs/estimate`; that does not use the upload up.

- A refused create (for example `402 INSUFFICIENT_CREDITS`, a too-long recording, a missing chunk) leaves the upload open. Fix the cause and create the job again with the same `uploadId`, until `expiresAt`.
- One upload makes one job. A second create with the same `uploadId` and a different (or no) `Idempotency-Key` answers `409 UPLOAD_ALREADY_USED` with the `jobId`. With the first request's `Idempotency-Key` you get the first answer again.
- Send the recording one way only: a file, `audioUrl` (any account), or `uploadId`. Both at once answer `400 BAD_REQUEST`. For a video: `url` (a YouTube link) or `uploadId`, not both.
- Large meeting and transcription recordings are turned into compact speech audio before they are transcribed. The job's result is the same. A video upload is used as it is.

### Cancel

```http
DELETE /api/v1/uploads/upl_66f5b7e1c3a2d4f6e8b01a2c HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `204 No Content`. The chunks are deleted. Cancelling again answers `204` too. An upload that already made a job answers `409 UPLOAD_ALREADY_USED`.

## Errors and recovery

All errors are `application/problem+json`. Branch on `code`. See [Errors](https://faraatarjomeh.com/api/v1/docs/errors.md).

| HTTP | `code` | When | Retry? | What the client should do |
|---|---|---|---|---|
| 400 | [`BAD_REQUEST`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-bad-request) | Bad `purpose`, `size` or `sha256`; `uploadId` sent to another purpose's endpoint; a file (or a video `url`) and `uploadId` sent together. | no | Fix the request. |
| 400 | [`FILE_TOO_LARGE`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-file-too-large) | `size` over 1 GB. | no | The file cannot be sent. |
| 400 | [`BAD_CHUNK`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-bad-chunk) | Index out of range, or wrong length for that index. | no | Cut the chunk again from `chunkSize`. |
| 404 | [`UPLOAD_NOT_FOUND`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-upload-not-found) | No such upload on this account, or it was cancelled. | no | Start a new upload. |
| 409 | [`UPLOAD_INCOMPLETE`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-upload-incomplete) | Job created before every chunk arrived. `missing` lists the indexes. | refresh | Send the missing chunks, then create the job again. |
| 409 | [`UPLOAD_ALREADY_USED`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-upload-already-used) | The upload already made a job (`jobId`). | no | Use that job. |
| 409 | [`UPLOAD_LIMIT_REACHED`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-upload-limit-reached) | Too many open uploads on the account. | no | Create a job from one, or cancel one. |
| 409 | [`CONFLICT`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-conflict) | Another request is creating a job from this upload right now. | refresh | GET the upload and decide from `status`. |
| 410 | [`UPLOAD_EXPIRED`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-upload-expired) | Past `expiresAt`; the chunks are gone. | no | Start a new upload. |
| 422 | [`CHUNK_DIGEST_MISMATCH`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-chunk-digest-mismatch) | The chunk does not match `Content-Digest`. | yes | Send the same chunk again. |
| 422 | [`UPLOAD_CHECKSUM_MISMATCH`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-upload-checksum-mismatch) | The joined file does not match `sha256`. Nothing was created or charged. | no | Upload the file again (a new upload). |
| 429 | [`RATE_LIMITED`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-rate-limited) | Too many requests. | yes | Wait `Retry-After` seconds. |
| 503 | [`SERVICE_UNAVAILABLE`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-service-unavailable) | Start: no room for this file right now. | yes | Wait `Retry-After`, send again. |

Every other error of the job create (`INSUFFICIENT_CREDITS`, `AUDIO_SOURCE_TOO_LONG`, `UNSUPPORTED_VIDEO_FILE`, …) is as described in the meeting, transcription and video guides.

## Rules for agents

- Take `chunkSize` from the Start answer. Never assume 8 MB.
- Send `Content-Digest` with every chunk; resend a chunk on `CHUNK_DIGEST_MISMATCH`, a timeout, or a `5xx`.
- After any break, GET the upload and send only the indexes missing from `received`.
- Create the job only when `received` has every index. Send an `Idempotency-Key` with the create.
- Cancel uploads you will not use; they count toward the open-upload limit until they expire.

## Complete script

Both scripts: start → send every chunk with a digest, retrying each → create a meeting job. Set `FARA_API_KEY` and `FARA_BASE_URL`.

```python
# Python 3.9+, pip install requests
import base64, hashlib, os, sys, time, uuid
import requests

BASE = os.environ.get("FARA_BASE_URL", "https://faraatarjomeh.com").rstrip("/")
H = {"Authorization": f"Bearer {os.environ['FARA_API_KEY']}"}
FILE = "weekly-sync.m4a"

def check(r):
    if r.status_code >= 400:
        p = r.json() if "json" in r.headers.get("Content-Type", "") else {}
        raise SystemExit(f"{r.status_code} {p.get('code')}: {p.get('detail')}")
    return r

size = os.path.getsize(FILE)
whole = hashlib.sha256()
with open(FILE, "rb") as f:
    for block in iter(lambda: f.read(1 << 20), b""):
        whole.update(block)

up = check(requests.post(f"{BASE}/api/v1/uploads", headers={**H, "Idempotency-Key": str(uuid.uuid4())},
                         json={"purpose": "meeting", "filename": os.path.basename(FILE),
                               "contentType": "audio/mp4", "size": size, "sha256": whole.hexdigest()},
                         timeout=30)).json()
upload_id, chunk_size = up["uploadId"], up["chunkSize"]

def send(index):
    with open(FILE, "rb") as f:
        f.seek(index * chunk_size)
        data = f.read(chunk_size)
    digest = base64.b64encode(hashlib.sha256(data).digest()).decode()
    for attempt in range(6):
        try:
            r = requests.put(f"{BASE}/api/v1/uploads/{upload_id}/chunks/{index}", data=data, timeout=120,
                             headers={**H, "Content-Type": "application/octet-stream",
                                      "Content-Digest": f"sha-256=:{digest}:"})
        except requests.RequestException:
            time.sleep(2 ** attempt)
            continue
        if r.status_code in (422, 429) or r.status_code >= 500:
            time.sleep(int(r.headers.get("Retry-After", 2 ** attempt)))
            continue
        return check(r)
    sys.exit(f"chunk {index} did not go through")

while True:
    state = check(requests.get(f"{BASE}/api/v1/uploads/{upload_id}", headers=H, timeout=30)).json()
    missing = sorted(set(range(state["totalChunks"])) - set(state["received"]))
    if not missing:
        break
    for index in missing:
        send(index)

job = check(requests.post(f"{BASE}/api/v1/meetings/jobs", headers={**H, "Idempotency-Key": str(uuid.uuid4())},
                          json={"uploadId": upload_id, "language": "auto"}, timeout=300)).json()
print("job:", job["jobId"], "held:", job["cost"]["faraCharged"], "Fara")
```

```js
// Node.js 20+ (ESM: save as chunked-upload.mjs)
import { createHash, randomUUID } from "node:crypto";
import { open, stat } from "node:fs/promises";
import { basename } from "node:path";

const BASE = (process.env.FARA_BASE_URL ?? "https://faraatarjomeh.com").replace(/\/+$/, "");
const H = { Authorization: `Bearer ${process.env.FARA_API_KEY}` };
const FILE = "weekly-sync.m4a";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function call(path, init = {}) {
  const res = await fetch(`${BASE}${path}`, { ...init, headers: { ...H, ...init.headers } });
  if (!res.ok) {
    const p = await res.json().catch(() => ({}));
    throw Object.assign(new Error(`${res.status} ${p.code}: ${p.detail}`), {
      status: res.status,
      retryAfter: Number(res.headers.get("retry-after")) || 0,
    });
  }
  return res;
}

const { size } = await stat(FILE);
const fh = await open(FILE, "r");
const whole = createHash("sha256");
for await (const block of fh.createReadStream({ autoClose: false, start: 0 })) whole.update(block);

const up = await (await call("/api/v1/uploads", {
  method: "POST",
  headers: { "Content-Type": "application/json", "Idempotency-Key": randomUUID() },
  body: JSON.stringify({ purpose: "meeting", filename: basename(FILE), contentType: "audio/mp4", size, sha256: whole.digest("hex") }),
})).json();

async function send(index) {
  const length = Math.min(up.chunkSize, size - index * up.chunkSize);
  const data = Buffer.alloc(length);
  await fh.read(data, 0, length, index * up.chunkSize);
  const digest = createHash("sha256").update(data).digest("base64");
  for (let attempt = 0; attempt < 6; attempt++) {
    try {
      return await call(`/api/v1/uploads/${up.uploadId}/chunks/${index}`, {
        method: "PUT",
        headers: { "Content-Type": "application/octet-stream", "Content-Digest": `sha-256=:${digest}:` },
        body: data,
      });
    } catch (e) {
      if (e.status && e.status < 500 && e.status !== 422 && e.status !== 429) throw e;
      await sleep((e.retryAfter || 2 ** attempt) * 1000);
    }
  }
  throw new Error(`chunk ${index} did not go through`);
}

for (;;) {
  const state = await (await call(`/api/v1/uploads/${up.uploadId}`)).json();
  const have = new Set(state.received);
  const missing = [...Array(state.totalChunks).keys()].filter((i) => !have.has(i));
  if (!missing.length) break;
  for (const index of missing) await send(index);
}
await fh.close();

const job = await (await call("/api/v1/meetings/jobs", {
  method: "POST",
  headers: { "Content-Type": "application/json", "Idempotency-Key": randomUUID() },
  body: JSON.stringify({ uploadId: up.uploadId, language: "auto" }),
})).json();
console.log("job:", job.jobId, "held:", job.cost.faraCharged, "Fara");
```
