Files
Karan LokchandaniandKris Oei 58d8c4bfab feat(sdks): add protein lookup to all SDKs (#5722)
* feat(sdks): add protein lookup to the Python and JS SDKs

* fix(sdks): restore the research_docs header, split the notice sentence, reuse RESEARCH_METHODS

The research_docs module docstring keeps main's wording and line breaks except for the added lookup_protein and five to six. The README notice line becomes two sentences. The sync and async client method checks now loop over RESEARCH_METHODS, so they cover lookup_protein.

* fix(sdks): keep the API's error message and code on research request failures

* feat(sdks): add protein lookup to the PHP, Ruby and Elixir SDKs

Add lookupProtein (PHP), lookup_protein (Ruby) and lookup_protein (Elixir), which call GET /v2/search/research/proteins with protein and an optional organism. The Elixir method sits in the hand-written region beside the paper methods, and generate.exs lists its route so a regenerate from the public spec emits no second definition.

* test(sdks): cover the protein lookup query in Ruby and PHP, document notice

Each test checks the path and that protein, origin and organism (only when set) reach the query string. The PHP, Ruby and Elixir doc comments now say the response's notice is the UniProt credit and license to show with the results.

* feat(sdks): add protein lookup to the Go, Rust, Java and .NET SDKs

* fix(sdks): rename GoTerm to ProteinGoTerm and cover origin and not_found

Rename the GO term type to ProteinGoTerm in the Go, Rust, Java and .NET
SDKs to match the other protein types and the JS SDK. Document that
notice carries UniProt's credit and CC BY 4.0 license. The protein tests
now assert that origin is sent, and the Rust test decodes a not_found
body.

---------

Co-authored-by: Kris Oei <oei.kris71@gmail.com>
2026-11-16 11:47:40 -08:00
..

Firecrawl Java SDK

Java SDK for Firecrawl, the context API for AI agents. Search, scrape, parse, crawl, map, and interact with the web, and run Agent and Monitor jobs.

Prerequisites

Before using the Java SDK, ensure you have the following installed:

Java Development Kit (JDK)

  • Required: Java 11 or later

  • Installation (macOS):

    brew install openjdk
    

    Then add Java to your PATH:

    echo 'export PATH="/opt/homebrew/opt/openjdk/bin:$PATH"' >> ~/.zshrc
    source ~/.zshrc
    
  • Installation (Linux):

    # Ubuntu/Debian
    sudo apt-get update
    sudo apt-get install openjdk-11-jdk
    
    # Fedora/RHEL
    sudo dnf install java-11-openjdk-devel
    
  • Verify Installation:

    java --version
    

Gradle (for building from source)

  • Required: Gradle 8+

  • Installation (macOS):

    brew install gradle
    
  • Installation (Linux):

    # Ubuntu/Debian
    sudo apt-get install gradle
    
    # Or use SDKMAN
    curl -s "https://get.sdkman.io" | bash
    sdk install gradle
    
  • Verify Installation:

    gradle --version
    

API Key Setup

  1. Get your API key from Firecrawl Dashboard

  2. Set it as an environment variable:

    export FIRECRAWL_API_KEY="fc-your-api-key-here"
    
  3. Or add it to your shell profile for persistence:

    # For Zsh (macOS/Linux)
    echo 'export FIRECRAWL_API_KEY="fc-your-api-key-here"' >> ~/.zshrc
    source ~/.zshrc
    
    # For Bash
    echo 'export FIRECRAWL_API_KEY="fc-your-api-key-here"' >> ~/.bashrc
    source ~/.bashrc
    

Installation

Gradle (Kotlin DSL)

implementation("com.firecrawl:firecrawl-java:1.18.9")

Gradle (Groovy)

implementation 'com.firecrawl:firecrawl-java:1.18.9'

Maven

<dependency>
    <groupId>com.firecrawl</groupId>
    <artifactId>firecrawl-java</artifactId>
    <version>1.18.9</version>
</dependency>

Quick Start

import com.firecrawl.client.FirecrawlClient;
import com.firecrawl.models.*;
import java.util.List;

// Create client with explicit API key
FirecrawlClient client = FirecrawlClient.builder()
    .apiKey("fc-your-api-key")
    .build();

// Scrape a page
Document doc = client.scrape("https://example.com",
    ScrapeOptions.builder()
        .formats(List.of("markdown"))
        .build());

System.out.println(doc.getMarkdown());

Or create a client from the environment variable:

// export FIRECRAWL_API_KEY=fc-your-api-key
FirecrawlClient client = FirecrawlClient.fromEnv();

API Reference

Scrape

Scrape a single URL and get the content in various formats.

Document doc = client.scrape("https://example.com",
    ScrapeOptions.builder()
        .formats(List.of("markdown", "html"))
        .onlyMainContent(true)
        .waitFor(5000)
        .build());

System.out.println(doc.getMarkdown());
System.out.println(doc.getMetadata().get("title"));

Video Extraction

Use the video format on supported video URLs, including YouTube and TikTok. The returned video field is a signed URL to the extracted video file.

Document doc = client.scrape("https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    ScrapeOptions.builder()
        .formats(List.of("video"))
        .build());

System.out.println(doc.getVideo());

Parse Uploaded Files

Upload local files (html, pdf, docx, etc.) via multipart form data and parse them synchronously. Parse options intentionally exclude browser-only features like change tracking, screenshot, branding, audio, video, actions, waitFor, location, and mobile.

ParseFile file = ParseFile.builder()
    .filename("upload.html")
    .content("<!DOCTYPE html><html><body><h1>Java Parse</h1></body></html>".getBytes())
    .contentType("text/html")
    .build();

Document parsed = client.parse(file,
    ParseOptions.builder()
        .formats(List.of("markdown"))
        .build());

System.out.println(parsed.getMarkdown());

To see which upload types the API accepts, call getParseFormats(). Each entry has a format, a kind (document or image), its extensions and mimeTypes, and whether it is available on the current deployment (image formats need image OCR enabled).

import com.firecrawl.models.ParseFormat;

for (ParseFormat format : client.getParseFormats()) {
    System.out.println(format.getFormat() + " " + format.getKind()
        + " " + format.getExtensions() + " available=" + format.isAvailable());
}

JSON Extraction

import com.firecrawl.models.JsonFormat;

JsonFormat jsonFmt = JsonFormat.builder()
    .prompt("Extract the product name and price")
    .schema(Map.of(
        "type", "object",
        "properties", Map.of(
            "name", Map.of("type", "string"),
            "price", Map.of("type", "number")
        )
    ))
    .build();

Document doc = client.scrape("https://example.com/product",
    ScrapeOptions.builder()
        .formats(List.of(jsonFmt))
        .build());

System.out.println(doc.getJson());

Product Extraction

Use the product format to get structured product data (title, brand, and variants, each with their own price and availability) from product pages, available on the document's getProduct(). It is the deterministic counterpart to the LLM-powered json format.

Document doc = client.scrape("https://example.com/product",
    ScrapeOptions.builder()
        .formats(List.of("product"))
        .build());

System.out.println(doc.getProduct());

Menu Extraction

Use the menu format to get structured menu data (merchant profile plus ordered sections, each holding items with their own price, availability, and images) from restaurant and menu pages, available on the document's getMenu().

Document doc = client.scrape("https://example.com/menu",
    ScrapeOptions.builder()
        .formats(List.of("menu"))
        .build());

System.out.println(doc.getMenu());

Scrape-Bound Interactive Session

Run browser automation against the page context captured by a scrape job:

Document doc = client.scrape("https://example.com");
String scrapeId = String.valueOf(doc.getMetadata().get("scrapeId"));

BrowserExecuteResponse exec = client.interact(
    scrapeId,
    "console.log(await page.title());",
    "node",
    30
);

System.out.println(exec.getStdout());

BrowserDeleteResponse deleted = client.stopInteractiveBrowser(scrapeId);
System.out.println("Deleted: " + deleted.isSuccess());

Crawl

Crawl an entire website. The crawl() method polls until completion.

// Convenience method — polls until done
CrawlJob job = client.crawl("https://example.com",
    CrawlOptions.builder()
        .limit(50)
        .maxDiscoveryDepth(3)
        .scrapeOptions(ScrapeOptions.builder()
            .formats(List.of("markdown"))
            .build())
        .build());

for (Document doc : job.getData()) {
    System.out.println(doc.getMetadata().get("sourceURL"));
}

Async Crawl (manual polling)

CrawlResponse start = client.startCrawl("https://example.com",
    CrawlOptions.builder().limit(100).build());

System.out.println("Job started: " + start.getId());

// Poll manually
CrawlJob status;
do {
    try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; }
    status = client.getCrawlStatus(start.getId());
    System.out.println(status.getCompleted() + "/" + status.getTotal());
} while (!status.isDone());

Batch Scrape

Scrape multiple URLs in parallel.

BatchScrapeJob job = client.batchScrape(
    List.of("https://example.com", "https://example.org"),
    BatchScrapeOptions.builder()
        .options(ScrapeOptions.builder()
            .formats(List.of("markdown"))
            .build())
        .build());

for (Document doc : job.getData()) {
    System.out.println(doc.getMarkdown());
}

Map

Discover all URLs on a website.

MapData data = client.map("https://example.com",
    MapOptions.builder()
        .limit(100)
        .search("blog")
        .build());

for (Map<String, Object> link : data.getLinks()) {
    System.out.println(link.get("url") + " - " + link.get("title"));
}

Search the web and optionally scrape results.

SearchData results = client.search("firecrawl",
    SearchOptions.builder()
        .limit(10)
        .build());

if (results.getWeb() != null) {
    for (Map<String, Object> result : results.getWeb()) {
        System.out.println(result.get("title") + " — " + result.get("url"));
    }
}

Search public repositories, GitHub issues, merged pull requests, READMEs and code documentation. It replaces the research index GitHub search, which was removed after 2026-11-03.

import com.firecrawl.models.ResearchModels;

ResearchModels.DeveloperSearchOptions options = new ResearchModels.DeveloperSearchOptions();
options.k = 5;
options.types = List.of("issue", "pull_request");
options.repos = List.of("square/okhttp");

ResearchModels.DeveloperSearchResponse response =
    client.developerSearch("retry an http request with exponential backoff", options);

for (ResearchModels.DeveloperSearchResult result : response.results) {
    System.out.println(result.title + " " + result.url);
}

Agent

Run an AI-powered agent to research and extract data from the web.

AgentStatusResponse result = client.agent(
    AgentOptions.builder()
        .prompt("Find the pricing plans for Firecrawl and compare them")
        .build());

System.out.println(result.getData());

To let the agent use the Exchange (Alexandria) data providers connected to your team, pass exchange. toolkits pins up to 5 providers by slug; omit it to allow all of them.

AgentStatusResponse result = client.agent(
    AgentOptions.builder()
        .prompt("Find the head of engineering at example.com")
        .exchange(AgentExchangeOptions.builder()
            .enabled(true)
            .toolkits(List.of("provider-slug"))
            .build())
        .build());

if (result.getExchange() != null) {
    System.out.println("Paid provider calls: " + result.getExchange().getPaidCalls());
}

Usage & Metrics

ConcurrencyCheck conc = client.getConcurrency();
System.out.println("Concurrency: " + conc.getConcurrency() + "/" + conc.getMaxConcurrency());

CreditUsage credits = client.getCreditUsage();
System.out.println("Remaining credits: " + credits.getRemainingCredits());

Async Support

All methods have async variants that return CompletableFuture:

import java.util.concurrent.CompletableFuture;

CompletableFuture<Document> future = client.scrapeAsync(
    "https://example.com",
    ScrapeOptions.builder().formats(List.of("markdown")).build());

future.thenAccept(doc -> System.out.println(doc.getMarkdown()));

Error Handling

The SDK throws unchecked exceptions:

import com.firecrawl.errors.*;

try {
    Document doc = client.scrape("https://example.com");
} catch (AuthenticationException e) {
    // 401 — invalid API key
    System.err.println("Auth failed: " + e.getMessage());
} catch (RateLimitException e) {
    // 429 — too many requests
    System.err.println("Rate limited: " + e.getMessage());
} catch (JobTimeoutException e) {
    // Async job timed out
    System.err.println("Job " + e.getJobId() + " timed out after " + e.getTimeoutSeconds() + "s");
} catch (FirecrawlException e) {
    // All other API errors
    System.err.println("Error " + e.getStatusCode() + ": " + e.getMessage());
}

Configuration

FirecrawlClient client = FirecrawlClient.builder()
    .apiKey("fc-your-api-key")            // Required (or set FIRECRAWL_API_KEY env var)
    .apiUrl("https://api.firecrawl.dev")  // Optional (or set FIRECRAWL_API_URL env var)
    .timeoutMs(300_000)                   // HTTP timeout: 5 min default
    .maxRetries(3)                        // Auto-retries for transient failures
    .backoffFactor(0.5)                   // Exponential backoff factor (seconds)
    .asyncExecutor(myExecutor)            // Custom executor for async methods
    .build();

Building from Source

Clone and Build

# Clone the repository (if you haven't already)
git clone https://github.com/firecrawl/firecrawl.git
cd firecrawl/apps/java-sdk

# Build the project
gradle build

Generate JAR

gradle jar
# Output: build/libs/firecrawl-java-1.18.9.jar

Install Locally

gradle publishToMavenLocal
# Now available as: com.firecrawl:firecrawl-java:1.18.9 in local Maven repository

Running Tests

The SDK includes both unit tests and E2E integration tests.

Unit Tests (No API Key Required)

Unit tests verify SDK functionality without making actual API calls:

gradle test

E2E Integration Tests (API Key Required)

E2E tests make real API calls and require a valid API key. These tests will be skipped if FIRECRAWL_API_KEY is not set:

# Set your API key
export FIRECRAWL_API_KEY="fc-your-api-key-here"

# Run all tests including E2E
gradle test

Run Specific Tests

# Run only scrape tests
gradle test --tests "*testScrape*"

# Run only E2E tests
gradle test --tests "*E2E"

# Run specific test class
gradle test --tests "com.firecrawl.FirecrawlClientTest"

View Test Results

After running tests, view the detailed report:

open build/reports/tests/test/index.html  # macOS
xdg-open build/reports/tests/test/index.html  # Linux

Development Setup

If you're contributing to the SDK or testing local changes:

  1. Install Prerequisites (see Prerequisites section above)

  2. Set Environment Variables:

    export FIRECRAWL_API_KEY="fc-your-api-key"
    # Optional: use local API server
    export FIRECRAWL_API_URL="http://localhost:3002"
    
  3. Build and Test:

    gradle clean build test
    
  4. Make Changes and Retest:

    # Quick compilation check
    gradle compileJava
    
    # Run tests
    gradle test --tests "*testYourFeature*"