Guide · Java
Generate Open Graph images in Java
Every post needs a share image, and drawing them by hand does not scale. This Java program sends the post’s title, category and author to a template and gets back a PNG on the CDN, ready for the og:image meta tag.
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.
og-imagefrom the Open Graph example: Tailwind classes, compiled at render time, no stylesheet to keep. - The data. The example’s
data.jsonnext to the program: category, title, publication date, reading time and the author with an avatar URL.
The program
The program reads data.json, asks for png, marks the output public, waits for the result when the API answers 202, and saves the image; download_url is its address on the CDN.
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;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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"));
// the JDK has no JSON library: the body is a text block, and a project would use Jackson or Gson
String body = """
{
"template": "og-image",
"data": %s,
"output": "png",
"access": "public"
}
""".formatted(data);
HttpResponse<String> response = send(HttpRequest.newBuilder(URI.create(ENDPOINT)).POST(HttpRequest.BodyPublishers.ofString(body)));
// not done within 60 seconds: the answer is 202 and the render goes on in the background;
// its result answers the same way until the render has finished
while (response.statusCode() == 202) {
Thread.sleep(2000);
response = send(HttpRequest.newBuilder(URI.create(ENDPOINT + "/" + field(response.body(), "id") + "/result")));
}
// 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);
}
String render = response.body();
CLIENT.send(HttpRequest.newBuilder(URI.create(field(render, "download_url"))).build(),
HttpResponse.BodyHandlers.ofFile(Path.of("og-image.png")));
System.out.println(field(render, "id") + " " + field(render, "download_url"));
}
/** One call to the API with the key; the download goes to a signed URL without it. */
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());
}
/** The first value of a field anywhere in a JSON text; a project would use Jackson or Gson instead. */
static String field(String json, String name) {
Matcher m = Pattern.compile("\"" + name + "\"\\s*:\\s*(?:\"([^\"]*)\"|([^,}\\s]+))").matcher(json);
return m.find() ? (m.group(1) != null ? m.group(1) : m.group(2)) : "";
}
}Run it
It prints the render’s id and the download URL, and og-image.png lies next to the program. Open it: 1200 × 630 pixels, the title truncated to fit, the avatar round.
export FORMFEED_API_KEY=ff_test_...
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.
What the two options do
output: "png". Names the format of the image.jpgandwebpwork as well; the pixel size, the scale factor and the format of a request withoutoutputcome from the template’simagesettings.access: "public". Gives a CDN URL without a signature, which is what a meta tag needs: a scraper has no API key. The address works for as long as the file is kept, which the retention of your plan decides, so serve the saved image from your own site when a page is shared for longer. Use it only for images that may be public.
Render once, not on every request
An identical request with a live key within 24 hours is answered from the deduplication cache at zero units, so a second deploy on the same day costs nothing (test keys cost nothing anyway and are never deduplicated). After that the image is rendered again: store the image or its URL with the post and render when the post changes, never inside the page handler, because a social scraper will not wait for a render. See deduplication.
One template, many sizes
Open Graph wants 1200 × 630, and other networks want other frames. Put the size in the request’s settings.image instead of the template, and the same markup renders every format you need.
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 Open Graph image API.
More Java guides
FAQ
- Does the image count as a render?
- Yes, one unit per image, like a one-page PDF. Test renders are free. See pricing.
- Can I use my own fonts?
- Yes: link a web font in the template’s head, which the renderer fetches and caches, or, from the Starter plan on, upload font files in the app under Fonts and name the family in your CSS. See fonts.
- Why is my text cut off?
- The frame is fixed, so a long headline has to give. The example truncates with
truncate: 70; a smaller font size or a two-line clamp in CSS works as well.