One request or a job
There are two ways to convert a file. Both run the same conversions on the same engines and cost the same.
POST /v1/convert |
Jobs | |
|---|---|---|
| Files | Up to 25 MB in all | Up to your plan’s limit; at a URL; up to 20 joined into one |
| Answer | The converted file | The job, while it runs |
| Waiting | The request waits, up to 30 seconds | Poll, stream events or get a webhook |
| Suits | Small files, scripts, a user waiting | Large files, queues, background work |
In one request
Section titled “In one request”POST /v1/convert takes the file and answers with the converted file, as in the quickstart. Send the file as a file part of multipart/form-data, or as the raw body with its name in filename. Then say what to make:
to=pdf: the format to make. The file’s own format is detected from its bytes.conversion=word-to-pdf: a conversion’s slug fromGET /v1/operations, when you want to be exact.options={"quality":80}: the conversion’s options, as JSON. With a multipart body you can send them in anoptionspart instead, as the SDKs do. A password (Unlock PDF’spassword) goes only there: it’s refused in the URL, which can end up in logs.
The request waits up to 30 seconds, or fewer with wait (in seconds, from 0). If the conversion hasn’t finished by then, the answer is 202 with the job, which carries on: wait for it as below. response=job asks for the job, with a download URL, instead of the file, and response=file for the file whatever your Accept header says; without response, Accept: application/json asks for the job. Conversions that make several files (Split PDF, a PDF’s pages as images) always answer with the job, whose outputs list the files in order.
For a conversion that joins files, such as Merge PDF, send a file part for each, in order.
As a job
Section titled “As a job”A job runs in four steps:
- Send the file: an upload, base64 in the body, or a URL we fetch. Inputs has the details.
- Make the job with
POST /v1/jobs: the input and one step, such as{"op": "convert", "to": "md"}. - Wait for it to end: poll
GET /v1/jobs/{id}, stream its events, or let a webhook tell you. - Download the outputs from their URLs before
expires_at.
This converts our sample PDF (report.pdf) to Markdown. Any conversion works the same way: only the step changes.
#!/usr/bin/env bash# Needs curl and jq.set -euo pipefailAPI=https://api.formatjet.com/v1AUTH="Authorization: Bearer $FORMATJET_API_KEY"
# 1. Make an upload, then PUT the file to its URL with the headers it names.upload=$(curl -sS --fail-with-body "$API/uploads" -H "$AUTH" -H "Content-Type: application/json" \ -d "{\"size\": $(wc -c < report.pdf), \"filename\": \"report.pdf\"}")headers=()while IFS= read -r header; do headers+=(-H "$header"); done \ < <(jq -r '.headers | to_entries[] | "\(.key): \(.value)"' <<< "$upload")curl -sS --fail-with-body -X PUT "$(jq -r .url <<< "$upload")" "${headers[@]}" \ --data-binary @report.pdf
# 2. Make a job from the upload.job=$(curl -sS --fail-with-body "$API/jobs" -H "$AUTH" -H "Content-Type: application/json" \ -d "{\"input\": {\"upload_id\": \"$(jq -r .id <<< "$upload")\"}, \"steps\": [{\"op\": \"convert\", \"to\": \"md\"}]}")id=$(jq -r .id <<< "$job")
# 3. Wait for it to end.status=$(jq -r .status <<< "$job")until [[ $status == completed || $status == failed || $status == canceled ]]; do sleep 1 job=$(curl -sS --fail-with-body "$API/jobs/$id" -H "$AUTH") status=$(jq -r .status <<< "$job")done[[ $status == completed ]] || { jq .error <<< "$job"; exit 1; }
# 4. Download the output: its URL needs no key and works until expires_at.curl -sS --fail-with-body "$(jq -r '.outputs[0].url' <<< "$job")" -o report.mdimport { readFile, writeFile } from 'node:fs/promises';
const API = 'https://api.formatjet.com/v1';const auth = { Authorization: `Bearer ${process.env.FORMATJET_API_KEY}` };
interface Upload { id: string; url: string; headers: Record<string, string>;}
interface Job { id: string; status: string; error: { code: string; detail: string } | null; outputs: { url: string }[];}
async function call<T>(path: string, init: RequestInit = {}): Promise<T> { const response = await fetch(`${API}${path}`, { ...init, headers: { ...auth, 'Content-Type': 'application/json', ...init.headers }, }); if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`); return (await response.json()) as T;}
// 1. Make an upload, then PUT the file to its URL with the headers it names.const file = await readFile('report.pdf');const upload = await call<Upload>('/uploads', { method: 'POST', body: JSON.stringify({ size: file.length, filename: 'report.pdf' }),});const put = await fetch(upload.url, { method: 'PUT', headers: upload.headers, body: file });if (!put.ok) throw new Error(`Upload failed: ${put.status}`);
// 2. Make a job from the upload. The Idempotency-Key makes a retry safe.let job = await call<Job>('/jobs', { method: 'POST', headers: { 'Idempotency-Key': crypto.randomUUID() }, body: JSON.stringify({ input: { upload_id: upload.id }, steps: [{ op: 'convert', to: 'md' }], }),});
// 3. Wait for it to end.while (!['completed', 'failed', 'canceled'].includes(job.status)) { await new Promise((resolve) => setTimeout(resolve, 1000)); job = await call<Job>(`/jobs/${job.id}`);}if (job.status !== 'completed') throw new Error(`Job ${job.status}: ${job.error?.detail}`);
// 4. Download the output: its URL needs no key and works until `expires_at`.const output = await fetch(job.outputs[0]!.url);await writeFile('report.md', new Uint8Array(await output.arrayBuffer()));import osimport timeimport uuid
import requests
API = "https://api.formatjet.com/v1"session = requests.Session()session.headers["Authorization"] = f"Bearer {os.environ['FORMATJET_API_KEY']}"
def call(method, path, **kwargs): response = session.request(method, f"{API}{path}", timeout=60, **kwargs) response.raise_for_status() return response.json()
# 1. Make an upload, then PUT the file to its URL with the headers it names.with open("report.pdf", "rb") as file: data = file.read()upload = call("POST", "/uploads", json={"size": len(data), "filename": "report.pdf"})requests.put(upload["url"], headers=upload["headers"], data=data, timeout=60).raise_for_status()
# 2. Make a job from the upload. The Idempotency-Key makes a retry safe.job = call( "POST", "/jobs", headers={"Idempotency-Key": str(uuid.uuid4())}, json={"input": {"upload_id": upload["id"]}, "steps": [{"op": "convert", "to": "md"}]},)
# 3. Wait for it to end.while job["status"] not in ("completed", "failed", "canceled"): time.sleep(1) job = call("GET", f"/jobs/{job['id']}")if job["status"] != "completed": raise SystemExit(f"Job {job['status']}: {job['error']}")
# 4. Download the output: its URL needs no key and works until expires_at.output = requests.get(job["outputs"][0]["url"], timeout=60)output.raise_for_status()with open("report.md", "wb") as file: file.write(output.content)A job’s life
Section titled “A job’s life”A job’s status moves through these values:
| Status | Means |
|---|---|
awaiting_upload |
Waiting for its file: an upload not yet checked, or a URL being fetched |
queued |
The file passed its checks; the job waits for an engine |
processing |
Converting; progress counts up to 100 |
completed |
Done: outputs have download URLs and credits says what it cost |
failed |
It didn’t work: error has a code and a reason. Nothing is charged |
canceled |
Stopped with POST /v1/jobs/{id}/cancel or DELETE /v1/jobs/{id}. Nothing is charged |
Credits are held when the job starts (estimate.credits) and charged only if it completes. A URL input that can’t be fetched within 30 minutes fails the job.
Waiting
Section titled “Waiting”- Polling.
GET /v1/jobs/{id}once a second or two is fine for most jobs; it counts against your rate limit like any request. Withwait, in seconds up to 30, a job still running is answered as soon as it ends, or when the time is up: a loop of these needs no pause of its own. - Events.
GET /v1/jobs/{id}/eventsis a server-sent event stream: the job asjob.updatedeach time it changes, thenjob.completed,job.failedorjob.canceled, after which the stream ends. Reconnect withLast-Event-IDto skip what you’ve seen. - Webhooks. Your endpoint gets a signed request when the job ends. Best for background work: nothing to poll. See webhooks.
Downloads and deletion
Section titled “Downloads and deletion”Each output’s url works without your key until its expires_at, like any presigned URL: hand it to a browser or a storage service as it is. A client that adds your key to every request can ask GET /v1/jobs/{id}/outputs/0 instead (the first output; 1 for the second): it answers with a redirect to that URL, and HTTP clients leave the key off when a redirect leads to another host. Outputs are deleted 24 hours after the job completes (1 hour for test keys); set output.ttl on the job, in seconds, to keep them for less. Inputs are deleted as soon as the job ends.
To delete everything at once, DELETE /v1/jobs/{id} answers with a signed receipt saying which files were deleted and when.