Skip to content

Rust SDK

Convert files between 240+ formats from Rust. One call uploads your file, converts it, waits and downloads the result; jobs, webhooks and the format list are there when you need more. Async on tokio, Rust 1.85+.

crates.io ↗GitHub ↗Changelog ↗v0.1.0Rust 1.85+ · asyncMIT

Installing

Install it with your package manager. Rust 1.85+ · async.

$ cargo add runconvert
cargo add tokio --features macros,rt-multi-thread

Initializing

Client::new(api_key: Option<&str>) / Client::builder()…build()

Create one client and reuse it. Without an API key it reads the RUNCONVERT_API_KEY environment variable. Get a key in Dashboard → API Keys, and keep it on your server: never put it in browser or mobile app code. The client is cheap to clone; reuse it.

Example

use runconvert::Client;

let rc = Client::new(None); // reads RUNCONVERT_API_KEY

Parameters

  • .api_key(&str)ClientBuilderYour API key. Defaults to the RUNCONVERT_API_KEY environment variable.
  • .base_url(&str)ClientBuilderDefaults to https://api.runconvert.com/v3.
  • .timeout(Duration)ClientBuilderTime limit per API request. Default 60 s. Uploads and downloads have none.
  • .max_retries(u32)ClientBuilderRetries for network errors, 429 and 5xx. Default 2.
  • .http_client(reqwest::Client)ClientBuilderYour own reqwest client, e.g. for proxies.

Quick start

Convert a file in one call: the SDK uploads it, converts it, waits for the job and saves the result.

Example

Convert a file
use runconvert::{Client, ConvertOptions};

#[tokio::main]
async fn main() -> Result<(), runconvert::Error> {
    let rc = Client::new(None);

    let result = rc.convert("report.docx", ConvertOptions::to("pdf").out_dir("out")).await?;
    println!("{:?}", result.saved); // ["out/report.pdf"]
    Ok(())
}
["out/report.pdf"]

Convert

Convert a file

rc.convert(file_or_url: &str, o: ConvertOptions).await → Result<ConvertResult, Error>

Converts one file in one call: uploads a local file (or imports a URL), converts it, waits for the job and, when an output folder is given, downloads the result. Uses credits.

Example

let r = rc.convert("report.docx", ConvertOptions::to("pdf").out_dir("out")).await?;
println!("{:?}", r.saved);
["out/report.pdf"]

Parameters

  • file_or_url&strA local path or an http(s) URL (imported by RunConvert).Required
  • ConvertOptions::to(&str)The target format, e.g. "pdf" or "mp3".Required
  • .from(&str)The source format. Read from the file name or URL when left out; needed for bytes or streams without a filename.
  • .options(Map<String, Value>)Engine options for the conversion, e.g. audioBitrate or image_quality. List them with Formats → engines for a pair.
  • .out_dir(impl Into<PathBuf>)Save the results in this folder (created if needed). Without it nothing is downloaded; use the result's files.
  • .tag(&str)A label to find the job later, e.g. "invoices".
  • .timeout(Duration)How long to wait for the job before giving up.
  • .on_update(Fn(&Job))Called with the job after every check, e.g. to show progress.

Returns

ConvertResult with job (the finished job), files (each with filename, url and size) and saved (local paths, when out_dir is set).

Jobs

Create a job

rc.create_job(tasks: BTreeMap<String, Value>, tag: Option<&str>).await → Result<Job, Error>

Creates a job from named tasks that run in order: import → convert → export. Tasks refer to each other by name in input. The job comes back with its tasks; an upload task carries the upload_url to send your file to. Build tasks with tasks::import_url, import_upload, convert and export_url.

Example

use runconvert::tasks;
use std::collections::BTreeMap;

let mut t = BTreeMap::new();
t.insert("a".into(), tasks::import_url("https://example.com/cover.pdf"));
t.insert("b".into(), tasks::import_url("https://example.com/body.pdf"));
t.insert("merge".into(), tasks::convert("pdf", "pdf", vec!["a", "b"], None));
t.insert("export".into(), tasks::export_url("merge"));

let job = rc.create_job(t, Some("merge")).await?;

Parameters

  • tasksBTreeMap<String, Value>Named task definitions. Names use letters, digits, - or _ (up to 64 characters).Required
  • tagOption<&str>A label to find the job later, e.g. "invoices".

Returns

The job, with its tasks.

Get a job

rc.get_job(id: &str).await → Result<Job, Error>

Gets one job with its tasks: status, credits used, and the result files of its export tasks.

Example

Get a job
let job = rc.get_job("job_01hx4k9m2p7w").await?;
println!("{}", job.status);
{
  "id": "job_01hx4k9m2p7w",
  "status": "finished",
  "tag": "invoices",
  "credits_used": 2,
  "created_at": "2026-11-16T09:12:04Z",
  "ended_at": "2026-11-16T09:12:09Z",
  "tasks": [
    { "name": "import-1", "operation": "import/direct/upload", "status": "finished" },
    { "name": "convert-1", "operation": "convert", "status": "finished" },
    { "name": "export-1", "operation": "export/url", "status": "finished",
      "result": { "files": [
        { "filename": "report.pdf", "size": 72841, "url": "https://storage.runconvert.com/…/report.pdf" }
      ] } }
  ]
}

Parameters

  • id&strThe job's ID.Required

Returns

The job, with its tasks.

List jobs

rc.list_jobs(p: &ListParams).await → Result<JobPage, Error>

One page of jobs, newest first, with paging details. Filter by status or tag.

Example

Finished jobs
use runconvert::ListParams;

let page = rc.list_jobs(&ListParams {
    status: Some("finished".into()),
    per_page: Some(20),
    ..Default::default()
}).await?;
for job in &page.data {
    println!("{}", job.id);
}
{
  "data": [ { "id": "job_01hx4k9m2p7w", "status": "finished", … } ],
  "meta": { "page": 1, "per_page": 20, "total": 42, "total_pages": 3 }
}

Parameters

  • statusOption<String>Only jobs with this status: waiting, processing, finished, error or canceled.
  • tagOption<String>A label to find the job later, e.g. "invoices".
  • pageOption<u64>Page number, from 1.
  • per_pageOption<u64>Jobs per page (max 100).
  • include_tasksboolInclude each job's tasks.

Returns

JobPage with data, page, total and total_pages.

Every job

rc.all_jobs(p: ListParams).await → Result<Vec<Job>, Error>

Every job, page by page, so you can loop over all of them without handling pages yourself. Collects every page into one Vec.

Example

All jobs with a tag
let jobs = rc.all_jobs(ListParams {
    tag: Some("invoices".into()),
    ..Default::default()
}).await?;
for job in jobs {
    println!("{} {}", job.id, job.status);
}

Parameters

  • pListParamsThe same filters as list_jobs; page is ignored.

Wait for a job

rc.wait(id: &str, timeout: Option<Duration>, on_update: Option<&(dyn Fn(&Job) + Send + Sync)>).await → Result<Job, Error>

Polls a job until it finishes (every 0.7 s, slowing to 3 s). Fails with the task's code and reason if the job fails, and stops after the timeout if you give one.

Example

let done = rc.wait(&job.id, Some(Duration::from_secs(300)), None).await?;
for f in done.exported_files() {
    rc.download(&f, "out").await?;
}

Parameters

  • id&strThe job's ID.Required
  • timeoutOption<Duration>How long to wait; returns Error::WaitTimeout after it.
  • on_updateOption<&dyn Fn(&Job)>Called with the job after every check, e.g. to show progress.

Returns

The finished job.

Cancel a job

rc.cancel_job(id: &str).await → Result<Job, Error>

Cancels a job's pending tasks. Credits for tasks that didn't finish are refunded.

Example

Cancel
rc.cancel_job("job_01hx4k9m2p7w").await?;

Parameters

  • id&strThe job's ID.Required

Returns

The canceled job.

Delete a job

rc.delete_job(id: &str).await → Result<(), Error>

Deletes a job and its files.

Example

Delete
rc.delete_job("job_01hx4k9m2p7w").await?;

Parameters

  • id&strThe job's ID.Required

Result files

job.exported_files() → Vec<ResultFile>

The files produced by a finished job's export tasks: file name, a temporary download URL and size.

Example

List results
for f in job.exported_files() {
    println!("{} {}", f.filename, f.url);
}
[
  { "filename": "report.pdf", "size": 72841, "url": "https://storage.runconvert.com/…/report.pdf" }
]

Files

Upload a file

rc.upload(upload_url: &str, path: impl AsRef<Path>, filename: Option<&str>).await → Result<(), Error>

Sends a file to an import/direct/upload task before its deadline. Use it with a job you created yourself.

Example

Upload
let url = job.task("upload").and_then(|t| t.upload_url.as_deref()).unwrap();
rc.upload(url, "image.png", None).await?;

Parameters

  • upload_url&strThe upload task's upload_url.Required
  • pathimpl AsRef<Path>The local file.Required
  • filenameOption<&str>The file's name when you pass bytes or a stream.

Download a result

rc.download(file: &ResultFile, dir: impl AsRef<Path>).await → Result<PathBuf, Error>

Saves a result file into a folder, keeping its name, and returns the path. Streams, so big files use little memory.

Example

Download
for f in job.exported_files() {
    println!("{}", rc.download(&f, "out").await?.display());
}
out/report.pdf

Parameters

  • file&ResultFileA result file from a job's export task, or its URL.Required
  • dirimpl AsRef<Path>The folder to save into.Required

Returns

The saved file's path.

Formats

List formats

rc.operations(category: Option<&str>).await → Result<Value, Error>

Every input format and what it converts to. Public: no API key needed.

Example

Audio formats
let catalog = rc.operations(Some("audio")).await?;
println!("{}", catalog["formats"].as_array().map_or(0, |a| a.len()));

Parameters

  • categoryOption<&str>Only one category: document, image, video, audio, ebook, archive, font, cad, …

Targets for a format

rc.operations_for_input(input: &str).await → Result<Value, Error>

What one format converts to, with the credit cost of each conversion. Public.

Example

What MP4 converts to
let mp4 = rc.operations_for_input("mp4").await?;
for o in mp4["outputs"].as_array().into_iter().flatten() {
    println!("{} {}", o["format"], o["credits"]);
}
{
  "format": "mp4",
  "category": "video",
  "outputs": [
    { "format": "mp3", "category": "audio", "engine": "ffmpeg", "credits": 1 },
    { "format": "gif", "category": "image", "engine": "ffmpeg", "credits": 4 },
    …
  ]
}

Parameters

  • input&strThe input format, e.g. "mp4".Required

Engines for a pair

rc.operations_for_pair(input: &str, output: &str).await → Result<Value, Error>

The engines for one conversion and the options its convert task accepts, e.g. bitrate or quality. Public.

Example

MP4 → MP3 options
let pair = rc.operations_for_pair("mp4", "mp3").await?;
for opt in pair["engines"][0]["options"].as_array().into_iter().flatten() {
    println!("{}", opt["name"]);
}
{
  "input": "mp4",
  "output": "mp3",
  "engines": [
    { "name": "ffmpeg", "credits": 1,
      "options": [
        { "name": "audioBitrate", "type": "string",
          "description": "Target audio bitrate in kbps.",
          "supported_values": ["32k", "48k", "64k", "80k", …] },
        …
      ] }
  ]
}

Parameters

  • input&strThe input format, e.g. "mp4".Required
  • output&strThe output format, e.g. "mp3".Required

Account

Credits and team

rc.me().await → Result<Value, Error>

The account, team and credit balance behind the API key.

Example

Credits left
let me = rc.me().await?;
println!("{}", me["credits"]["total_remaining"]);
{
  "user": { "email": "[email protected]", "full_name": "Ada Lovelace" },
  "team": { "name": "Acme" },
  "credits": { "mode": "wallet", "total_remaining": 4820 }
}

Webhooks

Verify a signature

webhooks::verify(raw_body: &[u8], signature: Option<&str>, secret: &str) → bool

Checks that a webhook delivery really came from RunConvert: an HMAC-SHA256 of the raw request body with your webhook secret, compared with the X-RunConvert-Signature header in constant time.

Example

Verify
use runconvert::webhooks;

let ok = webhooks::verify(&body, signature, &secret);

Parameters

  • raw_body&[u8]The raw request body, exactly as received (not parsed JSON).Required
  • signatureOption<&str>The X-RunConvert-Signature header.Required
  • secret&strYour webhook's signing secret.Required

Parse an event

webhooks::construct_event(raw_body: &[u8], signature: Option<&str>, secret: &str) → Result<Value, Error>

Verifies the signature and parses the event in one step. Fails if the signature is wrong.

Returns Error::Invalid when the signature doesn't match: answer 400 and ignore the request.

Example

axum
use axum::{body::Bytes, http::{HeaderMap, StatusCode}};
use runconvert::webhooks;

async fn webhook(headers: HeaderMap, body: Bytes) -> StatusCode {
    let sig = headers.get("x-runconvert-signature").and_then(|v| v.to_str().ok());
    let secret = std::env::var("RUNCONVERT_WEBHOOK_SECRET").unwrap();
    match webhooks::construct_event(&body, sig, &secret) {
        Ok(event) => {
            if event["event"] == "job.finished" {
                println!("done {}", event["job"]["id"]);
            }
            StatusCode::OK
        }
        Err(_) => StatusCode::BAD_REQUEST,
    }
}
{
  "event": "job.finished",
  "job": { "id": "job_01hx4k9m2p7w", "status": "finished", … }
}

Parameters

  • raw_body&[u8]The raw request body, exactly as received (not parsed JSON).Required
  • signatureOption<&str>The X-RunConvert-Signature header.Required
  • secret&strYour webhook's signing secret.Required

More

Errors

Every failure is a typed error. The API's code tells you what happened, for example BILLING_INSUFFICIENT_CREDITS, UNAUTHORIZED or INVALID_DATA. Every method returns Result<_, runconvert::Error>; err.code() gives the API code when there is one.

Example

Handle errors
use runconvert::Error;

match rc.convert("report.docx", ConvertOptions::to("pdf").out_dir("out")).await {
    Ok(r) => println!("{:?}", r.saved),
    Err(Error::JobFailed { task, .. }) => println!("conversion failed: {:?}", task.and_then(|t| t.reason)),
    Err(Error::Api { status, code, message }) => println!("{status} {code} {message}"),
    Err(e) => return Err(e),
}
422 BILLING_INSUFFICIENT_CREDITS Insufficient credits.

Error types

  • Error::Api { status, code, message }variantThe API said no, e.g. 422 BILLING_INSUFFICIENT_CREDITS.
  • Error::JobFailed { job, task }variantThe job ended in error; task has code, reason and message.
  • Error::WaitTimeout { job }variantwait ran past its timeout; job is the job as last seen.
  • Error::Transport(String)variantNo HTTP response (network), or a local file problem.
  • Error::Invalid(String)variantBad input to the SDK, or a bad webhook signature.

Retries and timeouts

Network errors, rate limits (429) and server errors (5xx) are retried twice with backoff, honouring Retry-After. Creating a job is only retried when the request never reached the API, so a job is never created twice.

Example

Tune retries
let rc = Client::builder()
    .max_retries(4)
    .timeout(Duration::from_secs(30))
    .build();

Like RunConvert? Set us as a preferred source on Google.

Add to Preferred Sources