☕ Java Integration — Quick Start

Integrate SnapAPI into your Java application using OkHttp. Capture screenshots, generate PDFs, and extract web content. Works with Spring Boot, plain Java, and Android.

On This Page

Installation

Add OkHttp and Gson to your project:

// build.gradle
dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.12.0'
    implementation 'com.google.code.gson:gson:2.10.1'
}

For Maven:

<dependencies>
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.12.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.10.1</version>
    </dependency>
</dependencies>
💡 Tip: For Java 11+, you can also use the built-in java.net.http.HttpClient — see the HttpClient section below.

Take Screenshots

Basic Screenshot

import okhttp3.*;
import com.google.gson.JsonObject;
import java.io.File;
import java.io.FileOutputStream;

public class SnapAPIExample {
    private static final String API_KEY = System.getenv("SNAPAPI_KEY");
    private static final OkHttpClient client = new OkHttpClient();

    public static void main(String[] args) throws Exception {
        JsonObject json = new JsonObject();
        json.addProperty("url", "https://example.com");
        json.addProperty("format", "png");
        json.addProperty("width", 1280);
        json.addProperty("height", 800);

        RequestBody body = RequestBody.create(
            json.toString(),
            MediaType.parse("application/json")
        );

        Request request = new Request.Builder()
            .url("https://api.snapapi.pics/screenshot")
            .addHeader("Authorization", "Bearer " + API_KEY)
            .post(body)
            .build();

        try (Response response = client.newCall(request).execute()) {
            byte[] imageBytes = response.body().bytes();
            try (FileOutputStream fos = new FileOutputStream("screenshot.png")) {
                fos.write(imageBytes);
            }
            System.out.println("Screenshot saved!");
        }
    }
}

Screenshot with Options

JsonObject json = new JsonObject();
json.addProperty("url", "https://example.com");
json.addProperty("format", "webp");       // png, jpeg, webp, avif
json.addProperty("width", 1440);
json.addProperty("height", 900);
json.addProperty("fullPage", false);
json.addProperty("blockAds", true);        // Block advertisements
json.addProperty("blockCookies", true);    // Block cookie banners
json.addProperty("delay", 2000);           // Wait 2s before capture
json.addProperty("devicePreset", "iPhone15");
json.addProperty("css", "body { background: white; }");
json.addProperty("responseType", "url");   // Get hosted URL

Get Hosted URL

json.addProperty("responseType", "url");

try (Response response = client.newCall(request).execute()) {
    String responseBody = response.body().string();
    JsonObject result = new Gson().fromJson(responseBody, JsonObject.class);
    System.out.println(result.get("url").getAsString());
    // → https://cdn.snapapi.pics/screenshots/abc123.png
}

Generate PDFs

JsonObject margin = new JsonObject();
margin.addProperty("top", "20mm");
margin.addProperty("bottom", "20mm");
margin.addProperty("left", "15mm");
margin.addProperty("right", "15mm");

JsonObject json = new JsonObject();
json.addProperty("url", "https://example.com");
json.addProperty("format", "A4");
json.addProperty("printBackground", true);
json.add("margin", margin);

RequestBody body = RequestBody.create(
    json.toString(), MediaType.parse("application/json")
);

Request request = new Request.Builder()
    .url("https://api.snapapi.pics/pdf")
    .addHeader("Authorization", "Bearer " + API_KEY)
    .post(body)
    .build();

try (Response response = client.newCall(request).execute()) {
    byte[] pdfBytes = response.body().bytes();
    try (FileOutputStream fos = new FileOutputStream("page.pdf")) {
        fos.write(pdfBytes);
    }
}

PDF from HTML String

JsonObject json = new JsonObject();
json.addProperty("html", "<h1>Invoice #1234</h1><p>Total: $99.00</p>");
json.addProperty("format", "A4");
json.addProperty("printBackground", true);

Extract Content

JsonObject json = new JsonObject();
json.addProperty("url", "https://example.com/blog-post");
json.addProperty("format", "markdown");

Request request = new Request.Builder()
    .url("https://api.snapapi.pics/extract")
    .addHeader("Authorization", "Bearer " + API_KEY)
    .post(RequestBody.create(json.toString(), MediaType.parse("application/json")))
    .build();

try (Response response = client.newCall(request).execute()) {
    JsonObject result = new Gson().fromJson(response.body().string(), JsonObject.class);
    System.out.println(result.get("markdown").getAsString());
}

Record Videos

JsonObject json = new JsonObject();
json.addProperty("url", "https://example.com");
json.addProperty("duration", 5);
json.addProperty("width", 1280);
json.addProperty("height", 720);
json.addProperty("format", "mp4");

Request request = new Request.Builder()
    .url("https://api.snapapi.pics/video")
    .addHeader("Authorization", "Bearer " + API_KEY)
    .post(RequestBody.create(json.toString(), MediaType.parse("application/json")))
    .build();

try (Response response = client.newCall(request).execute()) {
    byte[] videoBytes = response.body().bytes();
    try (FileOutputStream fos = new FileOutputStream("recording.mp4")) {
        fos.write(videoBytes);
    }
}

Error Handling

try (Response response = client.newCall(request).execute()) {
    switch (response.code()) {
        case 200:
            byte[] data = response.body().bytes();
            // Process successful response
            break;
        case 401:
            System.err.println("Invalid API key");
            break;
        case 429:
            String retryAfter = response.header("Retry-After");
            System.err.println("Rate limited. Retry after " + retryAfter + "s");
            break;
        case 400:
            String error = response.body().string();
            System.err.println("Bad request: " + error);
            break;
        default:
            System.err.println("Error " + response.code() + ": " + response.body().string());
    }
}
⚠️ Rate Limits: Free tier: 200 requests/month. Starter: $19/mo. Pro: $79/mo. View plans.

Spring Boot Integration

import org.springframework.web.bind.annotation.*;
import org.springframework.http.*;

@RestController
@RequestMapping("/api")
public class ScreenshotController {

    private final OkHttpClient httpClient = new OkHttpClient();
    private final String apiKey = System.getenv("SNAPAPI_KEY");

    @GetMapping("/screenshot")
    public ResponseEntity<byte[]> screenshot(@RequestParam String url) throws Exception {
        JsonObject json = new JsonObject();
        json.addProperty("url", url);
        json.addProperty("format", "png");
        json.addProperty("width", 1280);

        Request request = new Request.Builder()
            .url("https://api.snapapi.pics/screenshot")
            .addHeader("Authorization", "Bearer " + apiKey)
            .post(RequestBody.create(json.toString(), MediaType.parse("application/json")))
            .build();

        try (Response response = httpClient.newCall(request).execute()) {
            byte[] imageBytes = response.body().bytes();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(org.springframework.http.MediaType.IMAGE_PNG);
            headers.setContentDisposition(
                ContentDisposition.attachment().filename("screenshot.png").build()
            );

            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        }
    }
}

Java 11+ HttpClient

If you prefer the built-in java.net.http.HttpClient (no dependencies needed):

import java.net.http.*;
import java.net.URI;

var httpClient = HttpClient.newHttpClient();

String jsonBody = """
    {
        "url": "https://example.com",
        "format": "png",
        "width": 1280,
        "height": 800
    }
    """;

var request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.snapapi.pics/screenshot"))
    .header("Authorization", "Bearer " + System.getenv("SNAPAPI_KEY"))
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
    .build();

var response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());

if (response.statusCode() == 200) {
    java.nio.file.Files.write(
        java.nio.file.Path.of("screenshot.png"),
        response.body()
    );
    System.out.println("Screenshot saved!");
}

Next Steps