Skip to main content

SDKs

Java SDK

kloakd-sdk for Java 21+ — one API for everything, full module coverage with async support

8 min read


Install

<dependency>
  <groupId>dev.kloakd</groupId>
  <artifactId>kloakd-sdk</artifactId>
  <version>0.7.0</version>
</dependency>

Gradle:

implementation 'dev.kloakd:kloakd-sdk:0.7.0'

Java 21+ | version 0.7.0 | stdlib HttpClient

Client

Kloakd client = Kloakd.builder()
    .apiKey(System.getenv("KLOAKD_API_KEY"))
    .organizationId(System.getenv("KLOAKD_ORG_ID"))
    .timeout(Duration.ofSeconds(100))   // the default; keep it above the API's 85 s hand-off
    .maxRetries(3)
    .build();

Quickstart — one call does everything

SiteCrawlResult result = client.crawl("https://example.com",
    CrawlOptions.builder()
        .maxPages(50)
        .extractSchema(Map.of("title", "css:h1", "content", "css:article"))
        .build());

for (CrawlPage page : result.pages()) {
    if (page.ok()) {
        System.out.println(page.url() + " → " + page.structuredData());
    }
}

That's it. crawl() internally:

  1. Discovers all pages on the site (Webgrph BFS)
  2. Fetches each page through the anti-bot engine, which works out per site what it takes (a browser, a residential exit, a challenge solver) — no forceBrowser needed
  3. Extracts structured data from each page if extractSchema is provided (Kolektr, using cached fetch artifacts — no second HTTP round-trip)

Per-page failures are caught and marked success: false — the crawl never aborts on a single page error.

Primary method

client.crawl()

SiteCrawlResult result = client.crawl("https://example.com",
    CrawlOptions.builder()
        .maxDepth(3)
        .maxPages(100)
        .extractSchema(Map.of("title", "css:h1", "price", "css:.price"))
        .build());

System.out.printf("Discovered: %d pages%n", result.totalPagesDiscovered());
System.out.printf("Fetched:    %d%n", result.pagesFetched());
System.out.printf("Failed:     %d%n", result.pagesFailed());

for (CrawlPage page : result.pages()) {
    if (page.ok()) {
        System.out.printf("  %s %s%n", page.url(), page.structuredData());
    } else {
        System.out.printf("  %s FAILED: %s%n", page.url(), page.error());
    }
}

Parameters

| Parameter | Type | Default | Description | |---|---|---|---| | url | String | required | Seed URL to start crawling from | | maxDepth | int | 3 with build() | Maximum BFS depth | | maxPages | int | 100 with build() | Maximum pages to crawl | | extractSchema | Map<String, ?> | null | {field: "css:selector"} (the css: prefix is optional), or a full spec with a fields list | | scope, budget, captureMode | | null | Passed to the crawl (crawl()) | | includeExternalLinks | boolean | false | Follow off-domain links | | sessionArtifactId | String | null | Reuse an authenticated session artifact (from Fetchyr) |

CrawlOptions.builder().build() fills an unset maxDepth or maxPages with 3 or 100. buildAsSet() leaves them unset: they are not sent, and the crawl runs to your plan's limits.

Returns: SiteCrawlResult

| Field | Type | Description | |---|---|---| | success | boolean | The crawl's own success | | url | String | Seed URL | | totalPagesDiscovered | int | Pages found during BFS | | pagesFetched | int | Pages successfully fetched | | pagesFailed | int | Pages that failed (included with success: false) | | pages | List<CrawlPage> | All pages with HTML and optional structured data | | crawlArtifactId | String | Artifact ID for the site hierarchy | | error | String | Error message if crawl failed entirely | | crawlId | String | The crawl's id | | status | String | The crawl's own status, including held_quota | | held | boolean | The crawl is held for quota (below) | | message | String | The API's note on the crawl's state, such as why it is held |

client.crawlStream() — streaming

crawlStream() returns a lazy Stream: each event is produced as the crawl reaches it.

client.crawlStream("https://example.com",
    CrawlOptions.builder()
        .maxPages(500)
        .extractSchema(Map.of("title", "css:h1"))
        .build())
    .forEach(event -> {
        switch (event.type()) {
            case "page_fetched" -> System.out.printf("[%d/%d] %s OK%n", event.page(), event.total(), event.url());
            case "page_failed" -> System.out.printf("[%d/%d] %s FAIL: %s%n", event.page(), event.total(), event.url(), event.error());
            case "crawl_complete" -> System.out.println("Done");
        }
    });

Event types

| Type | Description | |---|---| | discovery_complete | Discovery finished, fetch phase starting | | page_fetching | About to fetch page N of total | | page_fetched | Page fetched successfully | | page_failed | Page fetch failed (crawl continues) | | crawl_complete | All pages processed |

Low-level methods

Need fine-grained control? The individual modules are still available:

evadr().fetch()

FetchResult page = client.evadr().fetch("https://example.com");
System.out.printf("Status: %d%n", page.statusCode());   // a 202 hand-off is followed to the result
System.out.printf("Artifact ID: %s%n", page.artifactId());

webgrph().crawl()

// waits for the crawl and returns its pages
CrawlResult crawl = client.webgrph().crawl("https://example.com", 3, 100, false, null);
System.out.printf("%s: %d pages%n", crawl.crawlId(), crawl.pages().size());

kolektr().extract()

Map<String, Object> schemaSpec = Map.of("fields", List.of(
    Map.of("name", "title", "selector", "h1"),
    Map.of("name", "price", "selector", ".price")));
ExtractionResult result = client.kolektr().extract("https://example.com", schemaSpec, null, null, null);
for (var record : result.records()) {
    System.out.println(record);
}

One record per item

On a list page, put the repeated element's selector in the spec as item_selector; each match is one record, with the field selectors read inside it (rules):

Map<String, Object> schemaSpec = Map.of(
    "item_selector", "article.product_pod",
    "fields", List.of(
        Map.of("name", "title", "selector", "h3 a", "attribute", "title"),
        Map.of("name", "price", "selector", "p.price_color")));
ExtractionResult result = client.kolektr().extract("https://books.toscrape.com/", schemaSpec, null, null, null);
System.out.println(result.totalRecords());   // 20: one record per book

The spec map is sent as given, so this works with 0.5.0 and is documented for 0.6.0. Without item_selector the page is one record.

Artifact chaining

Pass artifact IDs between low-level methods to skip redundant work:

FetchResult page = client.evadr().fetch("https://example.com");

Map<String, Object> schemaSpec = Map.of("fields", List.of(Map.of("name", "title", "selector", "h1")));
ExtractionResult data = client.kolektr().extract("https://example.com", schemaSpec,
    page.artifactId(), null, null);

Error handling

try {
    SiteCrawlResult result = client.crawl("https://example.com", CrawlOptions.builder().build());
} catch (RateLimitException e) {
    System.out.printf("Retry after %ds%n", e.getRetryAfter());
} catch (QuotaExceededException | PaymentRequiredException e) {
    System.out.println("Billing: " + e.getMessage());
} catch (AuthenticationException e) {
    System.out.println("Invalid API key");
} catch (KloakdException e) {
    System.out.println(e.getMessage());
}

Advanced namespaces

client.skanyr()    // Site store: resources, APIs, snapshots, diff, graph, timeline, search
client.nexus()     // Strategy engine
client.parlyr()    // Natural language queries
client.fetchyr()   // Logins & authenticated scraping

Crawls: held, partial, continue

A crawl whose organisation ran out of allowance is held (held_quota), not failed, and resumes by itself. webgrph().crawl and webgrph().waitForCrawl return it at once with held() true and message() the server's text. client.crawl returns SiteCrawlResult with held(), crawlId(), status() and message().

A crawl that stopped early ends completed with isPartial() true. CrawlResult also has partialReason(), resumable(), pagesDiscovered(), pagesFetched(), pagesUnfetched() and errorCode().

CrawlResult crawl = client.webgrph().crawl("https://example.com");
if (crawl.held()) {
    System.out.println(crawl.message());              // held for quota; it resumes by itself
} else if (Boolean.TRUE.equals(crawl.resumable())) {
    client.webgrph().continueCrawl(crawl.crawlId());  // ApiException 409 when it cannot be continued
    crawl = client.webgrph().waitForCrawl(crawl.crawlId());
}

Login sessions

LoginSession login = client.fetchyr().startLoginSession("https://example.com/login");
System.out.println(login.status() + " " + login.next());

if (login.sessionArtifactId() != null) {
    SessionStatus status = client.fetchyr().getSession(login.sessionArtifactId());
    System.out.println(status.status() + " " + status.pauseReason());
    client.fetchyr().resumeSession(status.artifactId());   // ApiException 409 when the session is not paused
}

startLoginSession(targetUrl, LoginSessionOptions) takes method, cookies, userAgent and country through LoginSessionOptions.builder(). The flow is described under logins.

Batch jobs

BatchJob batch = client.createBatchJob(
    List.of("https://books.toscrape.com/catalogue/page-1.html",
            "https://books.toscrape.com/catalogue/page-2.html"),
    BatchJobOptions.builder()
        .entityType("products")
        .fields(List.of("title", "price"))
        .build());
batch = client.getBatchJob(batch.id());
System.out.printf("%s %d/%d%n", batch.status(), batch.completedItems(), batch.totalItems());

client.pauseBatchJob(batch.id());
client.resumeBatchJob(batch.id());
client.cancelBatchJob(batch.id());

BatchJobsPage page = client.listBatchJobs(1, 20);            // page.total(), page.batchJobs()
BatchJobResults results = client.getBatchJobResults(batch.id(), 100, 0);
for (BatchJobItem item : results.results()) {
    System.out.println(item.url() + " " + item.status() + " " + item.extractedData());
}

SavedExport saved = client.downloadBatchJob(batch.id(), Path.of("batch.csv"), "csv");

BatchJobOptions.builder() has extractionConfig, crawlId, entityType and fields; createBatchJob(urls) sends the URLs alone. A BatchJob has id(), name(), status(), totalItems(), completedItems(), createdAt() and message(). A control the batch's state does not allow throws ApiException with getStatusCode() 409 and getCode() invalid_batch_transition. A create or resume that could not be queued throws ApiException with 503 and getCode() dispatch_failed. The limit on batches at once throws ConcurrencyLimitException; its getActiveCrawls() holds the API's active_batches. The rules are on the batch jobs page.

Unified scrape

UnifiedScrapeResult scrape = client.unifiedScrape("https://books.toscrape.com/",
    UnifiedScrapeOptions.builder()
        .prompt("extract all book titles and prices")
        .build());
if ("failed".equals(scrape.status())) {          // success() is true even then: check status()
    System.out.println("the scrape failed");
} else if (scrape.authRequired()) {
    System.out.println("login needed: " + scrape.discoveryId());
} else {
    UnifiedScrapeStatus job = client.getUnifiedScrape(scrape.jobId());
    System.out.println(job.status() + " " + job.result());
}

UnifiedScrapeOptions.builder() has prompt, mode, schema, options, context, constraints, sessionArtifactId, pollInterval and pollTimeout; a 202 hand-off is followed. See unified scrape for the failed and login answers.

Crawl-extract jobs and exports

webgrph() has startCrawlExtract, crawlExtract, getCrawlExtract, waitForCrawlExtract, getCrawlExtractResults, crawlExtractAllResults, getCrawlExtractPages, exportCrawlExtract, downloadCrawlExtract and cancelCrawlExtract for the crawl-extract job. The job, status, results and pages come back as maps.

SavedExport.crawl() (ExportCrawl) is read from the response's X-Crawl-* headers: status(), isPartial(), partialReason(), pagesDiscovered(), pagesFetched(), pagesUnfetched(), cancelled() and rootUnfetched(). It is null for a batch export.

Changes in 0.7.0

  • nexus().execute(...) and nexus().knowledge(...), with NexusExecuteResult and NexusKnowledgeResult.

Each PageNode gains fetchStatus().

Next steps

Was this page helpful?