SDKs
Two SDKs wrap the API: @formatjet/sdk for TypeScript and JavaScript, and formatjet for Python. Each is generated from our OpenAPI document, so it reaches every endpoint, with a small client on top for the common work. Both are open source under the MIT licence.
| TypeScript and JavaScript | Python | |
|---|---|---|
| Package | @formatjet/sdk on npm |
formatjet on PyPI |
| Install | npm install @formatjet/sdk |
pip install formatjet |
| Runs on | Node.js 20 or later, or Bun | Python 3.11 or later |
Both read your key from FORMATJET_API_KEY, or take it when you make the client: new FormatJet({ apiKey }), FormatJet(api_key=…).
Convert a file
Section titled “Convert a file”convert() sends a file in one request, up to 25 MB, and returns the converted files, as in the quickstart. Name the conversion by its slug from GET /v1/operations, or only the format to make (to: 'pdf'), and pass its options:
const result = await formatjet.convert( { data: await readFile('scan.pdf'), filename: 'scan.pdf' }, { conversion: 'pdf-to-jpg', options: { dpi: 300 } },);for (const file of result.files) await writeFile(file.filename ?? 'page.jpg', file.data);result = formatjet.convert("scan.pdf", conversion="pdf-to-jpg", options={"dpi": 300})for file in result.files: file.save()A PDF’s pages as images, Split PDF and a workbook’s sheets as CSV make several files; other conversions make one, which is also result.file. In TypeScript a file is a Uint8Array (Node’s Buffer is one), an ArrayBuffer, a Blob or a File, or { data, filename } to name the output after it. In Python it’s a path, bytes, a binary file object, or (filename, data).
Larger files and jobs
Section titled “Larger files and jobs”uploadAndConvert() (upload_and_convert() in Python) uploads the file straight to storage, so it takes files up to your plan’s limit. Then it makes a job, waits for it and downloads what it made:
import { readFile, writeFile } from 'node:fs/promises';import { FormatJet, FormatJetError } from '@formatjet/sdk';
const formatjet = new FormatJet(); // reads FORMATJET_API_KEY
try { // Uploads the file, makes a job, waits for it and downloads the result. const result = await formatjet.uploadAndConvert( { data: await readFile('report.pdf'), filename: 'report.pdf' }, { to: 'md', metadata: { order: '8812' }, onProgress: (job) => console.log(`${job.status} ${job.progress}%`), }, ); console.log(`${result.jobId}: ${result.credits} credits, ${result.engine}`); await writeFile('report.md', result.file.data);} catch (error) { // Branch on the code: https://formatjet.com/docs/errors if (error instanceof FormatJetError) console.error(error.code, error.detail, error.requestId); throw error;}from formatjet import FormatJet, FormatJetError
formatjet = FormatJet() # reads FORMATJET_API_KEY
try: # Uploads the file, makes a job, waits for it and downloads the result. result = formatjet.upload_and_convert( "report.pdf", to="md", metadata={"order": "8812"}, on_progress=lambda job: print(f"{job.status} {job.progress}%"), )except FormatJetError as error: # Branch on the code: https://formatjet.com/docs/errors print(error.code, error.detail, error.request_id) raise
print(f"{result.job_id}: {result.credits} credits, {result.engine}")result.file.save("report.md")Files to join, for Merge PDF or Image to PDF, go as a list in their order. For more control, jobs makes, reads, lists, waits for, cancels and deletes jobs, and download() fetches an output:
const job = await formatjet.jobs.create({ input: { url: 'https://example.com/report.docx' }, steps: [{ op: 'convert', conversion: 'word-to-pdf' }],});const done = await formatjet.jobs.wait(job.id);const pdf = await formatjet.download(done.outputs[0]!);job = formatjet.jobs.create({ "input": {"url": "https://example.com/report.docx"}, "steps": [{"op": "convert", "conversion": "word-to-pdf"}],})done = formatjet.jobs.wait(job.id)formatjet.download(done.outputs[0]).save()jobs.wait() returns the job once it has ended, whatever the outcome; the job’s error says why one failed. One request or a job explains how jobs run.
Steps and recipes
Section titled “Steps and recipes”uploadAndConvert() (upload_and_convert() in Python) takes steps instead of one conversion: up to 5 of them, each converting what the step before made. Both it and convert() take recipe, a saved recipe’s ID, and recipes saves, lists, changes and deletes them:
#!/usr/bin/env bash# Needs curl and jq.set -euo pipefailAPI=https://api.formatjet.com/v1AUTH="Authorization: Bearer $FORMATJET_API_KEY"
# 1. Save a recipe: print a web page to PDF, then read that PDF as Markdown.recipe=$(curl -sS --fail-with-body "$API/recipes" -H "$AUTH" -H "Content-Type: application/json" \ -d '{"name": "Web page to text", "output_name": "{name}-text", "steps": [{"op": "convert", "conversion": "html-to-pdf"}, {"op": "convert", "to": "md"}]}')recipe_id=$(jq -r .id <<< "$recipe")
# 2. Run it on a file: here sent as base64, as small files may be.job=$(jq -n --arg recipe "$recipe_id" --rawfile page report.html \ '{input: {base64: ($page | @base64), filename: "report.html"}, recipe: $recipe}' | curl -sS --fail-with-body "$API/jobs" -H "$AUTH" -H "Content-Type: application/json" -d @-)id=$(jq -r .id <<< "$job")
# 3. Wait for every step 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 last step's output, named by the recipe: report-text.md.output=$(jq '.outputs[0]' <<< "$job")curl -sS --fail-with-body "$(jq -r .url <<< "$output")" -o "$(jq -r .filename <<< "$output")"
# The recipe stays for later jobs; this removes it.curl -sS --fail-with-body -X DELETE "$API/recipes/$recipe_id" -H "$AUTH"import { readFile, writeFile } from 'node:fs/promises';import { FormatJet } from '@formatjet/sdk';
const formatjet = new FormatJet(); // reads FORMATJET_API_KEY
// Save a recipe: print a web page to PDF, then read that PDF as Markdown.const recipe = await formatjet.recipes.create({ name: 'Web page to text', steps: [ { op: 'convert', conversion: 'html-to-pdf' }, { op: 'convert', to: 'md' }, ], output_name: '{name}-text',});
// Run it on a file, wait for every step and download the last step's output.const result = await formatjet.uploadAndConvert( { data: await readFile('report.html'), filename: 'report.html' }, { recipe: recipe.id },);await writeFile(result.file.filename ?? 'report-text.md', result.file.data);console.log(`${result.jobId}: ${result.credits} credits, ${result.engine}`);
// The recipe stays for later jobs; this removes it.await formatjet.recipes.delete(recipe.id);from formatjet import FormatJet
formatjet = FormatJet() # reads FORMATJET_API_KEY
# Save a recipe: print a web page to PDF, then read that PDF as Markdown.recipe = formatjet.recipes.create( "Web page to text", [ {"op": "convert", "conversion": "html-to-pdf"}, {"op": "convert", "to": "md"}, ], output_name="{name}-text",)
# Run it on a file, wait for every step and download the last step's output.result = formatjet.upload_and_convert("report.html", recipe=recipe.id)result.file.save(result.file.filename or "report-text.md")print(f"{result.job_id}: {result.credits} credits, {result.engine}")
# The recipe stays for later jobs; this removes it.formatjet.recipes.delete(recipe.id)Steps and recipes explains how the steps run and what a recipe keeps.
Errors and retries
Section titled “Errors and retries”Failed calls, and conversions that fail, throw a FormatJetError with the error’s code, its detail and the request ID. Two codes come from the SDKs themselves: timeout when a wait ran out (the job carries on) and canceled for a job canceled while the SDK waited for it.
The clients retry 429 answers, 5xx answers and network errors twice, waiting as long as Retry-After says; an answer that asks for longer than a minute is raised at once. Every POST carries an Idempotency-Key, the same on each retry, so a retry never makes a second job. Limits and retries has the numbers. Upload and download URLs never get your key: they are signed for the one file.
Webhooks
Section titled “Webhooks”Check each delivery’s signature with the raw body, before parsing it. parse returns the event, or throws WebhookSignatureError:
const event = await formatjet.webhooks.parse({ body: await request.text(), header: request.headers.get('FormatJet-Signature'), secret: process.env.FORMATJET_WEBHOOK_SECRET!,});from formatjet import parse_webhook
event = parse_webhook(body, headers.get("FormatJet-Signature"), secret)Webhooks explains the events and how to answer them.
Every endpoint
Section titled “Every endpoint”The generated part of each SDK reaches the whole API, typed:
const { data: account } = await formatjet.api.GET('/v1/account');from formatjet.openapi.api.account import get_account
account = get_account.sync(client=formatjet.api)The reference lists every endpoint. In Python, its operation ID names the module, in lower case with underscores: getAccount is get_account, in the module of its group.