Guide · Java
Async PDF rendering with a verified webhook in Java
A long report should not hold an HTTP request open. In async mode the API answers at once with a queued render and calls your endpoint when the PDF is ready. This guide has both halves in Java: the request, and a receiver that accepts only deliveries Formfeed really signed.
Free plan with 100 units a month, no credit card
What you need
- An API key. Create one in the app under API keys and export it as
FORMFEED_API_KEY. A test key (ff_test_…) is right for trying things out. See the quick start. - Java. You need Java 17 or newer;
java.net.http.HttpClientand text blocks are part of the JDK. - The template.
revenue-reportfrom the report example, and itsdata.jsonnext to the program. - A secret. 16 to 200 random characters in
FORMFEED_WEBHOOK_SECRET, known to both programs. It signs the deliveries of this render, retries included. - A public URL. Replace
https://example.com/hooks/formfeedwith your endpoint. While developing,formfeed listenforwards deliveries tolocalhostwithout a tunnel.
The program
The request names the template, switches to mode: "async" and says where to report. The answer comes back immediately with the status queued.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
public class Render {
static final String ENDPOINT = "https://api-eu.formfeed.dev/v1/renders";
static final HttpClient CLIENT = HttpClient.newHttpClient();
public static void main(String[] args) throws Exception {
String data = Files.readString(Path.of("data.json"));
String secret = System.getenv("FORMFEED_WEBHOOK_SECRET");
// the JDK has no JSON library: the body is a text block, and a project would use Jackson or Gson
String body = """
{
"template": "revenue-report",
"data": %s,
"mode": "async",
"webhook_url": "https://example.com/hooks/formfeed",
"webhook_secret": %s
}
""".formatted(data, quote(secret));
HttpResponse<String> response = send(HttpRequest.newBuilder(URI.create(ENDPOINT)).POST(HttpRequest.BodyPublishers.ofString(body)));
// every error is a problem document (RFC 9457) with a title and a detail
if (response.statusCode() >= 400) {
System.err.println(response.body());
System.exit(1);
}
System.out.println(response.body()); // queued: the webhook reports the rest
}
/** One call to the API with the key. */
static HttpResponse<String> send(HttpRequest.Builder request) throws Exception {
return CLIENT.send(request
.header("Authorization", "Bearer " + System.getenv("FORMFEED_API_KEY"))
.header("Content-Type", "application/json")
.build(), HttpResponse.BodyHandlers.ofString());
}
/** A JSON string literal. */
static String quote(String text) {
StringBuilder out = new StringBuilder("\"");
for (char c : text.toCharArray()) {
if (c == '"' || c == '\\') out.append('\\').append(c);
else if (c < 0x20) out.append(String.format("\\u%04x", (int) c));
else out.append(c);
}
return out.append('"').toString();
}
}Run it
It prints the render’s id and queued. A few seconds later your endpoint receives render.completed with the full render, its download_url included, or render.failed with the reason.
export FORMFEED_API_KEY=ff_test_...
export FORMFEED_WEBHOOK_SECRET=$(openssl rand -hex 24)
java Render.javaWhat is particular about Java
- No JSON library in the JDK. To stay free of dependencies the body is a text block, and the values the program needs from JSON (the render’s
idanddownload_url, an invoice number) are read with a regular expression. In a project, build the body and read the answer with Jackson or Gson. - Single-file launch.
java Render.javacompiles and runs in one step, so trying it needs no build tool. - Straight to disk.
BodyHandlers.ofFilestreams the PDF into the file without holding it in memory.
The receiver
It listens on port 8080, reads the raw body, checks the signature and the age of the timestamp, and only then looks at the JSON. A delivery that fails the check gets 401.
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class Hook {
static final byte[] SECRET = System.getenv("FORMFEED_WEBHOOK_SECRET").getBytes(StandardCharsets.UTF_8);
/** Checks "Webhook-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of t.body>". */
static boolean valid(String header, byte[] body) throws Exception {
Map<String, String> parts = new HashMap<>();
for (String part : (header == null ? "" : header).split(",")) {
String[] pair = part.trim().split("=", 2);
if (pair.length == 2) parts.put(pair[0], pair[1]);
}
long timestamp;
byte[] given;
try {
timestamp = Long.parseLong(parts.getOrDefault("t", ""));
given = HexFormat.of().parseHex(parts.getOrDefault("v1", ""));
} catch (IllegalArgumentException e) {
return false;
}
if (Math.abs(System.currentTimeMillis() / 1000 - timestamp) > 300) return false;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(SECRET, "HmacSHA256"));
mac.update((timestamp + ".").getBytes(StandardCharsets.UTF_8));
return MessageDigest.isEqual(mac.doFinal(body), given); // constant time
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/hooks/formfeed", exchange -> {
// the signature covers the bytes on the wire: read the raw body, never re-serialised JSON
byte[] body = exchange.getRequestBody().readAllBytes();
boolean ok;
try {
ok = valid(exchange.getRequestHeaders().getFirst("Webhook-Signature"), body);
} catch (Exception e) {
ok = false;
}
if (ok) System.out.println(new String(body, StandardCharsets.UTF_8)); // hand it to your JSON library
exchange.sendResponseHeaders(ok ? 204 : 401, -1);
exchange.close();
});
server.start();
}
}Start the receiver
FORMFEED_WEBHOOK_SECRET=… java Hook.javaVerifying in Java
MessageDigest.isEqual. It compares the byte arrays in constant time;Arrays.equalsdoes not.- In Spring. Take the body as
@RequestBody byte[](orString) and verify before mapping it to an object with yourObjectMapper.
What arrives
A POST with Webhook-Signature: t=<unix seconds>,v1=<hex>, where the hex is HMAC-SHA256 over t, a dot and the raw body, keyed with your secret exactly as you have it, as UTF-8 bytes: the webhook_secret you sent, or a registered endpoint’s whole whsec_… string, prefix included. Every attempt is signed anew with its own t. Webhook-Id stays the same across retries, so it is your deduplication key. data is the render as GET /renders/{id} returns it:
{
"id": "evt_5b0c8e6f2d4a4c3e9b1a7f6e5d4c3b2a",
"type": "render.completed",
"created_at": "2026-09-18T10:42:00Z",
"workspace_id": "3a6f…",
"data": {
"id": "rnd_7da09ab6cd9946b798c187c2a9350852",
"status": "succeeded",
"download_url": "https://cdn.formfeed.dev/o/eu/…/document.pdf?exp=…&sig=…",
"page_count": 2,
"units": 1,
…
}
}Retries, and what your endpoint owes
- Answer fast. A delivery succeeds with a
2xxwithin 10 seconds. Store the event and do the work afterwards. - Retries. Anything else, a redirect included, is retried after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours: six attempts in all, over about 14 hours and 40 minutes. The same event can therefore arrive twice: deduplicate by
Webhook-Id. - Without a secret. A
webhook_urlwithoutwebhook_secretis delivered unsigned. For signed deliveries of every render, register an endpoint once in the app or throughPOST /webhooks; it gets its own secret. - Try it locally.
formfeed listen --forward-to http://localhost:8080/hooks/formfeedrelays the events of your test renders to your machine, signed with the session’s own secret rather thanwebhook_secret: start the receiver with that one, whichformfeed listen --print-secretprints (run it before the session, since it ends a running one).formfeed trigger render.completed --template revenue-reportmakes a real test render whose event you watch arrive. The key needs thewebhook:listenscope. See developing webhooks locally.
When the API says no
- One shape for every error. Errors are problem documents (RFC 9457) with
type,title,status,detail, a stablecodeand therequest_idto quote to support; thetypeURL leads to a page about that error. The list is in the error reference. - The usual ones.
401 unauthorizedfor a missing or revoked key,404 template_not_foundfor a wrong template name,422 template_runtime_errorwhen the template fails on the data,429 rate_limitedabove the plan’s requests per second,402 quota_exceededwhen the Free plan’s units are used up (a paid plan bills extra units up to its hard cap). - Retry safely. Send an
Idempotency-Keyheader with the POST, and repeat the request with the same key when you do not know whether the first attempt arrived: for 24 hours the key returns the first answer instead of rendering and billing again. The answer is stored once the first attempt has been answered, so do not retry while it may still run; and problems below 500 are stored too, so a corrected request needs a new key.
The job around this program
This guide is one program. What the job needs around it, from the template to the limits and the price, is on the page Report PDF generation.
More Java guides
FAQ
- Can I poll instead of receiving a webhook?
- Yes:
GET /renders/{id}until the status issucceededorfailed; the SDKs havewaitForandwait_forfor it. A webhook saves the requests and reports sooner. See async and batch. - Why must the raw body be used?
- The signature covers the bytes on the wire. Parsing and re-serialising JSON may reorder keys, change number formats or escape characters differently, and the HMAC of that text no longer matches.
- What is the five-minute tolerance for?
- It stops a captured delivery from being replayed later. It also means the clock of your server must be roughly right.