Ruby SDK
formfeed is the Ruby client for the REST API, for Ruby 3.3 and later. It needs nothing beyond Ruby's standard library (net/http, json, openssl), so it adds no other gem to your bundle. It behaves exactly like the TypeScript SDK: 429, 503 and network errors are retried, every render carries an Idempotency-Key, and API problems raise Formfeed::Error.
gem install formfeed
In an application with Bundler, add it to the Gemfile and run bundle install (bundle add formfeed does both):
gem "formfeed"
Set up a client
require "formfeed"
formfeed = Formfeed::Client.new(api_key: ENV.fetch("FORMFEED_API_KEY"))
| Keyword | Default | Notes |
|---|---|---|
api_key | required | ff_live_… or ff_test_… |
region | "eu" | "eu" (https://api-eu.formfeed.dev/v1) or "us" (https://api-us.formfeed.dev/v1) |
base_url | region host | Full URL including /v1, used instead of the region's host. You need it only for an address other than the public API, such as one our support gives you. Wins over region. |
max_retries | 3 | Retries on 429, 503 and network errors; 0 turns retrying off. |
timeout | 120 | Seconds for sending a request and for each read of its answer; connecting takes at most 10 of them. A request that times out counts as a network error and is retried. |
headers | {} | Sent with every request. |
sleep | Kernel.sleep | A callable that waits the seconds it is given, between retries and polls; for tests. |
jitter | random | A callable answering the seconds added to a retry's wait, 0 to 0.25; for tests. |
Every call takes the request as keywords or as one Hash, with the fields of the API reference: create(template: "invoice") and create("template" => "invoice") send the same. Template data, settings and the other nested options are plain hashes. Answers are immutable objects: render.download_url, render.page_count, render.units, and render.raw with the whole answer, fields of later API versions included.
The client opens a connection of its own for every request, so one client can be shared by every thread of an application. In Rails, make it once in an initializer:
# config/initializers/formfeed.rb
FORMFEED = Formfeed::Client.new(api_key: ENV.fetch("FORMFEED_API_KEY"))
Retries and idempotency
The rule is the one of the TypeScript SDK: 429, 503 and network errors are sent again up to max_retries times, after the seconds of Retry-After, else 0.5 s, 1 s, 2 s and so on plus up to 0.25 s of jitter, never more than 30 s. renders.create, renders.batch, every PDF tool but info, and einvoices.validate send an Idempotency-Key, a random one unless you pass idempotency_key:; its retries reuse it, so the API renders and charges once. To retry safely across processes, pass a key of your own, such as order-8812-invoice. See Idempotency.
Render
invoice = { number: "2026-0042", lines: [{ description: "Consulting", qty: 8, price: 120 }] }
render = formfeed.renders.create(
template: "invoice",
data: { invoice: invoice },
filename: "invoice-#{invoice[:number]}.pdf",
idempotency_key: "order-8812-invoice"
)
# a sync render still running after 60 seconds comes back queued; wait for it
render = formfeed.renders.wait_for(render) unless render.status == "succeeded"
puts "#{render.download_url} #{render.page_count} #{render.units}"
The keywords are the body of POST /renders: template, or html with engine, or url, or markdown; version; data; output; settings; locale; filename; expires_in; access; mode; webhook_url and webhook_secret; meta; region; dedupe; canary_key; validate_data; post; storage. idempotency_key: is the SDK's own.
A failed render raises Formfeed::Error. A sync render that has no answer after 60 seconds is not an error: it comes back with the status queued or rendering and finishes in the background (the automatic fallback), so check status before you download. formfeed.renders.get(id) fetches a render again, with a fresh download link; render.finished? says whether it succeeded or failed.
Downloads
pdf = formfeed.renders.download(render) # the file's bytes, a binary String
formfeed.renders.download_to(render, "invoice.pdf") # streamed into a file; answers the bytes written
File.open("invoice.pdf", "wb") { |file| formfeed.renders.download_to(render, file) } # or into an IO
# in a Rails controller
send_data formfeed.renders.download(render), type: "application/pdf", filename: "invoice.pdf"
Both take a render or its id; with an id, the render is fetched first. The signed link they follow needs no key, and a download is not retried. Both raise not_ready while the render has no output, and download_failed when the link answers an error. A download into a path that breaks off leaves no file behind.
Async renders and batches
queued = formfeed.renders.create(template: "annual-report", data: payload, mode: "async")
done = formfeed.renders.wait_for(queued, timeout: 120)
items = orders.map do |order|
{ data: { invoice: order }, filename: "#{order[:number]}.pdf", meta: { order_id: order[:id] } }
end
job = formfeed.renders.batch(template: "invoice", zip: true, items: items)
finished = formfeed.jobs.wait_for(job)
puts "#{finished.status} #{finished.succeeded} #{finished.failed} #{finished.zip_url}"
finished.items.each { |item| puts "#{item.id} #{item.status}" }
renders.wait_for(render, timeout: 120, interval: 1) asks every interval seconds until the render succeeded or failed and returns it either way; after timeout seconds it raises Formfeed::Error with the code timeout, while the render goes on. jobs.wait_for does the same for a batch (defaults: timeout: 600, interval: 2) and returns once the job is completed, partially_failed or failed. A job's items are its renders in the order of the request. For anything that takes more than a few seconds in production, prefer webhooks over polling.
List renders and delete outputs
page = formfeed.renders.list(template: "invoice", status: "failed", limit: 20)
page.each { |failed| puts "#{failed.id} #{failed.error&.dig("code")}" }
# an Enumerator that follows the cursor, asking for the next page only when it gets there
formfeed.renders.all(since: "2026-08-01T00:00:00Z", until: "2026-09-01T00:00:00Z").each do |render|
# …
end
formfeed.renders.delete_outputs(render) # needs the file:delete scope
kept = formfeed.renders.input(render) # the kept request (render:input); 410 render_input_expired when not kept
A page enumerates its renders and carries next_cursor, nil on the last one. all takes the same filters as list (template, status, environment, since, until, limit); with a block it hands each render to the block, and all(…).first(50) reads only the pages it needs.
PDF tools
# in the same render: steps run as merge, watermark, password
contract = formfeed.renders.create(template: "contract", data: data, post: { watermark: { text: "DRAFT" } })
# on renders you already have (a Render or its id); each answers a new render
bundle = formfeed.pdf.merge([invoice, terms], filename: "bundle.pdf")
locked = formfeed.pdf.protect(bundle, user_password: "open-sesame", permissions: ["print"])
info = formfeed.pdf.info(locked) # page_count, pages, encrypted, metadata, form; free
# office documents to PDF: an upload (Word, Excel, PowerPoint, OpenDocument, RTF or HTML, up to 20 MB, not kept)…
report = formfeed.pdf.convert(Formfeed::Upload.from_path("report.xlsx"), single_page_sheets: true, filename: "report.pdf")
# …or the output of a Word or PowerPoint template render
offer_pdf = formfeed.pdf.convert(offer_render, page_ranges: "1-3")
# split, compress, draw, redact and fill: a stored PDF, or an Upload that is never kept
parts = formfeed.pdf.split(bundle, ranges: ["1", "2-"]) # output zip
thumbnail = formfeed.pdf.to_image(bundle, pages: "1", dpi: 72) # output png
redacted = formfeed.pdf.redact(Formfeed::Upload.from_path("invoice.pdf"), text: ["Max Mustermann"])
form = formfeed.pdf.info("antrag.pdf").form # every field's name, type, value and options
filled = formfeed.pdf.fill("antrag.pdf", fields: { "customer.name" => "Erika Mustermann" }, flatten: true)
Starter plan and higher, 0.5 units per step on live keys; a conversion is counted like a PDF render, to_image one unit per picture. info is free on every plan. A source is a Formfeed::Render or its id, or a Formfeed::LibraryFile or its id or name; info, split, compress, to_image, redact and fill also take a Formfeed::Upload, which is sent as multipart and never kept, and convert takes an Upload or the render of a Word or PowerPoint template. The options are the fields of each tool as the PDF tools page describes them, as keywords or one Hash, output options included (filename, expires_in, access, meta, storage). A result of several files is one ZIP (render.output == "zip"). redact draws a black box over what it removed, fill: nil none; fill puts what it did in the render's form.
Uploads
Upload.from_path(path) reads a file, Upload.from_string(bytes, "a.pdf") takes bytes in memory, and Upload.from_io(io) reads an IO from where it stands, such as the upload a Rails or Rack application received. from_path and from_io take a name as name:, from_string as its second argument, and all three a type as content_type:; the API reads the format from the bytes either way.
# a Rails controller: the PDF a form posted, made smaller and sent back
def compress
upload = Formfeed::Upload.from_io(params.require(:file)) # takes the file's name and type
smaller = FORMFEED.pdf.compress(upload)
send_data FORMFEED.renders.download(smaller), type: "application/pdf", filename: "compressed.pdf"
end
# Sinatra or plain Rack: a file field is a Hash with the Tempfile and the file's name
file = request.params["file"]
upload = Formfeed::Upload.from_io(file[:tempfile], name: file[:filename])
E-invoice validation
report = formfeed.einvoices.validate(Formfeed::Upload.from_path("RE-2026-0001.xml"))
puts "#{report["result"]} by #{report["validator"]} (#{report["rules"]})"
report["checks"].each { |check| puts "#{check["name"]}: #{check["result"]}" }
stored = formfeed.einvoices.validate("rnd_0d290c45cbeb4554b946bbad1acee87e")
A render of this workspace's own e-invoice (a Formfeed::Render or its id) is answered from the report it keeps and costs nothing. An XML Formfeed did not make, as an Upload of up to 4 MB, takes one of the organisation's validations of the day, from the Starter plan. rules: is "auto" (the default), "factur-x", "xrechnung" or "en16931". The answer is the report as a Hash, a file that failed included; E-invoice validation describes it. Needs einvoice:validate.
File library
# the same name replaces the file everywhere; templates use {{ asset('brand/logo.png') }}
logo = formfeed.files.upload(Formfeed::Upload.from_path("logo.png", name: "brand/logo.png"))
puts logo.url
formfeed.files.all(prefix: "brand/").each { |file| puts "#{file.name} #{file.bytes}" }
formfeed.files.delete(logo)
# library files in post-processing: an image watermark and a PDF merged by name
formfeed.renders.create(template: "contract", data: data, post: { watermark: { image: "draft.png" }, merge_after: ["terms.pdf"] })
file:read, file:write and file:delete scopes. The Upload's name is the file's name in the library. Library files are served without a signature; see Files.
Templates
formfeed.templates.all(kind: "pdf").each { |template| puts "#{template.slug} #{template.published_version}" }
schema = formfeed.templates.schema("invoice") # JSON Schema of the expected data
check = formfeed.templates.validate("invoice", data: data) # valid, errors, warnings; renders nothing
templates.get(slug) reads one template; schema(slug, version:) takes "published" (the default), "latest", a number or a channel name, and returns the stored data schema, else one inferred from the sample data. The Ruby SDK reads and checks templates. Writing versions, publishing, release channels, the brand kit and shared partials have no methods yet: request reaches them.
Webhooks
class FormfeedWebhooksController < ActionController::API
def create
event = Formfeed::Webhook.parse(
ENV.fetch("FORMFEED_WEBHOOK_SECRET"),
request.headers["Webhook-Signature"],
request.raw_post
)
InvoiceReadyJob.perform_later(event["data"]["id"]) if event["type"] == "render.completed"
head :no_content
rescue Formfeed::Webhook::Error
head :unauthorized
end
end
Pass the raw request body (request.raw_post), not params: the signature covers the bytes on the wire. parse returns the event as a Hash (id, type, created_at, workspace_id, data) and raises Formfeed::Webhook::Error when the signature does not match or its timestamp is more than five minutes from the current time (tolerance: changes the five minutes, in seconds). Formfeed::Webhook.verify(secret, header, raw_body) returns true or false instead of raising. A controller that inherits from ActionController::Base also needs skip_forgery_protection, because a delivery carries no CSRF token. A receiver in Sinatra is in the Ruby guide.
Endpoints are managed with formfeed.webhooks.create(url: …, events: […]), list, update, delete and test; create and update take environments, and the endpoint create returns carries its secret, once. formfeed.webhooks.resend(event_id, endpoint_id: endpoint) sends a stored event again. Needs webhook:manage.
Usage and account
usage = formfeed.account.usage # current period
august = formfeed.account.usage("2026-08") # the period that started in August 2026
puts "#{usage.used} of #{usage.included}"
account = formfeed.account.get # workspace, plan, limits (a Hash)
Units are counted per organisation, in billing periods that renew on the day the subscription started (calendar months on the Free plan without a subscription). Both need account:read.
Errors
begin
formfeed.renders.create(template: "missing")
rescue Formfeed::Error => e
puts "#{e.code} #{e.status} #{e.request_id}" # template_not_found 404 req_…
pp e.problem&.raw # the full problem body
end
e.code is the problem code of the API's answer, e.message its detail (else its title) and e.status its HTTP status; e.problem is the problem body as a Formfeed::Problem (title, detail, errors, location and the others, and raw; e.problem["period_end"] reads any member) and e.request_id the X-Request-Id to quote to support. Failures on the client's side have no problem and these codes:
| Code | When |
|---|---|
network_error | The request could not be sent or timed out on every attempt |
timeout | renders.wait_for or jobs.wait_for ran out of time; the render or job goes on |
not_ready | renders.download of a render that has no output yet, or failed |
download_failed | The download link answered an error (the status is the link's), or more than five redirects |
invalid_response | The API answered with a body that is not the JSON the call expects |
invalid_request | The client was created without an API key, or with a region that is neither eu nor us |
Their status is 0, but where an answer came: download_failed has the link's, and an invalid_response whose body is no JSON at all has the API's. An error answer without a problem code gets http_<status>, such as http_502. Webhook.parse raises Formfeed::Webhook::Error, not Formfeed::Error, and a request that is not a Hash, or a file Upload.from_path cannot read, raises ArgumentError.
Anything else
request reaches any call of the API with the client's key, retries and errors, and returns the decoded JSON, nil for an answer without a body. A body is the third argument, a Hash sent as JSON, and idempotency_key: goes with it where the call takes one:
channels = formfeed.request(:get, "/templates/invoice/channels")
formfeed.request(:put, "/templates/invoice/channels/staging", { version: 7 })
brand = formfeed.request(:get, "/brand")