# Quickstart: translate your first PDF

> Translate one English PDF into Persian from your own server. The sequence is: `GET /api/v1/account` (balance) → `POST /api/v1/translate/analyze` (price, free) → `POST /api/v1/translate/start/{jobId}` (spends Fara) → `GET /api/v1/translate/status/{jobId}` until done (or a webhook) → `GET /api/v1/translate/download/{jobId}/{type}`.

## At a glance

- Base URL: `https://faraatarjomeh.com`. All paths start with `/api/v1`.
- Auth: `Authorization: Bearer $FARA_API_KEY` on every request — [Authentication](https://faraatarjomeh.com/api/v1/docs/authentication.md).
- Scopes: `read` for GET, `write` for POST and DELETE. This quickstart needs both.
- Spends Fara: only `POST /api/v1/translate/start/{jobId}`. Analysis, status and downloads are free.
- Async: yes. Start returns `202` at once; the translation runs in the background.
- Terminal statuses: `completed`, `completed_partial`, `failed`, `cancelled`.
- Webhook events: `translation.analyzed`, `translation.images_waiting`, `translation.completed`, `translation.completed_partial`, `translation.failed`, `translation.cancelled` — [Webhooks](https://faraatarjomeh.com/api/v1/docs/webhooks.md).
- Full detail for every step: [PDF translation guide](https://faraatarjomeh.com/api/v1/docs/guides/pdf-translation.md).

## Step 1: Create an API key

1. Sign in at https://faraatarjomeh.com.
2. Open **Profile → API access** and create a key with the `read` and `write` scopes.
3. Copy the key. It starts with `fara_sk_` and is shown only once.

## Step 2: Put the key in an environment variable

```bash
export FARA_API_KEY="fara_sk_..."
```

Use the key only from a server or a local script. Anyone who has it can spend your Fara.

## Step 3: Check your balance

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

Response `200 OK`:

```json
{
  "id": "66f1c0a2b4e5d6f7a8b9c0d1",
  "email": "owner@example.com",
  "emailVerified": true,
  "credits": {
    "currency": "FARA",
    "faraPerUsd": 100,
    "balance": 460,
    "reserved": 0,
    "chargebackLiability": 0,
    "lifetimeUsage": 1210,
    "lastTransactionAt": "2026-09-25T10:12:03.120Z"
  },
  "auth": { "type": "api_key", "keyId": "66f1c0a2b4e5d6f7a8b9c0ff", "scopes": ["read", "write"] }
}
```

`credits.balance` is what you can spend now. Buying Fara happens on the website only.

```bash
curl -s "https://faraatarjomeh.com/api/v1/account" -H "Authorization: Bearer $FARA_API_KEY"
```

## Step 4: Analyze the PDF to get the price

Analysis reads the PDF, counts pages and words, and returns the price. It is free. The file part must be sent with `Content-Type: application/pdf`, and the file must be 100 MB or smaller. When Word and EPUB input is on for the site, a `.docx` or EPUB file is accepted too; it is converted to PDF once and then analysed the same way, and the job shows `sourceFormat`.

Use `POST /api/v1/translate/analyze`. It answers in one response with the job id and the price. Large or image-heavy files can take several minutes, so set your client timeout to 15 minutes. If the connection drops, send the same request again with the same `Idempotency-Key` (see Step 5): the analysis keeps running on the server and you get its answer. The other route, `POST /api/v1/translate/analyze-stream` with a Server-Sent Events progress stream, exists for showing progress to a person; see the [guide](https://faraatarjomeh.com/api/v1/docs/guides/pdf-translation.md#streaming-analysis).

```http
POST /api/v1/translate/analyze HTTP/1.1
Authorization: Bearer fara_sk_...
Idempotency-Key: 0f8c6a52-2d7e-4b8e-9d0a-51e3b6f2c4a1
Content-Type: multipart/form-data; boundary=----fara

------fara
Content-Disposition: form-data; name="file"; filename="book.pdf"
Content-Type: application/pdf

<PDF bytes>
------fara--
```

Response `200 OK`:

```json
{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "filename": "book.pdf",
  "fileSize": 4823311,
  "pageCount": 212,
  "wordCount": 68450,
  "charCount": 402113,
  "totalChunks": 46,
  "paragraphCount": 1420,
  "quality": "medium",
  "workflow": "chunk_4stage",
  "availableWorkflows": ["chunk_4stage"],
  "imageCount": 14,
  "estimatedMinutes": 32,
  "estimatedPrice": 380,
  "timeEstimate": {
    "totalMinutes": 32,
    "minutesPerChunk": 8,
    "minutesPerBatch": 8,
    "chunksPerBatch": 15,
    "estimatedBatches": 4,
    "sampleCount": 0,
    "isDefault": true,
    "source": "fallback",
    "quality": null,
    "lastUpdatedAt": null
  },
  "qualityPreviews": null,
  "qualityEstimates": [
    { "quality": "simple", "estimatedCost": 380, "estimatedCostEconomy": 380, "estimatedMinutes": 32 },
    { "quality": "medium", "estimatedCost": 380, "estimatedCostEconomy": 380, "estimatedMinutes": 32 },
    { "quality": "highest", "estimatedCost": 380, "estimatedCostEconomy": 380, "estimatedMinutes": 32 }
  ],
  "status": "analyzed"
}
```

The price is in `qualityEstimates`: `estimatedCost`, in Fara. Every translation runs fast, so `estimatedCostEconomy` is the same number. `estimatedMinutes` is the time estimate for fast delivery. It is worked out from the real times of recent fast chunks (`source: "measured_median"`); `source: "fallback"` means there were too few of them yet, so the estimate uses a fixed time per chunk. A later analysis may show a different number.

```bash
curl -s --max-time 900 -X POST "https://faraatarjomeh.com/api/v1/translate/analyze" \
  -H "Authorization: Bearer $FARA_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -F "file=@book.pdf;type=application/pdf"
```

## Step 5: Start the translation

There is one delivery mode: every translation starts right away and runs fast. Send `"executionMode": "realtime"`, or leave it out. The value `economy_batch` is still accepted and runs as `realtime`. Any other value answers `400 INVALID_EXECUTION_MODE` and starts nothing.

`quality` is still accepted so old clients keep working, but it no longer changes the result. The translation keeps the tone of the source text.

**Why the `Idempotency-Key`:** if the request times out or the connection drops, send it again with the **same** key. You get the first answer back (header `Idempotent-Replayed: true`); the job is never started or charged twice. Error answers `4xx` and `503` are not stored, so after fixing the cause (for example a top-up) the same key works again. Use a new key for each new action.

```http
POST /api/v1/translate/start/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70 HTTP/1.1
Authorization: Bearer fara_sk_...
Idempotency-Key: 7d4e1f0a-93c2-4b5e-8a61-2f0c9e7b3d58
Content-Type: application/json

{"executionMode": "realtime"}
```

Response `202 Accepted`:

```json
{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "quality": "medium",
  "workflow": "chunk_4stage",
  "executionMode": "realtime",
  "availableWorkflows": ["chunk_4stage"],
  "message": "Translation started",
  "totalChunks": 46,
  "status": "pending"
}
```

The balance is checked now (`402 INSUFFICIENT_CREDITS` if too low). Fara is held when the job begins running and the actual cost is charged when it finishes — see [Billing](https://faraatarjomeh.com/api/v1/docs/billing.md).

```bash
JOB_ID="3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70"
START_KEY=$(uuidgen)   # keep it; reuse it if you must resend this request
curl -s -X POST "https://faraatarjomeh.com/api/v1/translate/start/$JOB_ID" \
  -H "Authorization: Bearer $FARA_API_KEY" \
  -H "Idempotency-Key: $START_KEY" \
  -H "Content-Type: application/json" \
  -d '{"executionMode":"realtime"}'
```

## Step 6: Wait until it is done

Either:

- **Webhook (best):** register an https endpoint once with `POST /api/v1/webhook-endpoints` and wait for `translation.completed`, `translation.completed_partial`, `translation.failed` or `translation.cancelled` — [Webhooks](https://faraatarjomeh.com/api/v1/docs/webhooks.md).
- **Polling:** call `GET /api/v1/translate/status/{jobId}`. Poll every 30 seconds. Jobs started before economy delivery was removed may still show `batch_submitted`, `batch_waiting`, `batch_results_received` or `validating`; for those, poll every 10 minutes. If the status is `images_waiting`, the job waits for your choice on the pictures: send it with `POST /api/v1/jobs/{jobId}/images` (see the guide), or wait.

```http
GET /api/v1/translate/status/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70 HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `200 OK` (short form; the full field list is in the [guide](https://faraatarjomeh.com/api/v1/docs/guides/pdf-translation.md#poll-the-status)):

```json
{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "status": "completed",
  "filename": "book.pdf",
  "executionMode": "realtime",
  "estimatedPrice": 380,
  "estimatedPriceEconomy": null,
  "totalChunks": 46,
  "completedChunks": 46,
  "progress": 100,
  "createdAt": "2026-09-25T10:12:03.000Z",
  "completedAt": "2026-09-25T21:40:11.000Z",
  "customerErrorCode": null,
  "outputs": { "docx": "66f2a1c3d4e5f60718293a4b", "pdf": "66f2a1c3d4e5f60718293a4c" }
}
```

The job is done when `status` is `completed` or `completed_partial` (finished, but more than a quarter of the text stayed in English). `failed` has a reason in `customerErrorCode`. Treat any other status as still running.

```bash
curl -s "https://faraatarjomeh.com/api/v1/translate/status/$JOB_ID" -H "Authorization: Bearer $FARA_API_KEY"
```

## Step 7: Download the PDF and DOCX

`GET /api/v1/translate/download/{jobId}/{type}` with `type` = `pdf` (`application/pdf`) or `docx` (`application/vnd.openxmlformats-officedocument.wordprocessingml.document`). Download only the types whose `outputs` value is not `null`. Downloads are free and can be repeated.

```http
GET /api/v1/translate/download/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70/pdf HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `200 OK` with the file as the body, `Content-Type: application/pdf` and `Content-Disposition: attachment` with a suggested (Persian) file name.

```bash
curl -sf -o book-fa.pdf "https://faraatarjomeh.com/api/v1/translate/download/$JOB_ID/pdf" \
  -H "Authorization: Bearer $FARA_API_KEY"
```

## State machine

| status | terminal? | meaning | next action for the client |
|---|---|---|---|
| `analyzed` | no | priced, not started, nothing held | start it, or discard it with `DELETE /api/v1/translate/analyze/{jobId}` |
| `pending` | no | queued | wait |
| `processing`, `translating` | no | running | wait (poll every 30 s) |
| `batch_submitted`, `batch_waiting`, `batch_results_received`, `validating` | no | older economy job (started before economy delivery was removed) waiting for its turn or being checked | wait (poll every 10 min) |
| `completed` | yes | done | download |
| `completed_partial` | yes | done, more than a quarter of the text stayed in English | download; see [fixing a finished job](https://faraatarjomeh.com/api/v1/docs/guides/pdf-translation.md#fix-a-finished-job) |
| `failed` | yes | stopped; hold released | read `customerErrorCode`; see the [guide](https://faraatarjomeh.com/api/v1/docs/guides/pdf-translation.md#state-machine) |
| `cancelled` | yes | cancelled; hold released | nothing |
| anything else | no | still running | wait |

## Errors and recovery

| HTTP | code | when | retry? | what the client should do |
|---|---|---|---|---|
| 400 | `BAD_REQUEST` | not a PDF, over 100 MB, no readable text, or the job is not `analyzed` at start | no | fix the input; read `detail` for the log only |
| 415 | `UNSUPPORTED_FILE_TYPE` | Word/EPUB input is on, and the file is neither a PDF, a `.docx` nor an EPUB | no | send a PDF, a `.docx` or an EPUB; nothing was charged |
| 422 | `DOCUMENT_PROTECTED`, `INVALID_DOCUMENT`, `DOCUMENT_CONVERSION_INCOMPLETE`, `DOCUMENT_CONVERSION_FAILED` | a Word or EPUB file that is locked, cannot be opened, or cannot be prepared in full | no | save the file as a PDF and send the PDF; nothing was charged |
| 400 | `INVALID_EXECUTION_MODE` | `executionMode` is not `economy_batch` or `realtime` | no | send one of the two values, same key |
| 401 | `INVALID_API_KEY` | wrong or revoked key | no | check `FARA_API_KEY` |
| 402 | `INSUFFICIENT_CREDITS` | balance below the price (body has `balance`, `estimatedCost`) | no | tell the user to top up at https://faraatarjomeh.com; then send the start again (the same `Idempotency-Key` is fine: a 402 is not stored) |
| 403 | `INSUFFICIENT_SCOPE` | key lacks `read` or `write` | no | use a key with both scopes |
| 409 | `IDEMPOTENCY_KEY_IN_USE` | the first request with this key is still running | yes | wait `Retry-After` seconds, send again with the same key |
| 429 | `RATE_LIMITED` | too many requests | yes | wait `Retry-After` seconds, same key |
| 503 | `EXTRACTION_CAPACITY_EXCEEDED`, `SERVICE_UNAVAILABLE` | busy | yes | wait `Retry-After` (or 30 s), send again with the same key |
| 500, 504 | `INTERNAL_ERROR`, `EXTRACTION_TIMEOUT` | failed on our side; this answer is stored under the key | once | check whether the job exists (`GET /api/v1/translate/resumable`, or the job status), then send again with a **new** key |

Full list: [PDF translation guide](https://faraatarjomeh.com/api/v1/docs/guides/pdf-translation.md#errors-and-recovery) and [Errors](https://faraatarjomeh.com/api/v1/docs/errors.md).

## Rules for agents

- Get the price (Step 4) before starting, and do not start if it is above what the user approved or above `credits.balance`.
- Send an `Idempotency-Key` on every POST that spends Fara and reuse the same key when you retry that POST.
- Poll no faster than every 30 s (every 10 min for the older economy waiting statuses). Prefer webhooks.
- Branch on `code` in errors, never on the `detail` text.
- Treat unknown `status` values as still running.
- Do not create a second job to retry a job that is still running.

## Complete script

Both scripts do Steps 3–7: check the balance, analyze, stop if the price is above your limit or your balance, start, poll, and download. They retry network errors, `409 IDEMPOTENCY_KEY_IN_USE`, `429` and `503` with the same `Idempotency-Key`.

Python 3.9+ (`pip install requests`). Run: `python fara_translate.py book.pdf 500`

```python
# fara_translate.py
import os
import sys
import time
import uuid

import requests

BASE_URL = "https://faraatarjomeh.com"
API_KEY = os.environ["FARA_API_KEY"]
TERMINAL = {"completed", "completed_partial", "failed", "cancelled"}


def api(method, path, idempotency_key=None, json_body=None, files=None, stream=False):
    """Send one request. Retries network errors, 429, 503 and
    409 IDEMPOTENCY_KEY_IN_USE with the SAME Idempotency-Key."""
    headers = {"Authorization": f"Bearer {API_KEY}"}
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    for attempt in range(1, 61):
        if files:
            for part in files.values():
                part[1].seek(0)
        try:
            res = requests.request(method, BASE_URL + path, headers=headers, json=json_body,
                                   files=files, stream=stream, timeout=(10, 900))
        except requests.RequestException:
            time.sleep(min(2 ** attempt, 60))
            continue
        if res.ok:
            return res if stream else res.json()
        try:
            problem = res.json()
        except ValueError:
            problem = {}
        if res.status_code in (429, 503) or problem.get("code") == "IDEMPOTENCY_KEY_IN_USE":
            wait = int(res.headers.get("Retry-After") or min(2 ** attempt, 60))
            time.sleep(max(wait, 10))
            continue
        raise RuntimeError(f"{method} {path} -> {res.status_code} {problem.get('code')}: {problem.get('detail')}")
    raise RuntimeError(f"{method} {path}: gave up after retries")


def main():
    pdf_path = sys.argv[1]
    max_fara = float(sys.argv[2]) if len(sys.argv) > 2 else float("inf")

    balance = api("GET", "/api/v1/account")["credits"]["balance"]
    print(f"Balance: {balance} Fara")

    with open(pdf_path, "rb") as fh:
        files = {"file": (os.path.basename(pdf_path), fh, "application/pdf")}
        analysis = api("POST", "/api/v1/translate/analyze", idempotency_key=str(uuid.uuid4()), files=files)
    job_id = analysis["jobId"]
    price = analysis["estimatedPrice"]
    print(f"Job {job_id}: {analysis['pageCount']} pages, {analysis['wordCount']} words, price {price} Fara")

    if price > max_fara or price > balance:
        api("DELETE", f"/api/v1/translate/analyze/{job_id}")
        sys.exit(f"Not started: price {price} Fara, limit {max_fara}, balance {balance}")

    api("POST", f"/api/v1/translate/start/{job_id}", idempotency_key=str(uuid.uuid4()),
        json_body={"executionMode": "realtime"})

    while True:
        job = api("GET", f"/api/v1/translate/status/{job_id}")
        print(f"{job['status']} {job['progress']}%")
        if job["status"] in TERMINAL:
            break
        time.sleep(30)

    if job["status"] not in ("completed", "completed_partial"):
        sys.exit(f"Job ended as {job['status']} ({job.get('customerErrorCode')})")

    for file_type, value in (job.get("outputs") or {}).items():
        if not value:
            continue
        res = api("GET", f"/api/v1/translate/download/{job_id}/{file_type}", stream=True)
        with open(f"{job_id}.{file_type}", "wb") as out:
            for block in res.iter_content(chunk_size=1 << 16):
                out.write(block)
        print(f"Saved {job_id}.{file_type}")


if __name__ == "__main__":
    main()
```

Node.js 20+ (no packages). Run: `node fara-translate.mjs book.pdf 500`

```js
// fara-translate.mjs
import { openAsBlob } from "node:fs";
import { writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { basename } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";

const BASE_URL = "https://faraatarjomeh.com";
const API_KEY = process.env.FARA_API_KEY;
if (!API_KEY) throw new Error("Set FARA_API_KEY");

const [pdfPath, maxFaraArg] = process.argv.slice(2);
if (!pdfPath) throw new Error("Usage: node fara-translate.mjs book.pdf [maxFara]");
const maxFara = maxFaraArg ? Number(maxFaraArg) : Infinity;
const TERMINAL = new Set(["completed", "completed_partial", "failed", "cancelled"]);

// Retries network errors, 429, 503 and 409 IDEMPOTENCY_KEY_IN_USE with the SAME Idempotency-Key.
async function api(method, path, { json, form, idempotencyKey, raw = false } = {}) {
  const headers = { Authorization: `Bearer ${API_KEY}` };
  if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
  let body = form;
  if (json !== undefined) {
    headers["Content-Type"] = "application/json";
    body = JSON.stringify(json);
  }
  for (let attempt = 1; attempt <= 60; attempt++) {
    let res;
    try {
      res = await fetch(BASE_URL + path, { method, headers, body });
    } catch {
      await sleep(Math.min(2 ** attempt, 60) * 1000);
      continue;
    }
    if (res.ok) return raw ? res : res.json();
    const problem = await res.json().catch(() => ({}));
    if (res.status === 429 || res.status === 503 || problem.code === "IDEMPOTENCY_KEY_IN_USE") {
      const wait = Number(res.headers.get("retry-after")) || Math.min(2 ** attempt, 60);
      await sleep(Math.max(wait, 10) * 1000);
      continue;
    }
    throw new Error(`${method} ${path} -> ${res.status} ${problem.code}: ${problem.detail}`);
  }
  throw new Error(`${method} ${path}: gave up after retries`);
}

const account = await api("GET", "/api/v1/account");
const balance = account.credits.balance;
console.log(`Balance: ${balance} Fara`);

const form = new FormData();
form.append("file", await openAsBlob(pdfPath, { type: "application/pdf" }), basename(pdfPath));
const analysis = await api("POST", "/api/v1/translate/analyze", { form, idempotencyKey: randomUUID() });
const jobId = analysis.jobId;
const price = analysis.estimatedPrice;
console.log(`Job ${jobId}: ${analysis.pageCount} pages, ${analysis.wordCount} words, price ${price} Fara`);

if (price > maxFara || price > balance) {
  await api("DELETE", `/api/v1/translate/analyze/${jobId}`);
  console.error(`Not started: price ${price} Fara, limit ${maxFara}, balance ${balance}`);
  process.exit(1);
}

await api("POST", `/api/v1/translate/start/${jobId}`, {
  json: { executionMode: "realtime" },
  idempotencyKey: randomUUID(),
});

let job;
for (;;) {
  job = await api("GET", `/api/v1/translate/status/${jobId}`);
  console.log(`${job.status} ${job.progress}%`);
  if (TERMINAL.has(job.status)) break;
  await sleep(30 * 1000);
}

if (job.status !== "completed" && job.status !== "completed_partial") {
  console.error(`Job ended as ${job.status} (${job.customerErrorCode})`);
  process.exit(1);
}

for (const [type, value] of Object.entries(job.outputs ?? {})) {
  if (!value) continue;
  const res = await api("GET", `/api/v1/translate/download/${jobId}/${type}`, { raw: true });
  await writeFile(`${jobId}.${type}`, Buffer.from(await res.arrayBuffer()));
  console.log(`Saved ${jobId}.${type}`);
}
```
