Skip to main content

PHP SDK

formfeed/sdk is the PHP client for the REST API, for PHP 8.3 and later. It behaves exactly like the TypeScript SDK: 429, 503 and network errors are retried, every render carries an Idempotency-Key, and API problems throw FormfeedException. It sends over the PSR-18 HTTP client your application already has. In Laravel, formfeed/laravel adds the settings from .env, a facade, a webhook middleware and a fake for tests. Use it on a server: the API refuses an API key sent from a web page.

composer require formfeed/sdk guzzlehttp/guzzle

Any other PSR-18 client works in place of Guzzle, Symfony's HttpClient for example.

Set up a client​

$formfeed = new Formfeed\Client(apiKey: getenv('FORMFEED_API_KEY'));
ArgumentDefaultNotes
apiKeyrequiredff_live_… or ff_test_…
region'eu''eu' (https://api-eu.formfeed.dev/v1) or 'us' (https://api-us.formfeed.dev/v1)
baseUrlregion hostFull 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.
httpClientfoundA PSR-18 client. Left out, Guzzle or Symfony's HttpClient where one is installed, made with timeout; else whatever php-http/discovery finds.
requestFactory, streamFactoryfoundPSR-17 factories; php-http/discovery finds them when left out.
maxRetries3Retries on 429, 503 and network errors; 0 turns retrying off.
timeout120.0Seconds per request, for the Guzzle or Symfony client the SDK makes itself. A client you pass keeps its own limits. A request that times out counts as a network error and is retried.
headers[]Sent with every request.
sleepusleepA closure that waits the seconds it is given, between retries and polls; for tests.

Pass them as named arguments. Every call takes the request as an array with the fields of the API reference, and answers a readonly model: $render->downloadUrl, $render->pageCount, $render->units, and $render->raw with the whole answer, fields of later API versions included.

Retries and idempotency​

The rule is the one of the TypeScript SDK: 429, 503 and network errors are sent again up to maxRetries 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 one as the last argument; 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",
], 'order-8812-invoice');

// a sync render still running after 60 seconds comes back queued; wait for it
if ($render->status !== 'succeeded') {
$render = $formfeed->renders->waitFor($render);
}
echo $render->downloadUrl, ' ', $render->pageCount, ' ', $render->units, PHP_EOL;

$formfeed->renders->downloadTo($render, 'invoice.pdf');

The array is 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. The second argument, the idempotency key, is the SDK's own.

A failed render throws FormfeedException. 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; download($render) returns the file's bytes, downloadTo($render, $path) writes them, and both throw not_ready while the render has no output.

Async renders and batches​

$queued = $formfeed->renders->create(['template' => 'annual-report', 'data' => $payload, 'mode' => 'async']);
$done = $formfeed->renders->waitFor($queued, timeout: 120);

$job = $formfeed->renders->batch([
'template' => 'invoice',
'zip' => true,
'items' => array_map(fn (array $order) => [
'data' => ['invoice' => $order],
'filename' => "{$order['number']}.pdf",
'meta' => ['order_id' => $order['id']],
], $orders),
]);
$finished = $formfeed->jobs->waitFor($job);
echo $finished->status, ' ', $finished->succeeded, ' ', $finished->failed, ' ', $finished->zipUrl, PHP_EOL;

renders->waitFor($render, timeout: 120, interval: 1) asks every interval seconds until the render succeeded or failed and returns it either way; after timeout seconds it throws FormfeedException with the code timeout, while the render goes on. jobs->waitFor does the same for a batch (defaults: timeout: 600, interval: 2) and returns once the job is completed, partially_failed or failed. 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]);
foreach ($page->data as $failed) {
echo $failed->id, ' ', $failed->error['code'] ?? '', PHP_EOL;
}

// a generator that follows the cursor
foreach ($formfeed->renders->all(['since' => '2026-08-01T00:00:00Z', 'until' => '2026-09-01T00:00:00Z']) as $render) {
// …
}

$formfeed->renders->deleteOutputs($render); // needs the file:delete scope

$kept = $formfeed->renders->input($render); // the kept request (render:input); 410 render_input_expired when not kept

PDF tools​

use Formfeed\Upload;

// 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); // pageCount, 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(Upload::fromPath('report.xlsx'), ['single_page_sheets' => true, 'filename' => 'report.pdf']);
// …or the output of a Word or PowerPoint template render
$offerPdf = $formfeed->pdf->convert($offerRender, ['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->toImage($bundle, ['pages' => '1', 'dpi' => 72]); // output png
$redacted = $formfeed->pdf->redact(Upload::fromPath('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, toImage one unit per picture. info is free on every plan. A source is a Render or its id, or a LibraryFile or its id or name; info, split, compress, toImage, redact and fill also take an Upload (Upload::fromPath($path) or Upload::fromString($bytes, $name)), 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, 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' => null none; fill puts what it did in the render's form. $formfeed->einvoices->validate($render) says which rules an e-invoice passed; see E-invoice validation.

File library​

use Formfeed\Upload;

// the same name replaces the file everywhere; templates use {{ asset('brand/logo.png') }}
$logo = $formfeed->files->upload(Upload::fromPath('logo.png', 'brand/logo.png'));
echo $logo->url, PHP_EOL;

foreach ($formfeed->files->all(['prefix' => 'brand/']) as $file) {
echo $file->name, ' ', $file->bytes, PHP_EOL;
}
$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. Library files are served without a signature; see Files.

Templates​

foreach ($formfeed->templates->all(['kind' => 'pdf']) as $template) {
echo $template->slug, ' ', $template->publishedVersion, PHP_EOL;
}

$schema = $formfeed->templates->schema('invoice'); // JSON Schema of the expected data
$check = $formfeed->templates->validate('invoice', ['data' => $data]); // ok, template, diagnostics; 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 PHP SDK reads and checks templates. Writing versions, publishing, release channels, the brand kit and shared partials have no methods yet: $formfeed->request('GET', '/templates/invoice/channels') reaches any call of the API with the client's key, retries and errors.

Webhooks​

$event = Formfeed\Webhook::parse(
getenv('FORMFEED_WEBHOOK_SECRET'),
$_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? null,
file_get_contents('php://input'),
);
if ($event['type'] === 'render.completed') {
// …
}

Pass the raw request body, not decoded JSON: the signature covers the bytes on the wire. parse returns the event as an array (id, type, created_at, workspace_id, data) and throws UnexpectedValueException when the signature does not match or its timestamp is more than five minutes from the current time (the fourth argument changes the five minutes). Webhook::verify($secret, $header, $rawBody) returns a boolean instead of throwing. Endpoints are managed with $formfeed->webhooks->create(['url' => …, 'events' => […]]), list(), update(), delete() and test(); create and update take environments. $formfeed->webhooks->resend($eventId, $endpointId) sends a stored event again. A complete receiver is on the Webhooks page.

Usage and account​

$usage = $formfeed->account->usage(); // current period
$august = $formfeed->account->usage('2026-08'); // the period that started in August 2026
echo $usage->used, ' of ', $usage->included, PHP_EOL;

$account = $formfeed->account->get(); // workspace, plan, limits (an array)

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​

try {
$formfeed->renders->create(['template' => 'missing']);
} catch (Formfeed\FormfeedException $e) {
echo $e->errorCode, ' ', $e->status, ' ', $e->requestId, PHP_EOL; // template_not_found 404 req_…
print_r($e->problem); // the full problem body
}

$e->errorCode is the problem code of the API's answer, $e->getMessage() its detail and $e->status its HTTP status; $e->problem is the problem body as an array and $e->requestId the X-Request-Id to quote to support. Failures on the client's side have the status 0 and these codes:

CodeWhen
network_errorThe request could not be sent or timed out on every attempt
timeoutrenders->waitFor or jobs->waitFor ran out of time; the render or job goes on
not_readyrenders->download of a render that has no output yet, or failed
download_failedThe download link answered an error (the status is the link's)
invalid_responseThe API answered with a body that is not the JSON the call expects
invalid_requestThe client was created without an API key, or with a region that is neither eu nor us

An error answer without a problem code gets http_<status>, such as http_502. Webhook::parse throws UnexpectedValueException, not FormfeedException.

Laravel​

composer require formfeed/laravel

formfeed/laravel (Laravel 12 and 13) binds one Formfeed\Client in the container, set up from .env:

FORMFEED_API_KEY=ff_test_...
FORMFEED_WEBHOOK_SECRET=whsec_...

FORMFEED_REGION and FORMFEED_BASE_URL are there when you need them; php artisan vendor:publish --tag=formfeed-config copies config/formfeed.php for the retries, the time limit and the webhook tolerance. php artisan about shows whether the key and the secret arrived, never their values. The facade has the client's services as methods, and a class that takes Formfeed\Client in its constructor gets the same client:

use Formfeed\Laravel\Facades\Formfeed;

$render = Formfeed::renders()->create(['template' => 'invoice', 'data' => $data]);
Storage::put("invoices/{$order->id}.pdf", Formfeed::renders()->download($render));

The middleware formfeed.webhook lets a delivery through only when its signature matches the body as it arrived, within the tolerance; anything else is answered 401, which Formfeed retries. After it, the event is the request's JSON ($request->input('type')). A route in routes/web.php also needs an exception from the CSRF check (validateCsrfTokens(except: […]) in bootstrap/app.php); one in routes/api.php does not.

Route::post('/formfeed/webhook', StoreFormfeedEvent::class)->middleware('formfeed.webhook');

In tests, Formfeed::fake() swaps the client for one that never reaches the network. It answers renders, batches, jobs and the PDF tools as the API would (a sync render finished, an async one queued until it is first read, a real PDF with the render's pages behind every link), keeps every request, and needs an answer from the test for any other call:

use Formfeed\Laravel\Facades\Formfeed;
use Formfeed\Laravel\Testing\FormfeedFake;

Formfeed::fake([
'POST /pdf/protect' => FormfeedFake::problem('forbidden', 403, 'PDF tools need the Starter plan'),
'GET /account' => ['id' => 'org_1', 'name' => 'Fennlor Studio GmbH'],
]);

$this->post('/orders/8812/invoice')->assertOk();

Formfeed::assertRendered('invoice');
Formfeed::assertRendered(fn (array $request) => $request['data']['number'] === 'RE-8812', times: 1);

Answers go by METHOD /path with * as a wildcard: an array is laid over the fake's own answer and kept, FormfeedFake::problem() and FormfeedFake::response() are answered exactly, FormfeedFake::failed() makes an async render fail once it is read, FormfeedFake::sequence() answers in turn, and a closure decides per request. The assertions are assertRendered, assertNotRendered, assertNothingRendered, assertBatched, assertSent, assertNotSent, assertNothingSent and assertSentCount; Formfeed::recorded() returns the requests. The trait Formfeed\Laravel\Testing\InteractsWithFormfeedWebhooks posts a signed delivery to a route behind the middleware ($this->postFormfeedWebhook($uri, 'render.completed', $data)), on Laravel's clock.