wellfriend-document-sdk 1.0.0

Official async Rust SDK for the Wellfriend document API: typed document tools, pipelines, streaming uploads and downloads, retries and webhook verification.
Documentation

wellfriend-document-sdk (Rust)

The official async Rust SDK for the Wellfriend document API: compress, convert, merge, split, OCR, redact and sign documents with one typed call per tool, chain tools into pipelines, and stream files in and out.

This is the client for Wellfriend's hosted API. It is not the open-source wellfriendpdf engine, which runs locally and needs no key.

Install

cargo add wellfriend-document-sdk
cargo add tokio --features macros,rt-multi-thread

The package is wellfriend-document-sdk; the crate you use is wellfriend. Rust 1.80 or newer.

Get an API key

Sign in at wellfriend.dev, open Developer API → API keys (https://wellfriend.dev/dashboard/developer-api/keys) and create a key. Test keys start with wf_v2_test, live keys with wf_v2_live.

export WELLFRIEND_API_KEY="wf_v2_test_..."

Quickstart

use wellfriend::Wellfriend;

#[tokio::main]
async fn main() -> wellfriend::Result<()> {
    let wf = Wellfriend::new();
    wf.tools().compress_pdf("in.pdf", None).await?.save("out.pdf").await?;
    Ok(())
}

compress_pdf uploads in.pdf, starts the operation, waits for it, fails on error and returns a ToolResult; save streams the output to disk.

Tools

Every tool in the catalog has a typed method on wf.tools(), with its own parameter struct (None means the tool's defaults). Parameter structs and their choice enums live in wellfriend::types (and at the crate root).

use wellfriend::types::{CompressPdfParams, CompressPdfProfile, ResizeImageMode, ResizeImageParams};

let params = CompressPdfParams { profile: Some(CompressPdfProfile::AggressiveLossless), ..Default::default() };
let result = wf.tools().compress_pdf("scan.pdf", Some(params)).await?;
println!("{} -> {:?} bytes", result.operation.id, result.outputs[0].size_bytes);

let thumb = ResizeImageParams { mode: Some(ResizeImageMode::Percentage), percentage: Some(25.0), ..Default::default() };
wf.tools().resize_image("photo.jpg", Some(thumb)).await?.save("photo.small.jpg").await?;

// Tools that read several files take a list.
wf.tools().merge_pdf(["a.pdf", "b.pdf", "c.pdf"], None).await?.save("merged.pdf").await?;
  • Input (FileInput) is a path, FileInput::bytes(data, "name.pdf"), FileInput::reader(reader, size, "name.pdf"), FileInput::file(tokio_file, "name.pdf"), or a stored document (FileInput::document("doc_..."), a &Document). The content type comes from the file extension.
  • ToolResult gives .save(path) (a directory writes every output under its own name), .bytes(), .stream(), .outputs (document id, version id, file name, content type, size), .operation and .usage.
  • Any tool by id: wf.tools().run(ToolId::CompressPdf, "in.pdf", Some(ToolParameters::new().set("profile", "medium"))).
  • Named asset files (watermark image, signature image, certificate): wf.tools().request(ToolId::AddWatermark).input("in.pdf").asset("watermarkImage", Asset::file("logo.png")).run().
  • Start without waiting: wf.tools().start(...) returns the Operation; later wf.document_operations().wait(&operation.id) returns the ToolResult. (Rust's form of wait: false.)
  • Price a run first: wf.quote(ToolId::OcrPdf, None).await? (free, nothing is reserved).

Pipelines

Several tools on one file. The input is uploaded once; every step is created at once, each reading the output of the step before it, and only the last step is waited for.

use wellfriend::Step;

let result = wf
    .pipeline([Step::new("compress-pdf").params(CompressPdfParams::default()), Step::rotate_pdf(None)])
    .run("report.pdf")
    .await?;
result.save("report.small.rotated.pdf").await?;
  • 1 to 10 steps. Tools that read several files (merge) cannot be steps.
  • If a step fails, the steps after it fail too and their request units are given back; the error is Error::OperationFailed with step (1-based) and a message naming the tool.
  • An idempotency key set with .with_options(..) covers the whole run (each step uses <key>.step<n>).
  • wf.pipeline(..).quote() prices the run first.
  • wf.workflows().define(name, steps) creates a published workflow with the same steps, for triggers and the dashboard.

Files

  • Uploads stream from disk. Files up to 100 MiB go in one request; larger files use the resumable upload: the server sets the part size (8 MiB), each part is retried on its own, and the SHA-256 the API needs above 50 MiB is computed while reading. Only one part is in memory at a time.
  • wf.documents().create("big.pdf") stores a file without running a tool and returns the Document.
  • Downloads stream: wf.document_versions().download(doc, ver).await? returns a Download with .save(path) (written to a temporary file, renamed when complete), .bytes_stream() and .bytes().

Errors

Every call returns wellfriend::Result<T>. Error has one variant per case:

Variant When
BadRequest (400), Validation (422, or a 400 for invalid input such as a bad tool parameter) the request is wrong
Authentication (401), PermissionDenied (403), NotFound (404), Conflict (409) as named
RateLimit (429) too many requests; retry_after() says how long to wait
Server (5xx), Api (any other status) the API failed
Connection, Timeout network or TLS failure; no answer within the timeout
OperationFailed the operation or run ended failed or cancelled (code, message, the final operation)
WaitTimeout still running at the wait limit; carries the id to wait on again
WebhookVerification, InvalidInput, Io, Decode local problems
match wf.tools().compress_pdf("in.pdf", None).await {
    Ok(result) => { result.save("out.pdf").await?; }
    Err(wellfriend::Error::OperationFailed(failure)) => eprintln!("{}: {}", failure.code, failure.message),
    Err(error) => eprintln!("{error} (status {:?}, code {:?})", error.status(), error.code()),
}

API errors read message (reference ref_...); quote the reference id to support. error.status(), error.code() and error.reference_id() work on every variant.

Retries and timeouts

use std::time::Duration;
use wellfriend::{RequestOptions, Wellfriend};

let wf = Wellfriend::builder()
    .api_key("wf_v2_live_...")            // default: WELLFRIEND_API_KEY
    .timeout(Duration::from_secs(30))     // default 60 s
    .max_retries(4)                       // default 2
    .wait_timeout(Duration::from_secs(1800)) // default 15 min
    .build()?;

// Per call: options on any resource handle.
let options = RequestOptions::new().idempotency_key("invoice-42-compress").timeout(Duration::from_secs(120));
wf.tools().with_options(options).compress_pdf("invoice.pdf", None).await?;
  • Retried: network errors, 408, 429, 500, 502, 503, 504 and 520 to 524, for reads, deletes, and writes that carry an idempotency key. Backoff is exponential with full jitter (0.5 s base, 8 s cap) and honours Retry-After. An error the API marks final (for example an exhausted balance) is returned at once.
  • Every write the API keys gets a generated idempotency key (UUID v4), reused for each retry of that call.
  • The timeout covers connecting, the response headers and each read; it never limits a whole streamed upload or download.
  • Waiting polls every 0.5 s, growing to 5 s. Drop the future (or wrap it in tokio::time::timeout) to cancel.
  • Rust passes options with .with_options(...) instead of a last argument; WELLFRIEND_BASE_URL overrides the base URL (https:// only; plain http:// for a loopback host).

Webhooks

let event = wellfriend::verify_webhook(raw_body, &headers, "whsec_...")?;
if let wellfriend::WebhookEventData::DocumentOperationCompletedV2(data) = &event.data {
    println!("operation {} finished: {:?}", data.operation_id, data.output_document_id);
}

verify_webhook (also wf.webhooks().verify(...)) checks the webhook-signature HMAC-SHA256 over {webhook-id}.{webhook-timestamp}.{raw body} and a timestamp within 5 minutes, then returns the typed event. Pass the raw body exactly as received. During secret rotation use WebhookVerifier::new([old_secret, new_secret]).verify(raw_body, &headers). Headers can be a HeaderMap, a HashMap or a list of pairs.

Endpoints created with the ED25519 signature scheme sign with v1a,; enable the ed25519 feature (cargo add wellfriend-document-sdk --features ed25519) and use WebhookVerifier::ed25519([public_key]).

All resources

Every API operation has a typed method: the namespace is the operation group and the method its action, in snake case (documents.list → wf.documents().list(..), document-versions.download → wf.document_versions().download(..), webhooks.endpoints.create → wf.webhooks().endpoints_create(..)). The server-side verification endpoint is wf.webhooks().verify_remote(..).

List calls return a Page<T> (items, next_cursor, has_more()); the matching stream method returns every item, fetching further pages as you read:

use futures_util::TryStreamExt;

let mut documents = wf.documents().stream(None);
while let Some(document) = documents.try_next().await? {
    println!("{} {}", document.id, document.title);
}

Namespaces: documents, document_versions, document_operations, document_analytics, uploads, workflows, workflow_runs, workflow_approvals, pricing, platform, secure_links, webhooks, connectors, templates, signature_requests, annotations, forms, deal_rooms, embeds, embed_sessions, rooms, portals, esign, keys, usage and logs. Responses the API document describes are typed structs; the rest are JSON objects (wellfriend::Object). Unknown fields are kept in extra, and enums keep values this version does not know in Unknown(String). A TOOL embed session (one tool workspace in your page) is wf.embed_sessions().create_tool(ToolEmbedSession::new("compress-pdf", "https://app.example.com")).

License

MIT