Java Screenshot API Tutorial: HttpClient, Spring Boot, Jobs and Webhooks
A Java guide to the Screenshotly API that starts with a dependency-free HttpClient call and ends with a Spring Boot service that queues durable jobs and verifies signed webhooks.
This guide shows how to call the Screenshotly API from Java 17 and later. It starts with a single request that uses only the JDK, then builds a small client you can reuse: typed errors, retries that respect Retry-After, streaming to disk, durable async jobs, webhook signature checks and Spring Boot 3 wiring.
Every snippet below was compiled and run against an offline stub that validates requests with Screenshotly's real request schema and plan rules. Nothing here depends on an unpublished SDK.
Reference docs for the Java APIs used here: the java.net.http package, Jackson databind, Spring Boot and Caffeine. For the full parameter list see the screenshot API reference.
What you need
- Java 17 or later. The code uses text blocks, records, switch expressions and
HexFormat. - An API key from Dashboard → API Tokens. Store it in an environment variable or secret manager, never in source.
- A plan that covers the features you call. The Free plan includes 100 captures in total at 5 requests per minute, with PNG, JPEG and WebP output. See pricing for Basic, Growth and Scale.
How the API works
| Endpoint | POST https://screenshotly.app/api/screenshot |
| Auth | x-api-key: YOUR_KEY header (Authorization: Bearer YOUR_KEY also works) |
| Body | JSON. Only url is required; format defaults to png |
| Success | 200 with the image or PDF bytes as the body |
| Errors | JSON {"error": "...", "message": "..."} with a 4xx or 5xx status |
| Slow work | POST https://screenshotly.app/api/jobs (Basic+) returns 202 with a job ID |
Failed captures don't count against your quota. Only successful ones do.
Quick start: one request with the JDK
No dependencies. Save this as QuickStart.java and run java QuickStart.java with SCREENSHOTLY_API_KEY set.
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.time.Duration;
public class QuickStart {
private static final String API_URL = "https://screenshotly.app/api/screenshot";
public static void main(String[] args) throws Exception {
String apiKey = System.getenv("SCREENSHOTLY_API_KEY");
if (apiKey == null || apiKey.isBlank()) {
throw new IllegalStateException("Set SCREENSHOTLY_API_KEY first");
}
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
// A fixed body keeps the first request dependency-free. Use a JSON
// library (next section) as soon as any value comes from user input.
String body = """
{"url": "https://example.com", "device": "desktop", "format": "png"}
""";
HttpRequest request = HttpRequest.newBuilder(URI.create(API_URL))
.header("x-api-key", apiKey)
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(60))
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
if (response.statusCode() != 200) {
// Errors are JSON: {"error": "...", "message": "..."}
throw new IllegalStateException("HTTP " + response.statusCode() + ": "
+ new String(response.body(), java.nio.charset.StandardCharsets.UTF_8));
}
Files.write(Path.of("screenshot.png"), response.body());
System.out.println("Saved screenshot.png (" + response.body().length + " bytes)");
}
}
The fixed JSON body is fine for a first test. As soon as the URL or any option comes from user input, build the body with a JSON library so values are escaped correctly.
A reusable client with Jackson
Add Jackson. Spring Boot projects already have it.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>
The request model
The API's schema is strict: unknown keys and explicit null values are rejected with 400 Invalid request data. @JsonInclude(NON_NULL) makes unset options disappear from the JSON. Field names are camelCase, and width and height sit at the top level. There is no viewport object.
package com.example.screenshotly;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.List;
import java.util.Map;
/**
* Request body for POST /api/screenshot and POST /api/jobs.
* The API rejects unknown keys and null values, so unset fields must be
* omitted (NON_NULL) rather than sent as null.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public final class CaptureRequest {
public final String url;
public String format = "png"; // png | jpeg | webp; pdf/html need Basic+
public String device; // desktop | laptop | tablet | mobile
public Integer width; // 320–3840
public Integer height; // 240–3840
public Boolean fullPage;
public Integer quality; // 0–100 (jpeg/webp)
public Integer delay; // ms, 0–10000
public String waitForSelector;
public Boolean waitForNetworkIdle;
public String selector;
public Boolean blockAds;
public Boolean darkMode;
public Double deviceScaleFactor; // 1–3
public String mockup; // Growth+
public AiRemoval aiRemoval; // Growth+
public List<String> hideSelectors; // Growth+
public Storage storage; // Basic+
public Webhook webhook; // Basic+
public CaptureRequest(String url) { this.url = url; }
public CaptureRequest format(String v) { format = v; return this; }
public CaptureRequest device(String v) { device = v; return this; }
public CaptureRequest size(int w, int h) { width = w; height = h; return this; }
public CaptureRequest fullPage(boolean v) { fullPage = v; return this; }
public CaptureRequest quality(int v) { quality = v; return this; }
public CaptureRequest delay(int ms) { delay = ms; return this; }
public CaptureRequest waitForSelector(String v) { waitForSelector = v; return this; }
public CaptureRequest waitForNetworkIdle(boolean v) { waitForNetworkIdle = v; return this; }
public CaptureRequest selector(String v) { selector = v; return this; }
public CaptureRequest blockAds(boolean v) { blockAds = v; return this; }
public CaptureRequest darkMode(boolean v) { darkMode = v; return this; }
public CaptureRequest deviceScaleFactor(double v) { deviceScaleFactor = v; return this; }
public CaptureRequest mockup(String v) { mockup = v; return this; }
public CaptureRequest aiRemoval(String... types) { aiRemoval = new AiRemoval(true, List.of(types), null); return this; }
public CaptureRequest hideSelectors(String... v) { hideSelectors = List.of(v); return this; }
public CaptureRequest storeResult() { storage = new Storage(true); return this; }
public CaptureRequest webhook(String url, String secret, Map<String, String> headers) {
webhook = new Webhook(url, null, headers, secret);
return this;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
public record AiRemoval(Boolean enabled, List<String> types, Double confidence) {}
public record Storage(boolean enabled) {}
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Webhook(String url, String method, Map<String, String> headers, String secret) {}
}
The model covers the options most Java services use. The full list, including clip, scroll, cookies, headers, javascript, userAgent, timezone and geolocation, is in the API reference. Add fields the same way, as nullable wrapper types.
Typed errors
package com.example.screenshotly;
import java.time.Duration;
/** A non-2xx response from Screenshotly, mapped from its JSON error body. */
public class ScreenshotlyException extends RuntimeException {
private final int status;
private final String error;
private final String minimumPlan;
private final Duration retryAfter;
public ScreenshotlyException(int status, String error, String message, String minimumPlan, Duration retryAfter) {
super("HTTP " + status + " " + error + (message == null ? "" : ": " + message));
this.status = status;
this.error = error;
this.minimumPlan = minimumPlan;
this.retryAfter = retryAfter;
}
public int status() { return status; }
public String error() { return error; }
/** Set on 403 "Plan upgrade required" responses, e.g. "basic" or "growth". */
public String minimumPlan() { return minimumPlan; }
/** Parsed Retry-After header on 429 responses, otherwise null. */
public Duration retryAfter() { return retryAfter; }
public boolean isRetryable() {
return status == 429 || status == 500 || status == 502 || status == 503 || status == 504;
}
}
The client
package com.example.screenshotly;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ThreadLocalRandom;
public class ScreenshotlyClient {
private static final int MAX_ATTEMPTS = 3;
// A 429 caused by an exhausted monthly quota carries a Retry-After that can
// be days long. Only wait for short, per-minute throttles.
private static final Duration MAX_RETRY_AFTER = Duration.ofSeconds(60);
private final HttpClient http;
private final ObjectMapper json;
private final URI baseUri;
private final String apiKey;
public ScreenshotlyClient(String apiKey) {
this(URI.create("https://screenshotly.app"), apiKey);
}
/** The base URI is configurable so tests can point at a local stub. */
public ScreenshotlyClient(URI baseUri, String apiKey) {
if (apiKey == null || apiKey.isBlank()) throw new IllegalArgumentException("API key is required");
this.baseUri = baseUri;
this.apiKey = apiKey;
this.json = new ObjectMapper();
this.http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NEVER)
.build();
}
/** Synchronous capture; returns the image/PDF bytes. */
public byte[] capture(CaptureRequest request) throws IOException, InterruptedException {
try (InputStream body = send("/api/screenshot", request, null)) {
return body.readAllBytes();
}
}
/** Synchronous capture streamed straight to disk without buffering in memory. */
public Path captureToFile(CaptureRequest request, Path target) throws IOException, InterruptedException {
try (InputStream body = send("/api/screenshot", request, null)) {
Files.copy(body, target, StandardCopyOption.REPLACE_EXISTING);
return target;
}
}
/** Queues a durable job (Basic+). Reusing an idempotency key returns the original job. */
public JsonNode submitJob(CaptureRequest request, String idempotencyKey) throws IOException, InterruptedException {
try (InputStream body = send("/api/jobs", request, idempotencyKey)) {
return json.readTree(body); // {"id", "status", "replayed", "statusUrl"}
}
}
public JsonNode getJob(String jobId) throws IOException, InterruptedException {
HttpRequest req = HttpRequest.newBuilder(baseUri.resolve("/api/jobs/" + jobId))
.header("x-api-key", apiKey)
.timeout(Duration.ofSeconds(15))
.GET()
.build();
HttpResponse<InputStream> res = http.send(req, HttpResponse.BodyHandlers.ofInputStream());
if (res.statusCode() != 200) throw toException(res);
try (InputStream body = res.body()) {
return json.readTree(body);
}
}
/** Polls until the job is SUCCEEDED, FAILED or CANCELED, or the deadline passes. */
public JsonNode waitForJob(String jobId, Duration timeout) throws IOException, InterruptedException {
Instant deadline = Instant.now().plus(timeout);
Duration pause = Duration.ofSeconds(2);
while (true) {
JsonNode job = getJob(jobId);
String status = job.path("status").asText();
if (status.equals("SUCCEEDED") || status.equals("FAILED") || status.equals("CANCELED")) return job;
if (Instant.now().plus(pause).isAfter(deadline)) {
throw new IOException("Job " + jobId + " still " + status + " after " + timeout);
}
Thread.sleep(pause.toMillis());
pause = pause.multipliedBy(2).compareTo(Duration.ofSeconds(15)) > 0 ? Duration.ofSeconds(15) : pause.multipliedBy(2);
}
}
/**
* Downloads a job's short-lived resultUrl. The URL is already signed, so
* the API key is deliberately NOT sent: it may point at object storage.
*/
public Path download(String resultUrl, Path target) throws IOException, InterruptedException {
HttpRequest req = HttpRequest.newBuilder(URI.create(resultUrl)).timeout(Duration.ofSeconds(60)).GET().build();
HttpResponse<Path> res = http.send(req, HttpResponse.BodyHandlers.ofFile(target));
if (res.statusCode() != 200) {
Files.deleteIfExists(target);
throw new IOException("Download failed with HTTP " + res.statusCode() + "; read the job again for a fresh URL");
}
return res.body();
}
private InputStream send(String path, CaptureRequest request, String idempotencyKey)
throws IOException, InterruptedException {
byte[] payload = json.writeValueAsBytes(request);
HttpRequest.Builder builder = HttpRequest.newBuilder(baseUri.resolve(path))
.header("x-api-key", apiKey)
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(60)) // navigation alone may take up to 30 s
.POST(HttpRequest.BodyPublishers.ofByteArray(payload));
if (idempotencyKey != null) builder.header("Idempotency-Key", idempotencyKey);
HttpRequest httpRequest = builder.build();
for (int attempt = 1; ; attempt++) {
try {
HttpResponse<InputStream> res = http.send(httpRequest, HttpResponse.BodyHandlers.ofInputStream());
int status = res.statusCode();
if (status >= 200 && status < 300) return res.body();
ScreenshotlyException error = toException(res);
if (!error.isRetryable() || attempt == MAX_ATTEMPTS) throw error;
Duration wait = error.retryAfter() != null ? error.retryAfter() : backoff(attempt);
if (wait.compareTo(MAX_RETRY_AFTER) > 0) throw error; // quota exhausted: fail fast
Thread.sleep(wait.toMillis());
} catch (HttpTimeoutException e) {
if (attempt == MAX_ATTEMPTS) throw e;
Thread.sleep(backoff(attempt).toMillis());
}
}
}
private static Duration backoff(int attempt) {
long base = 1000L << (attempt - 1); // 1 s, 2 s, 4 s ...
return Duration.ofMillis(base + ThreadLocalRandom.current().nextLong(250));
}
private ScreenshotlyException toException(HttpResponse<InputStream> res) throws IOException {
JsonNode body;
try (InputStream in = res.body()) {
body = json.readTree(in);
} catch (IOException e) {
body = json.createObjectNode();
}
Duration retryAfter = res.headers().firstValue("Retry-After")
.map(v -> Duration.ofSeconds(Long.parseLong(v.trim())))
.orElse(null);
return new ScreenshotlyException(
res.statusCode(),
body.path("error").asText("Unknown error"),
body.hasNonNull("message") ? body.get("message").asText() : null,
body.hasNonNull("minimumPlan") ? body.get("minimumPlan").asText() : null,
retryAfter);
}
}
A few details are deliberate:
- One
HttpClientper application. It pools connections and is thread-safe. Don't build one per request. - 60-second request timeout. A capture can take tens of seconds: page navigation alone may take up to 30 seconds, plus any
delayorwaitForSelectoryou ask for. For pages that need longer, use the async jobs API below rather than raising the timeout. - Retries only where they help.
429,500,502,503and504are retried up to three attempts.400,401,403and413are not, because the request, key or plan needs fixing. - Retry-After is capped. A
429from the per-minute limit carries aRetry-Afterof a few seconds. A429because the monthly quota is used up carries one that can be days long. The client waits for the first kind and fails fast on the second. - Timeouts are retried with care. A request that timed out on your side may still have completed on the server and used a capture. If that matters, use a job with an
Idempotency-Key.
Using it
ScreenshotlyClient screenshotly = new ScreenshotlyClient(System.getenv("SCREENSHOTLY_API_KEY"));
// Full-page desktop capture, written straight to disk
screenshotly.captureToFile(
new CaptureRequest("https://example.com")
.device("desktop")
.fullPage(true)
.waitForNetworkIdle(true)
.blockAds(true),
Path.of("home.png"));
// Exact viewport, retina density, WebP
byte[] hero = screenshotly.capture(
new CaptureRequest("https://example.com/pricing")
.size(1440, 900)
.deviceScaleFactor(2)
.format("webp")
.quality(80));
// Growth plan and above: device frame plus AI cleanup of overlays
byte[] marketing = screenshotly.capture(
new CaptureRequest("https://example.com")
.mockup("macbook-pro")
.aiRemoval("cookie-banner", "chat-widget"));
Options and plan requirements
| Option | Plan | Notes |
|---|---|---|
format: png, jpeg, webp |
All | quality 0–100 |
device, width/height, fullPage, deviceScaleFactor |
All | Width 320–3840, height 240–3840, scale 1–3 |
delay, waitForSelector, waitForNetworkIdle, selector, blockAds, darkMode |
All | delay up to 10,000 ms |
format: pdf, html |
Basic+ | PDF is A4 with 1 cm margins; other paper sizes aren't available |
storage, webhook, headers, cookies, cache, stealth |
Basic+ | |
mockup, aiRemoval, hideSelectors, javascript, scroll, geolocation |
Growth+ | Mockups: browser-light, browser-dark, browser-minimal, iphone-14, ipad-pro, macbook-pro |
format: webm, proxyRegion |
Scale | WebM videoDuration 1–15 s; regions us, eu, apac |
Calling a gated option on a lower plan returns 403 with "error": "Plan upgrade required" and minimumPlan. The exception above exposes it as minimumPlan().
Error reference
| Status | Meaning | What to do |
|---|---|---|
400 |
Invalid JSON, a schema violation, or a URL that resolves to a private address | Fix the request; the details or message field says what failed |
401 |
Missing or invalid API key | Check the key and header; don't retry |
403 |
Plan upgrade required (see minimumPlan), or the account email is not verified yet |
Change the request or plan, or verify the email; don't retry |
413 |
Request body larger than 64 KB | Trim large javascript, headers or cookies values |
429 |
Per-minute limit (short Retry-After) or monthly quota used up (long Retry-After) |
Wait and retry only for the short case |
500 |
The capture failed, for example because the target page errored | Retry once or twice with backoff; failed captures are not billed |
503 |
The capture proxy is unavailable | Retry with backoff |
Per-minute limits are 5 requests on Free, 40 on Basic, 80 on Growth and 200 on Scale. Successful responses include X-RateLimit-Limit and X-RateLimit-Remaining for your monthly quota.
Spring Boot 3 integration
Register the client as a bean and bind the key from configuration.
screenshotly:
api-key: ${SCREENSHOTLY_API_KEY}
base-url: https://screenshotly.app
webhook-secret: ${SCREENSHOTLY_WEBHOOK_SECRET}
webhook-url: https://your-app.example.com/webhooks/screenshotly
package com.example.screenshotly;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "screenshotly")
public record ScreenshotlyProperties(String apiKey, String baseUrl, String webhookSecret, String webhookUrl) {}
package com.example.screenshotly;
import java.net.URI;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(ScreenshotlyProperties.class)
public class ScreenshotlyConfig {
@Bean
ScreenshotlyClient screenshotlyClient(ScreenshotlyProperties props) {
return new ScreenshotlyClient(URI.create(props.baseUrl()), props.apiKey());
}
@Bean
WebhookVerifier webhookVerifier(ScreenshotlyProperties props) {
return new WebhookVerifier(props.webhookSecret());
}
}
Queue captures instead of blocking a request thread
A controller that captures inline holds a servlet thread for the whole capture. On Basic and higher, hand the work to Screenshotly's job queue and return 202 straight away. The webhook headers you set are sent back with the delivery, which is how you match a delivery to your own record.
package com.example.screenshotly;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ScreenshotController {
private final ScreenshotlyClient screenshotly;
private final ScreenshotlyProperties props;
public ScreenshotController(ScreenshotlyClient screenshotly, ScreenshotlyProperties props) {
this.screenshotly = screenshotly;
this.props = props;
}
/** Queues the capture with Screenshotly and returns immediately. */
@PostMapping("/reports/{reportId}/snapshot")
public ResponseEntity<Map<String, Object>> snapshot(@PathVariable String reportId)
throws IOException, InterruptedException {
CaptureRequest request = new CaptureRequest("https://app.example.com/reports/" + reportId)
.format("pdf") // Basic+; fixed A4 with 1 cm margins
.waitForNetworkIdle(true)
.webhook(props.webhookUrl(), props.webhookSecret(),
Map.of("X-Report-Id", reportId)); // echoed back so you can correlate the delivery
// Same key for the same report: a client retry returns the original job.
JsonNode job = screenshotly.submitJob(request, "report-" + reportId);
return ResponseEntity.status(HttpStatus.ACCEPTED)
.body(Map.of("jobId", job.get("id").asText(), "status", job.get("status").asText()));
}
@org.springframework.web.bind.annotation.ExceptionHandler(ScreenshotlyException.class)
public ResponseEntity<Map<String, Object>> onScreenshotlyError(ScreenshotlyException e) {
// Do not echo upstream auth failures to your own callers.
HttpStatus status = e.status() == 400 ? HttpStatus.BAD_REQUEST : HttpStatus.BAD_GATEWAY;
return ResponseEntity.status(status).body(Map.of("error", e.error()));
}
}
Verify webhook signatures
When you set webhook.secret, each delivery carries X-Screenshotly-Signature: sha256=<hex>, an HMAC-SHA256 of the raw request body. Compute it over the exact bytes you received and compare in constant time.
package com.example.screenshotly;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/** Verifies X-Screenshotly-Signature: sha256=<hex HMAC-SHA256 of the raw body>. */
public final class WebhookVerifier {
private final byte[] secret;
public WebhookVerifier(String secret) {
this.secret = secret.getBytes(StandardCharsets.UTF_8);
}
public boolean isValid(byte[] rawBody, String signatureHeader) {
if (signatureHeader == null || !signatureHeader.startsWith("sha256=")) return false;
byte[] received;
try {
received = HexFormat.of().parseHex(signatureHeader.substring("sha256=".length()));
} catch (IllegalArgumentException e) {
return false;
}
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret, "HmacSHA256"));
byte[] expected = mac.doFinal(rawBody);
return MessageDigest.isEqual(expected, received); // constant-time comparison
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
}
package com.example.screenshotly;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WebhookController {
private final WebhookVerifier verifier;
private final ObjectMapper json = new ObjectMapper();
public WebhookController(WebhookVerifier verifier) {
this.verifier = verifier;
}
@PostMapping("/webhooks/screenshotly")
public ResponseEntity<Void> receive(
@RequestBody byte[] rawBody, // raw bytes: re-serialized JSON would not match the signature
@RequestHeader(value = "X-Screenshotly-Signature", required = false) String signature,
@RequestHeader(value = "X-Report-Id", required = false) String reportId) throws IOException {
if (!verifier.isValid(rawBody, signature)) {
return ResponseEntity.status(401).build();
}
JsonNode event = json.readTree(rawBody);
switch (event.path("event").asText()) {
case "screenshot.completed" -> {
String fileUrl = event.path("data").path("storageUrl").asText(); // signed, short-lived
// Hand off to a queue/executor and download there; respond fast.
}
case "screenshot.failed" -> {
String reason = event.path("data").path("error").asText();
}
default -> { }
}
return ResponseEntity.noContent().build();
}
}
The payload looks like this:
{
"event": "screenshot.completed",
"timestamp": "2026-11-13T08:00:00.000Z",
"data": {
"url": "https://app.example.com/reports/42",
"format": "pdf",
"size": 1234,
"storageUrl": "https://screenshotly.app/api/assets/...",
"duration": 4200
}
}
Failed jobs send "event": "screenshot.failed" with data.error. Screenshotly makes up to five delivery attempts if your endpoint doesn't answer with a 2xx, and it does not follow redirects. Make the handler idempotent so a repeated delivery is harmless, and do slow work such as downloading storageUrl after you respond.
Async jobs without a webhook
If you'd rather poll, the client's submitJob, waitForJob and download methods cover it. Jobs need Basic or higher.
JsonNode job = screenshotly.submitJob(
new CaptureRequest("https://example.com/annual-report").format("pdf"),
"annual-report-2026"); // retries with the same key return the same job
JsonNode done = screenshotly.waitForJob(job.get("id").asText(), Duration.ofMinutes(5));
if (done.get("status").asText().equals("SUCCEEDED")) {
screenshotly.download(done.get("resultUrl").asText(), Path.of("annual-report.pdf"));
}
GET /api/jobs/{id} returns QUEUED, RUNNING, SUCCEEDED, FAILED or CANCELED. The resultUrl is signed and short-lived. If it expires, read the job again for a fresh one. The client never sends your API key to that URL, because it may point at object storage. Screenshotly makes up to three attempts at a job before it reports FAILED.
On Growth and Scale, POST /api/jobs/batch queues up to 20 captures in one call:
{
"captures": [
{ "url": "https://example.com", "format": "png" },
{ "url": "https://example.com/pricing", "format": "pdf" }
]
}
The response lists one job per capture. With an Idempotency-Key, each capture gets the key plus its index (key:0, key:1, …). See the async jobs reference.
Batch captures with bounded concurrency
For synchronous captures, cap the number in flight so you stay under your per-minute limit. A fixed thread pool does that:
package com.example.screenshotly;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class BatchCapture {
public record Result(String url, Path file, String error) {
public boolean ok() { return error == null; }
}
/** Captures URLs with at most {@code concurrency} requests in flight. */
public static List<Result> captureAll(ScreenshotlyClient client, List<String> urls, Path dir, int concurrency)
throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(concurrency);
try {
List<Future<Result>> futures = new ArrayList<>();
for (int i = 0; i < urls.size(); i++) {
String url = urls.get(i);
Path target = dir.resolve("capture-" + i + ".png");
futures.add(pool.submit(() -> {
try {
return new Result(url, client.captureToFile(new CaptureRequest(url), target), null);
} catch (Exception e) {
return new Result(url, null, e.getMessage());
}
}));
}
List<Result> results = new ArrayList<>();
for (Future<Result> f : futures) {
try {
results.add(f.get());
} catch (java.util.concurrent.ExecutionException e) {
throw new IllegalStateException(e.getCause());
}
}
return results;
} finally {
pool.shutdown();
}
}
}
Size the pool from your plan, not your CPU count. Four concurrent captures can easily exceed Free's 5 requests per minute. The client's 429 handling absorbs short bursts, but a pool of one or two is the right size on Free.
Caching
There are two levels:
- API-side (Basic+): send
"cache": trueand optionally"cacheTtl"(60–86,400 seconds, default 3,600) to let Screenshotly reuse a recent result. - In-process: for repeated requests inside one JVM, cache the bytes with Caffeine. The key below is the serialized request, so two requests with different options never collide.
package com.example.screenshotly;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
public class CachedScreenshots {
private final ScreenshotlyClient client;
private final ObjectMapper json = new ObjectMapper();
private final Cache<String, byte[]> cache = Caffeine.newBuilder()
.maximumWeight(200L * 1024 * 1024) // ~200 MB of images
.weigher((String key, byte[] value) -> value.length)
.expireAfterWrite(Duration.ofHours(1))
.build();
public CachedScreenshots(ScreenshotlyClient client) {
this.client = client;
}
public byte[] capture(CaptureRequest request) {
return cache.get(cacheKey(request), key -> {
try {
return client.capture(request);
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
});
}
// The serialized request covers every option, so different options never collide.
private String cacheKey(CaptureRequest request) {
try {
return json.writeValueAsString(request);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
Testing
You don't need a mocking library to test the client. The JDK includes a small HTTP server, which lets the test check the exact JSON that goes over the wire:
package com.example.screenshotly;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ScreenshotlyClientTest {
private HttpServer server;
private final List<String> bodies = new CopyOnWriteArrayList<>();
private final AtomicInteger calls = new AtomicInteger();
@BeforeEach
void start() throws Exception {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/api/screenshot", exchange -> {
bodies.add(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
assertThat(exchange.getRequestHeaders().getFirst("x-api-key")).isEqualTo("test-key");
if (calls.incrementAndGet() == 1) { // first call is throttled
exchange.getResponseHeaders().add("Retry-After", "1");
byte[] err = "{\"error\":\"Rate limit exceeded\"}".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(429, err.length);
exchange.getResponseBody().write(err);
} else {
byte[] png = {(byte) 0x89, 'P', 'N', 'G'};
exchange.getResponseHeaders().add("Content-Type", "image/png");
exchange.sendResponseHeaders(200, png.length);
exchange.getResponseBody().write(png);
}
exchange.close();
});
server.start();
}
@AfterEach
void stop() { server.stop(0); }
private ScreenshotlyClient client() {
return new ScreenshotlyClient(URI.create("http://127.0.0.1:" + server.getAddress().getPort()), "test-key");
}
@Test
void retriesThrottledRequestAndOmitsUnsetFields() throws Exception {
byte[] image = client().capture(new CaptureRequest("https://example.com").size(1280, 800));
assertThat(image).startsWith((byte) 0x89);
assertThat(calls.get()).isEqualTo(2);
assertThat(bodies.get(0))
.isEqualTo("{\"url\":\"https://example.com\",\"format\":\"png\",\"width\":1280,\"height\":800}");
}
@Test
void webhookSignatureIsCheckedInConstantTime() {
WebhookVerifier verifier = new WebhookVerifier("whsec_test");
byte[] body = "{\"event\":\"screenshot.completed\"}".getBytes(StandardCharsets.UTF_8);
String good = "sha256=" + "595255b9b9f3ded02941a21a8ca07a418e784abc584ce3d5dbe59e646ca25cf7";
assertThat(verifier.isValid(body, good)).isTrue();
assertThat(verifier.isValid(body, "sha256=00")).isFalse();
assertThat(verifier.isValid(body, null)).isFalse();
}
@Test
void nonRetryableErrorsSurfaceImmediately() {
server.removeContext("/api/screenshot");
server.createContext("/api/screenshot", exchange -> {
calls.incrementAndGet();
byte[] err = "{\"error\":\"Plan upgrade required\",\"message\":\"PDF output requires the basic plan or higher\",\"minimumPlan\":\"basic\"}"
.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(403, err.length);
exchange.getResponseBody().write(err);
exchange.close();
});
assertThatThrownBy(() -> client().capture(new CaptureRequest("https://example.com").format("pdf")))
.isInstanceOfSatisfying(ScreenshotlyException.class, e -> {
assertThat(e.status()).isEqualTo(403);
assertThat(e.minimumPlan()).isEqualTo("basic");
});
assertThat(calls.get()).isEqualTo(1);
}
}
The expected signature in the webhook test is the HMAC-SHA256 of that body with the secret whsec_test. You can reproduce it with printf '%s' '{"event":"screenshot.completed"}' | openssl dgst -sha256 -hmac whsec_test.
Production checklist
- The API key comes from the environment or a secret manager, and it never reaches a browser.
- One shared
HttpClient, 10 s connect timeout, 60 s request timeout. - Unset options are omitted (
NON_NULL), not sent asnull. - Retries cover
429(shortRetry-Afteronly) and5xx, never400,401,403or413. - Large captures are streamed to disk or storage, not held in memory.
- Slow pages, PDFs and batches go through
/api/jobswith anIdempotency-Key. - Webhook handlers verify the signature over raw bytes, respond quickly and are idempotent.
- Concurrency is sized to your plan's per-minute limit.
Conclusion
For Java, the JDK's HttpClient and Jackson are all you need. Start with the one-file quick start, move to the reusable client when you need typed errors and retries, and switch to jobs and webhooks once captures leave the request path.
Ready to add screenshots to your Java app?
Get your free API key →. The Free plan includes 100 captures to test with.
See also:
About the Author

Asad Ali
CTO at ZTABS and the developer behind Screenshotly. Writes about screenshot automation, API design, and building reliable SaaS backends with Next.js, Node.js, and TypeScript.
Credentials: CTO at ZTABS, full-stack developer, builder and maintainer of Screenshotly and its official JavaScript and Python clients
Frequently Asked Questions
Should I use Java's built-in HttpClient or OkHttp?
The JDK HttpClient (java.net.http, Java 11+) covers everything the Screenshotly API needs: HTTPS, timeouts, streaming bodies and a GET for job polling. This guide uses it with Jackson for JSON. OkHttp or Spring's RestClient work equally well if they are already in your dependency graph; the request contract is the same.
Why does the API reject my request with 'Invalid request data'?
The request schema is strict. Unknown keys are rejected, and so are explicit nulls for optional fields. Configure Jackson with @JsonInclude(NON_NULL) so unset options are omitted, use camelCase names (fullPage, waitForNetworkIdle) and send width and height at the top level. There is no nested viewport object.
Where does the capture call belong in a Spring Boot service?
Not inline in a request handler for anything slow. A capture can take tens of seconds (page navigation alone may take up to 30 seconds), which ties up a servlet thread. On Basic and higher, queue the capture with POST /api/jobs and let Screenshotly call your webhook when it finishes. On Free, run synchronous captures on a bounded executor or a message consumer.
How should I set timeouts in Java?
Set connectTimeout on the HttpClient builder (10 seconds is plenty) and a per-request timeout of about 60 seconds on synchronous captures. Use the async jobs endpoint instead of longer timeouts for slow pages, PDFs and batches.
What happens when I call a feature my plan doesn't include?
The API returns HTTP 403 with error 'Plan upgrade required' and a minimumPlan field such as basic or growth. PDF and HTML output, webhooks, stored results, custom headers and cookies need Basic. Device mockups, AI element removal, custom JavaScript and hideSelectors need Growth.
Ready to capture your first screenshot?
Get started with 100 free screenshots. No credit card required.