Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

feat(sdks): next cursor pagination (#2067)

Rafael Miller815963890f9a
diff --git a/apps/js-sdk/example_pagination.ts b/apps/js-sdk/example_pagination.ts
new file mode 100644
index 000000000..c66bdf227
--- /dev/null
+++ b/apps/js-sdk/example_pagination.ts
@@ -0,0 +1,72 @@
+import { config } from "dotenv";
+import { Firecrawl } from "./firecrawl/src/index";
+
+config();
+
+async function main() {
+ const apiKey = process.env.FIRECRAWL_API_KEY || "fc-YOUR_API_KEY";
+ const firecrawl = new Firecrawl({ apiKey });
+
+ // --- Crawl examples ---
+
+ // Method 1: Simple crawl - automatically waits for completion and returns all results
+ // Use this when you want all the data and don't need to control pagination
+ const crawlAll = await firecrawl.crawl("https://docs.firecrawl.dev", { limit: 5 });
+ console.log("crawl auto (default):", crawlAll.status, "docs:", crawlAll.data.length, "next:", crawlAll.next);
+
+ // Method 2: Manual crawl with pagination control
+ // Use this when you need to control how many pages to fetch or want to process results incrementally
+ const crawlStart = await firecrawl.startCrawl("https://docs.firecrawl.dev", { limit: 5 });
+ const crawlJobId = crawlStart.id;
+
+ // Get just the first page of results (useful for large crawls where you want to process incrementally)
+ const crawlSingle = await firecrawl.getCrawlStatus(crawlJobId, { autoPaginate: false });
+ console.log("crawl single page:", crawlSingle.status, "docs:", crawlSingle.data.length, "next:", crawlSingle.next);
+
+ // Get multiple pages with custom limits (useful for controlling memory usage or processing time)
+ const crawlLimited = await firecrawl.getCrawlStatus(crawlJobId, {
+ autoPaginate: true,
+ maxPages: 2, // Only fetch 2 pages maximum
+ maxResults: 50, // Only fetch 50 results maximum
+ maxWaitTime: 15, // Spend at most 15 seconds fetching additional pages
+ });
+ console.log("crawl limited:", crawlLimited.status, "docs:", crawlLimited.data.length, "next:", crawlLimited.next);
+
+ // --- Batch scrape examples ---
+
+ // Method 1: Simple batch scrape - automatically waits for completion and returns all results
+ // Use this when you want all the data from multiple URLs and don't need to control pagination
+ const batchAll = await firecrawl.batchScrape([
+ "https://docs.firecrawl.dev",
+ "https://firecrawl.dev",
+ ], { options: { formats: ["markdown"] } });
+ console.log("batch auto (default):", batchAll.status, "docs:", batchAll.data.length, "next:", batchAll.next);
+
+ // Method 2: Manual batch scrape with pagination control
+ // Use this when you need to control how many pages to fetch or want to process results incrementally
+ const batchStart = await firecrawl.startBatchScrape([
+ "https://docs.firecrawl.dev",
+ "https://firecrawl.dev",
+ ], { options: { formats: ["markdown"] } });
+ const batchJobId = batchStart.id;
+
+ // Get just the first page of results
+ const batchSingle = await firecrawl.getBatchScrapeStatus(batchJobId, { autoPaginate: false });
+ console.log("batch single page:", batchSingle.status, "docs:", batchSingle.data.length, "next:", batchSingle.next);
+
+ // Get multiple pages with custom limits
+ const batchLimited = await firecrawl.getBatchScrapeStatus(batchJobId, {
+ autoPaginate: true,
+ maxPages: 2, // Only fetch 2 pages maximum
+ maxResults: 100, // Only fetch 100 results maximum
+ maxWaitTime: 20, // Spend at most 20 seconds fetching additional pages
+ });
+ console.log("batch limited:", batchLimited.status, "docs:", batchLimited.data.length, "next:", batchLimited.next);
+}
+
+main().catch((e) => {
+ console.error(e);
+ process.exit(1);
+});
+
+
diff --git a/apps/js-sdk/firecrawl/package.json b/apps/js-sdk/firecrawl/package.json
index 75ed8e80f..f9abd453c 100644
--- a/apps/js-sdk/firecrawl/package.json
+++ b/apps/js-sdk/firecrawl/package.json
@@ -1,6 +1,6 @@
{
"name": "@mendable/firecrawl-js",
- "version": "3.3.0",
+ "version": "4.0.0",
"description": "JavaScript SDK for Firecrawl API",
"main": "dist/index.js",
"types": "dist/index.d.ts",
diff --git a/apps/js-sdk/firecrawl/src/__tests__/unit/v2/pagination.test.ts b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/pagination.test.ts
new file mode 100644
index 000000000..20e2afe42
--- /dev/null
+++ b/apps/js-sdk/firecrawl/src/__tests__/unit/v2/pagination.test.ts
@@ -0,0 +1,112 @@
+import { describe, test, expect, jest } from "@jest/globals";
+import { getCrawlStatus } from "../../../v2/methods/crawl";
+import { getBatchScrapeStatus } from "../../../v2/methods/batch";
+
+describe("JS SDK v2 pagination", () => {
+ function makeHttp(getImpl: (url: string) => any) {
+ return { get: jest.fn(async (u: string) => getImpl(u)) } as any;
+ }
+
+ test("crawl: autoPaginate=false returns next", async () => {
+ const first = { status: 200, data: { success: true, status: "completed", completed: 1, total: 2, next: "https://api/next", data: [{ markdown: "a" }] } };
+ const http = makeHttp(() => first);
+ const res = await getCrawlStatus(http, "job1", { autoPaginate: false });
+ expect(res.data.length).toBe(1);
+ expect(res.next).toBe("https://api/next");
+ });
+
+ test("crawl: default autoPaginate aggregates and nulls next", async () => {
+ const first = { status: 200, data: { success: true, status: "completed", completed: 1, total: 3, next: "https://api/n1", data: [{ markdown: "a" }] } };
+ const second = { status: 200, data: { success: true, next: "https://api/n2", data: [{ markdown: "b" }] } };
+ const third = { status: 200, data: { success: true, next: null, data: [{ markdown: "c" }] } };
+ const http = makeHttp((url) => {
+ if (url.includes("/v2/crawl/")) return first;
+ if (url.endsWith("n1")) return second;
+ return third;
+ });
+ const res = await getCrawlStatus(http, "job1");
+ expect(res.data.length).toBe(3);
+ expect(res.next).toBeNull();
+ });
+
+ test("crawl: respects maxPages and maxResults", async () => {
+ const first = { status: 200, data: { success: true, status: "completed", completed: 1, total: 10, next: "https://api/n1", data: [{ markdown: "a" }] } };
+ const page = (n: number) => ({ status: 200, data: { success: true, next: n < 3 ? `https://api/n${n + 1}` : null, data: [{ markdown: `p${n}` }] } });
+ const http = makeHttp((url) => {
+ if (url.includes("/v2/crawl/")) return first;
+ if (url.endsWith("n1")) return page(1);
+ if (url.endsWith("n2")) return page(2);
+ return page(3);
+ });
+ const res = await getCrawlStatus(http, "job1", { autoPaginate: true, maxPages: 2, maxResults: 2 });
+ expect(res.data.length).toBe(2);
+ });
+
+ test("batch: default autoPaginate aggregates and nulls next", async () => {
+ const first = { status: 200, data: { success: true, status: "completed", completed: 1, total: 3, next: "https://api/b1", data: [{ markdown: "a" }] } };
+ const second = { status: 200, data: { success: true, next: "https://api/b2", data: [{ markdown: "b" }] } };
+ const third = { status: 200, data: { success: true, next: null, data: [{ markdown: "c" }] } };
+ const http = makeHttp((url) => {
+ if (url.includes("/v2/batch/scrape/")) return first;
+ if (url.endsWith("b1")) return second;
+ return third;
+ });
+ const res = await getBatchScrapeStatus(http, "jobB");
+ expect(res.data.length).toBe(3);
+ expect(res.next).toBeNull();
+ });
+
+ test("batch: autoPaginate=false returns next", async () => {
+ const first = { status: 200, data: { success: true, status: "completed", completed: 1, total: 2, next: "https://api/nextBatch", data: [{ markdown: "a" }] } };
+ const http = makeHttp(() => first);
+ const res = await getBatchScrapeStatus(http, "jobB", { autoPaginate: false });
+ expect(res.data.length).toBe(1);
+ expect(res.next).toBe("https://api/nextBatch");
+ });
+
+ test("crawl: maxWaitTime stops pagination after first page", async () => {
+ const first = { status: 200, data: { success: true, status: "completed", completed: 1, total: 5, next: "https://api/n1", data: [{ markdown: "a" }] } };
+ const p1 = { status: 200, data: { success: true, next: "https://api/n2", data: [{ markdown: "b" }] } };
+ const http: any = makeHttp((url: string) => {
+ if (url.includes("/v2/crawl/")) return first;
+ if (url.endsWith("n1")) return p1;
+ return { status: 200, data: { success: true, next: null, data: [{ markdown: "c" }] } };
+ });
+ const nowSpy = jest.spyOn(Date, "now");
+ try {
+ nowSpy
+ .mockImplementationOnce(() => 0) // started
+ .mockImplementationOnce(() => 0) // first loop check
+ .mockImplementationOnce(() => 3000); // second loop check > maxWaitTime
+ const res = await getCrawlStatus(http, "jobC", { autoPaginate: true, maxWaitTime: 1 });
+ expect(res.data.length).toBe(2); // initial + first page
+ expect((http.get as jest.Mock).mock.calls.length).toBe(2); // initial + n1 only
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
+ test("batch: maxWaitTime stops pagination after first page", async () => {
+ const first = { status: 200, data: { success: true, status: "completed", completed: 1, total: 5, next: "https://api/b1", data: [{ markdown: "a" }] } };
+ const p1 = { status: 200, data: { success: true, next: "https://api/b2", data: [{ markdown: "b" }] } };
+ const http: any = makeHttp((url: string) => {
+ if (url.includes("/v2/batch/scrape/")) return first;
+ if (url.endsWith("b1")) return p1;
+ return { status: 200, data: { success: true, next: null, data: [{ markdown: "c" }] } };
+ });
+ const nowSpy = jest.spyOn(Date, "now");
+ try {
+ nowSpy
+ .mockImplementationOnce(() => 0) // started
+ .mockImplementationOnce(() => 0) // first loop check
+ .mockImplementationOnce(() => 3000); // second loop check > maxWaitTime
+ const res = await getBatchScrapeStatus(http, "jobB", { autoPaginate: true, maxWaitTime: 1 });
+ expect(res.data.length).toBe(2);
+ expect((http.get as jest.Mock).mock.calls.length).toBe(2);
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+});
+
+
diff --git a/apps/js-sdk/firecrawl/src/v2/client.ts b/apps/js-sdk/firecrawl/src/v2/client.ts
index 7a76ca266..0adce61ba 100644
--- a/apps/js-sdk/firecrawl/src/v2/client.ts
+++ b/apps/js-sdk/firecrawl/src/v2/client.ts
@@ -36,6 +36,7 @@ import type {
ExtractResponse,
CrawlOptions,
BatchScrapeOptions,
+ PaginationConfig,
} from "./types";
import { Watcher } from "./watcher";
import type { WatcherOptions } from "./watcher";
@@ -145,8 +146,8 @@ export class FirecrawlClient {
* Get the status and partial data of a crawl job.
* @param jobId Crawl job id.
*/
- async getCrawlStatus(jobId: string): Promise<CrawlJob> {
- return getCrawlStatus(this.http, jobId);
+ async getCrawlStatus(jobId: string, pagination?: PaginationConfig): Promise<CrawlJob> {
+ return getCrawlStatus(this.http, jobId, pagination);
}
/**
* Cancel a crawl job.
@@ -201,8 +202,8 @@ export class FirecrawlClient {
* Get the status and partial data of a batch scrape job.
* @param jobId Batch job id.
*/
- async getBatchScrapeStatus(jobId: string): Promise<BatchScrapeJob> {
- return getBatchScrapeStatus(this.http, jobId);
+ async getBatchScrapeStatus(jobId: string, pagination?: PaginationConfig): Promise<BatchScrapeJob> {
+ return getBatchScrapeStatus(this.http, jobId, pagination);
}
/**
* Retrieve batch scrape errors and robots.txt blocks.
diff --git a/apps/js-sdk/firecrawl/src/v2/methods/batch.ts b/apps/js-sdk/firecrawl/src/v2/methods/batch.ts
index b80ea5305..b919b3ad1 100644
--- a/apps/js-sdk/firecrawl/src/v2/methods/batch.ts
+++ b/apps/js-sdk/firecrawl/src/v2/methods/batch.ts
@@ -4,9 +4,11 @@ import {
type CrawlErrorsResponse,
type Document,
type BatchScrapeOptions,
+ type PaginationConfig,
} from "../types";
import { HttpClient } from "../utils/httpClient";
import { ensureValidScrapeOptions } from "../utils/validation";
+import { fetchAllPages } from "../utils/pagination";
import { normalizeAxiosError, throwForBadResponse } from "../utils/errorHandler";
export async function startBatchScrape(
@@ -47,19 +49,38 @@ export async function startBatchScrape(
}
}
-export async function getBatchScrapeStatus(http: HttpClient, jobId: string): Promise<BatchScrapeJob> {
+export async function getBatchScrapeStatus(
+ http: HttpClient,
+ jobId: string,
+ pagination?: PaginationConfig
+): Promise<BatchScrapeJob> {
try {
const res = await http.get<{ success: boolean; status: BatchScrapeJob["status"]; completed?: number; total?: number; creditsUsed?: number; expiresAt?: string; next?: string | null; data?: Document[] }>(`/v2/batch/scrape/${jobId}`);
if (res.status !== 200 || !res.data?.success) throwForBadResponse(res, "get batch scrape status");
const body = res.data;
+ const initialDocs = (body.data || []) as Document[];
+ const auto = pagination?.autoPaginate ?? true;
+ if (!auto || !body.next) {
+ return {
+ status: body.status,
+ completed: body.completed ?? 0,
+ total: body.total ?? 0,
+ creditsUsed: body.creditsUsed,
+ expiresAt: body.expiresAt,
+ next: body.next ?? null,
+ data: initialDocs,
+ };
+ }
+
+ const aggregated = await fetchAllPages(http, body.next, initialDocs, pagination);
return {
status: body.status,
completed: body.completed ?? 0,
total: body.total ?? 0,
creditsUsed: body.creditsUsed,
expiresAt: body.expiresAt,
- next: body.next ?? null,
- data: (body.data || []) as Document[],
+ next: null,
+ data: aggregated,
};
} catch (err: any) {
if (err?.isAxiosError) return normalizeAxiosError(err, "get batch scrape status");
@@ -115,5 +136,4 @@ export function chunkUrls(urls: string[], chunkSize = 100): string[][] {
const chunks: string[][] = [];
for (let i = 0; i < urls.length; i += chunkSize) chunks.push(urls.slice(i, i + chunkSize));
return chunks;
-}
-
+}
\ No newline at end of file
diff --git a/apps/js-sdk/firecrawl/src/v2/methods/crawl.ts b/apps/js-sdk/firecrawl/src/v2/methods/crawl.ts
index d1eb68206..f84fa4e03 100644
--- a/apps/js-sdk/firecrawl/src/v2/methods/crawl.ts
+++ b/apps/js-sdk/firecrawl/src/v2/methods/crawl.ts
@@ -5,10 +5,13 @@ import {
type CrawlResponse,
type Document,
type CrawlOptions,
+ type PaginationConfig,
} from "../types";
import { HttpClient } from "../utils/httpClient";
import { ensureValidScrapeOptions } from "../utils/validation";
import { normalizeAxiosError, throwForBadResponse } from "../utils/errorHandler";
+import type { HttpClient as _Http } from "../utils/httpClient";
+import { fetchAllPages } from "../utils/pagination";
export type CrawlRequest = CrawlOptions & {
url: string;
@@ -52,21 +55,42 @@ export async function startCrawl(http: HttpClient, request: CrawlRequest): Promi
}
}
-export async function getCrawlStatus(http: HttpClient, jobId: string): Promise<CrawlJob> {
+export async function getCrawlStatus(
+ http: HttpClient,
+ jobId: string,
+ pagination?: PaginationConfig
+): Promise<CrawlJob> {
try {
const res = await http.get<{ success: boolean; status: CrawlJob["status"]; completed?: number; total?: number; creditsUsed?: number; expiresAt?: string; next?: string | null; data?: Document[] }>(`/v2/crawl/${jobId}`);
if (res.status !== 200 || !res.data?.success) {
throwForBadResponse(res, "get crawl status");
}
const body = res.data;
+ const initialDocs = (body.data || []) as Document[];
+
+ const auto = pagination?.autoPaginate ?? true;
+ if (!auto || !body.next) {
+ return {
+ status: body.status,
+ completed: body.completed ?? 0,
+ total: body.total ?? 0,
+ creditsUsed: body.creditsUsed,
+ expiresAt: body.expiresAt,
+ next: body.next ?? null,
+ data: initialDocs,
+ };
+ }
+
+ const aggregated = await fetchAllPages(http, body.next, initialDocs, pagination);
+
return {
status: body.status,
completed: body.completed ?? 0,
total: body.total ?? 0,
creditsUsed: body.creditsUsed,
expiresAt: body.expiresAt,
- next: body.next ?? null,
- data: (body.data || []) as Document[],
+ next: null,
+ data: aggregated,
};
} catch (err: any) {
if (err?.isAxiosError) return normalizeAxiosError(err, "get crawl status");
@@ -140,5 +164,4 @@ export async function crawlParamsPreview(http: HttpClient, url: string, prompt:
if (err?.isAxiosError) return normalizeAxiosError(err, "crawl params preview");
throw err;
}
-}
-
+}
\ No newline at end of file
diff --git a/apps/js-sdk/firecrawl/src/v2/types.ts b/apps/js-sdk/firecrawl/src/v2/types.ts
index 7ee12ac5b..56d83cfd6 100644
--- a/apps/js-sdk/firecrawl/src/v2/types.ts
+++ b/apps/js-sdk/firecrawl/src/v2/types.ts
@@ -189,6 +189,18 @@ export interface Document {
changeTracking?: Record<string, unknown>;
}
+// Pagination configuration for auto-fetching pages from v2 endpoints that return a `next` URL
+export interface PaginationConfig {
+ /** When true (default), automatically follow `next` links and aggregate all documents. */
+ autoPaginate?: boolean;
+ /** Maximum number of additional pages to fetch after the first response. */
+ maxPages?: number;
+ /** Maximum total number of documents to return across all pages. */
+ maxResults?: number;
+ /** Maximum time to spend fetching additional pages (in seconds). */
+ maxWaitTime?: number;
+}
+
export interface SearchResultWeb {
url: string;
title?: string;
diff --git a/apps/js-sdk/firecrawl/src/v2/utils/pagination.ts b/apps/js-sdk/firecrawl/src/v2/utils/pagination.ts
new file mode 100644
index 000000000..4c54d1271
--- /dev/null
+++ b/apps/js-sdk/firecrawl/src/v2/utils/pagination.ts
@@ -0,0 +1,45 @@
+import type { HttpClient } from "../utils/httpClient";
+import type { Document, PaginationConfig } from "../types";
+
+/**
+ * Shared helper to follow `next` cursors and aggregate documents with limits.
+ */
+export async function fetchAllPages(
+ http: HttpClient,
+ nextUrl: string,
+ initial: Document[],
+ pagination?: PaginationConfig
+): Promise<Document[]> {
+ const docs = initial.slice();
+ let current: string | null = nextUrl;
+ let pageCount = 0;
+ const maxPages = pagination?.maxPages ?? undefined;
+ const maxResults = pagination?.maxResults ?? undefined;
+ const maxWaitTime = pagination?.maxWaitTime ?? undefined;
+ const started = Date.now();
+
+ while (current) {
+ if (maxPages != null && pageCount >= maxPages) break;
+ if (maxWaitTime != null && (Date.now() - started) / 1000 > maxWaitTime) break;
+
+ let payload: { success: boolean; next?: string | null; data?: Document[] } | null = null;
+ try {
+ const res = await http.get<{ success: boolean; next?: string | null; data?: Document[] }>(current);
+ payload = res.data;
+ } catch {
+ break; // axios rejects on non-2xx; stop pagination gracefully
+ }
+ if (!payload?.success) break;
+
+ for (const d of payload.data || []) {
+ if (maxResults != null && docs.length >= maxResults) break;
+ docs.push(d as Document);
+ }
+ if (maxResults != null && docs.length >= maxResults) break;
+ current = (payload.next ?? null) as string | null;
+ pageCount += 1;
+ }
+ return docs;
+}
+
+
diff --git a/apps/js-sdk/package-lock.json b/apps/js-sdk/package-lock.json
index adc6781d0..a0ce659f9 100644
--- a/apps/js-sdk/package-lock.json
+++ b/apps/js-sdk/package-lock.json
@@ -18,6 +18,7 @@
"zod": "^3.23.8"
},
"devDependencies": {
+ "@types/node": "^24.3.0",
"tsx": "^4.9.3"
}
},
@@ -531,12 +532,12 @@
"integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA=="
},
"node_modules/@types/node": {
- "version": "20.14.11",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.11.tgz",
- "integrity": "sha512-kprQpL8MMeszbz6ojB5/tU8PLN4kesnN8Gjzw349rDlNgsSzg90lAVj3llK99Dh7JON+t9AuscPPFW6mPbTnSA==",
- "peer": true,
+ "version": "24.3.0",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.3.0.tgz",
+ "integrity": "sha512-aPTXCrfwnDLj4VvXrm+UUCQjNEvJgNA8s5F1cvwQU+3KNltTOkBm1j30uNLyqqPNe7gE3KFzImYoZEfLhp4Yow==",
+ "license": "MIT",
"dependencies": {
- "undici-types": "~5.26.4"
+ "undici-types": "~7.10.0"
}
},
"node_modules/acorn": {
@@ -1068,10 +1069,10 @@
"integrity": "sha512-dFSOFBKV6uwaloBCCUhxlD3Pr/P1a/tJdcmPrTXCHlEFD3faj0mztjcGn6VBAhQ0/Bdy8K3VWrrqwbt/ffsYsg=="
},
"node_modules/undici-types": {
- "version": "5.26.5",
- "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
- "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
- "peer": true
+ "version": "7.10.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.10.0.tgz",
+ "integrity": "sha512-t5Fy/nfn+14LuOc2KNYg75vZqClpAiqscVvMygNnlsHBFpSXdJaYtXMcdNLpl/Qvc3P2cB3s6lOV51nqsFq4ag==",
+ "license": "MIT"
},
"node_modules/uuid": {
"version": "10.0.0",
diff --git a/apps/js-sdk/package.json b/apps/js-sdk/package.json
index 1e9c95534..4d3e32cd9 100644
--- a/apps/js-sdk/package.json
+++ b/apps/js-sdk/package.json
@@ -20,6 +20,7 @@
"zod": "^3.23.8"
},
"devDependencies": {
+ "@types/node": "^24.3.0",
"tsx": "^4.9.3"
}
}
diff --git a/apps/python-sdk/example_pagination.py b/apps/python-sdk/example_pagination.py
new file mode 100644
index 000000000..106d578ca
--- /dev/null
+++ b/apps/python-sdk/example_pagination.py
@@ -0,0 +1,99 @@
+"""
+Example demonstrating pagination functionality in Firecrawl v2 SDK.
+
+This example shows how to use the new pagination features for both crawl and batch scrape operations.
+"""
+
+from firecrawl import Firecrawl
+from firecrawl.v2.types import PaginationConfig
+
+# Initialize the client
+firecrawl = Firecrawl(api_key="your-api-key")
+
+# Example 1: Simple crawl - automatically waits for completion and returns all results
+# Use this when you want all the data and don't need to control pagination
+print("=== Example 1: Simple crawl (default) ===")
+crawl_result = firecrawl.crawl("https://example.com", limit=100)
+print(f"Total documents fetched: {len(crawl_result.data)}")
+print(f"Next URL: {crawl_result.next}") # Should be None since auto-pagination is enabled
+
+# Example 2: Manual crawl with pagination control
+# Use this when you need to control how many pages to fetch or want to process results incrementally
+print("\n=== Example 2: Manual crawl with pagination control ===")
+crawl_job = firecrawl.start_crawl("https://example.com", limit=100)
+
+# Get just the first page of results (useful for large crawls where you want to process incrementally)
+pagination_config = PaginationConfig(auto_paginate=False)
+status = firecrawl.get_crawl_status(crawl_job.id, pagination_config=pagination_config)
+print(f"Documents from first page: {len(status.data)}")
+print(f"Next URL: {status.next}") # Will show the next page URL
+
+# Example 3: Limited pagination - fetch only 3 pages
+# Useful for controlling memory usage or processing time
+print("\n=== Example 3: Limited pagination ===")
+pagination_config = PaginationConfig(max_pages=3)
+status = firecrawl.get_crawl_status(crawl_job.id, pagination_config=pagination_config)
+print(f"Documents from first 3 pages: {len(status.data)}")
+
+# Example 4: Result-limited pagination - stop after 50 results
+# Useful when you only need a specific number of results
+print("\n=== Example 4: Result-limited pagination ===")
+pagination_config = PaginationConfig(max_results=50)
+status = firecrawl.get_crawl_status(crawl_job.id, pagination_config=pagination_config)
+print(f"Documents (max 50): {len(status.data)}")
+
+# Example 5: Time-limited pagination - stop after 30 seconds
+# Useful for controlling processing time in time-sensitive applications
+print("\n=== Example 5: Time-limited pagination ===")
+pagination_config = PaginationConfig(max_wait_time=30)
+status = firecrawl.get_crawl_status(crawl_job.id, pagination_config=pagination_config)
+print(f"Documents fetched within 30 seconds: {len(status.data)}")
+
+# Example 6: Combined pagination limits
+# Useful for fine-grained control over resource usage
+print("\n=== Example 6: Combined limits ===")
+pagination_config = PaginationConfig(
+ max_pages=5, # Only fetch 5 pages maximum
+ max_results=100, # Only fetch 100 results maximum
+ max_wait_time=60 # Spend at most 60 seconds fetching additional pages
+)
+status = firecrawl.get_crawl_status(crawl_job.id, pagination_config=pagination_config)
+print(f"Documents with combined limits: {len(status.data)}")
+
+# Example 7: Simple batch scrape - automatically waits for completion and returns all results
+# Use this when you want all the data from multiple URLs and don't need to control pagination
+print("\n=== Example 7: Simple batch scrape (default) ===")
+urls = ["https://example1.com", "https://example2.com", "https://example3.com"]
+batch_result = firecrawl.batch_scrape(urls)
+print(f"Batch scrape documents: {len(batch_result.data)}")
+
+# Example 8: Manual batch scrape with pagination control
+# Use this when you need to control how many pages to fetch or want to process results incrementally
+print("\n=== Example 8: Manual batch scrape with pagination control ===")
+batch_job = firecrawl.start_batch_scrape(urls)
+status = firecrawl.get_batch_scrape_status(batch_job.id)
+print(f"Batch scrape documents: {len(status.data)}")
+
+# Example 9: Async usage
+print("\n=== Example 9: Async pagination ===")
+import asyncio
+from firecrawl import AsyncFirecrawl
+
+async def async_example():
+ async_client = AsyncFirecrawl(api_key="your-api-key")
+
+ # Simple async crawl - automatically waits for completion
+ crawl_result = await async_client.crawl("https://example.com", limit=50)
+ print(f"Async crawl documents: {len(crawl_result.data)}")
+
+ # Manual async crawl with pagination
+ crawl_job = await async_client.start_crawl("https://example.com", limit=50)
+ pagination_config = PaginationConfig(max_pages=2)
+ status = await async_client.get_crawl_status(
+ crawl_job.id,
+ pagination_config=pagination_config
+ )
+ print(f"Async crawl with pagination: {len(status.data)}")
+
+# Run async example
+# asyncio.run(async_example())
diff --git a/apps/python-sdk/firecrawl/__init__.py b/apps/python-sdk/firecrawl/__init__.py
index 9b7ead690..54b89235e 100644
--- a/apps/python-sdk/firecrawl/__init__.py
+++ b/apps/python-sdk/firecrawl/__init__.py
@@ -17,7 +17,7 @@ from .v1 import (
V1ChangeTrackingOptions,
)
-__version__ = "3.4.0"
+__version__ = "4.0.0"
# Define the logger for the Firecrawl project
logger: logging.Logger = logging.getLogger("firecrawl")
diff --git a/apps/python-sdk/firecrawl/__tests__/e2e/v2/test_crawl.py b/apps/python-sdk/firecrawl/__tests__/e2e/v2/test_crawl.py
index cefa05916..c7533e983 100644
--- a/apps/python-sdk/firecrawl/__tests__/e2e/v2/test_crawl.py
+++ b/apps/python-sdk/firecrawl/__tests__/e2e/v2/test_crawl.py
@@ -63,7 +63,7 @@ class TestCrawlE2E:
assert status_job.status in ["scraping", "completed", "failed"]
assert status_job.completed >= 0
assert status_job.expires_at is not None
- assert status_job.next is not None
+ assert status_job.next is None
assert isinstance(status_job.data, list)
def test_cancel_crawl(self):
diff --git a/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_pagination.py b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_pagination.py
new file mode 100644
index 000000000..f6a1ffe34
--- /dev/null
+++ b/apps/python-sdk/firecrawl/__tests__/unit/v2/methods/test_pagination.py
@@ -0,0 +1,602 @@
+"""
+Unit tests for Firecrawl v2 pagination functionality.
+"""
+
+import pytest
+import time
+from unittest.mock import Mock, patch, AsyncMock
+from typing import Dict, Any, List
+
+from firecrawl.v2.types import (
+ PaginationConfig,
+ CrawlJob,
+ BatchScrapeJob,
+ Document,
+ DocumentMetadata
+)
+from firecrawl.v2.methods.crawl import get_crawl_status, _fetch_all_pages
+from firecrawl.v2.methods.batch import get_batch_scrape_status, _fetch_all_batch_pages
+from firecrawl.v2.methods.aio.crawl import get_crawl_status as get_crawl_status_async, _fetch_all_pages_async
+from firecrawl.v2.methods.aio.batch import get_batch_scrape_status as get_batch_scrape_status_async, _fetch_all_batch_pages_async
+
+
+class TestPaginationConfig:
+ """Test PaginationConfig model."""
+
+ def test_default_values(self):
+ """Test default values for PaginationConfig."""
+ config = PaginationConfig()
+ assert config.auto_paginate is True
+ assert config.max_pages is None
+ assert config.max_results is None
+ assert config.max_wait_time is None
+
+ def test_custom_values(self):
+ """Test custom values for PaginationConfig."""
+ config = PaginationConfig(
+ auto_paginate=False,
+ max_pages=5,
+ max_results=100,
+ max_wait_time=30
+ )
+ assert config.auto_paginate is False
+ assert config.max_pages == 5
+ assert config.max_results == 100
+ assert config.max_wait_time == 30
+
+
+class TestCrawlPagination:
+ """Test crawl pagination functionality."""
+
+ def setup_method(self):
+ """Set up test fixtures."""
+ self.mock_client = Mock()
+ self.job_id = "test-crawl-123"
+
+ # Sample document data
+ self.sample_doc = {
+ "url": "https://example.com",
+ "markdown": "# Test Content",
+ "metadata": {
+ "title": "Test Page",
+ "statusCode": 200
+ }
+ }
+
+ def test_get_crawl_status_no_pagination(self):
+ """Test get_crawl_status with auto_paginate=False."""
+ # Mock response with next URL
+ mock_response = Mock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 10,
+ "total": 10,
+ "creditsUsed": 5,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": "https://api.firecrawl.dev/v2/crawl/test-crawl-123?page=2",
+ "data": [self.sample_doc]
+ }
+
+ self.mock_client.get.return_value = mock_response
+
+ # Test with auto_paginate=False
+ pagination_config = PaginationConfig(auto_paginate=False)
+ result = get_crawl_status(self.mock_client, self.job_id, pagination_config)
+
+ assert result.status == "completed"
+ assert result.next == "https://api.firecrawl.dev/v2/crawl/test-crawl-123?page=2"
+ assert len(result.data) == 1
+ assert isinstance(result.data[0], Document)
+
+ def test_get_crawl_status_with_pagination(self):
+ """Test get_crawl_status with auto_paginate=True."""
+ # Mock first page response
+ mock_response1 = Mock()
+ mock_response1.ok = True
+ mock_response1.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 10,
+ "total": 20,
+ "creditsUsed": 5,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": "https://api.firecrawl.dev/v2/crawl/test-crawl-123?page=2",
+ "data": [self.sample_doc]
+ }
+
+ # Mock second page response
+ mock_response2 = Mock()
+ mock_response2.ok = True
+ mock_response2.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 20,
+ "total": 20,
+ "creditsUsed": 10,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": None,
+ "data": [self.sample_doc]
+ }
+
+ self.mock_client.get.side_effect = [mock_response1, mock_response2]
+
+ # Test with auto_paginate=True
+ pagination_config = PaginationConfig(auto_paginate=True)
+ result = get_crawl_status(self.mock_client, self.job_id, pagination_config)
+
+ assert result.status == "completed"
+ assert result.next is None # Should be None when auto_paginate=True
+ assert len(result.data) == 2
+ assert self.mock_client.get.call_count == 2
+
+ def test_get_crawl_status_max_pages_limit(self):
+ """Test get_crawl_status with max_pages limit."""
+ # Mock responses for multiple pages
+ mock_responses = []
+ for i in range(5): # 5 pages available
+ mock_response = Mock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": (i + 1) * 10,
+ "total": 50,
+ "creditsUsed": (i + 1) * 5,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": f"https://api.firecrawl.dev/v2/crawl/test-crawl-123?page={i+2}" if i < 4 else None,
+ "data": [self.sample_doc]
+ }
+ mock_responses.append(mock_response)
+
+ self.mock_client.get.side_effect = mock_responses
+
+ # Test with max_pages=3
+ pagination_config = PaginationConfig(auto_paginate=True, max_pages=3)
+ result = get_crawl_status(self.mock_client, self.job_id, pagination_config)
+
+ assert len(result.data) == 4 # 1 initial + 3 from pages
+ assert self.mock_client.get.call_count == 4 # 1 initial + 3 pagination calls
+
+ def test_get_crawl_status_max_results_limit(self):
+ """Test get_crawl_status with max_results limit."""
+ # Mock responses with multiple documents per page
+ mock_response1 = Mock()
+ mock_response1.ok = True
+ mock_response1.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 10,
+ "total": 20,
+ "creditsUsed": 5,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": "https://api.firecrawl.dev/v2/crawl/test-crawl-123?page=2",
+ "data": [self.sample_doc, self.sample_doc, self.sample_doc] # 3 docs
+ }
+
+ mock_response2 = Mock()
+ mock_response2.ok = True
+ mock_response2.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 20,
+ "total": 20,
+ "creditsUsed": 10,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": "https://api.firecrawl.dev/v2/crawl/test-crawl-123?page=3",
+ "data": [self.sample_doc, self.sample_doc] # 2 more docs
+ }
+
+ self.mock_client.get.side_effect = [mock_response1, mock_response2]
+
+ # Test with max_results=4
+ pagination_config = PaginationConfig(auto_paginate=True, max_results=4)
+ result = get_crawl_status(self.mock_client, self.job_id, pagination_config)
+
+ assert len(result.data) == 4 # Should stop at 4 results
+ assert self.mock_client.get.call_count == 2 # Should fetch 2 pages
+
+ def test_get_crawl_status_max_wait_time_limit(self):
+ """Test get_crawl_status with max_wait_time limit."""
+ # Mock slow response
+ mock_response = Mock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 10,
+ "total": 20,
+ "creditsUsed": 5,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": "https://api.firecrawl.dev/v2/crawl/test-crawl-123?page=2",
+ "data": [self.sample_doc]
+ }
+
+ self.mock_client.get.return_value = mock_response
+
+ # Test with max_wait_time=1 second
+ pagination_config = PaginationConfig(auto_paginate=True, max_wait_time=1)
+
+ with patch('firecrawl.v2.methods.crawl.time.monotonic', side_effect=[0, 2]): # Simulate 2 seconds elapsed
+ result = get_crawl_status(self.mock_client, self.job_id, pagination_config)
+
+ assert len(result.data) == 1 # Should stop due to timeout
+ assert self.mock_client.get.call_count == 1
+
+ def test_fetch_all_pages_error_handling(self):
+ """Test _fetch_all_pages with API errors."""
+ # Mock first page success, second page error
+ mock_response1 = Mock()
+ mock_response1.ok = True
+ mock_response1.json.return_value = {
+ "success": True,
+ "data": [self.sample_doc],
+ "next": "https://api.firecrawl.dev/v2/crawl/test-crawl-123?page=2"
+ }
+
+ mock_response2 = Mock()
+ mock_response2.ok = False
+ mock_response2.status_code = 500
+
+ self.mock_client.get.side_effect = [mock_response1, mock_response2]
+
+ # Should continue with what we have
+ result = _fetch_all_pages(self.mock_client, "https://api.firecrawl.dev/v2/crawl/test-crawl-123?page=2", [], None)
+
+ assert len(result) == 1 # Should have the first page data
+ assert self.mock_client.get.call_count == 2
+
+
+class TestBatchScrapePagination:
+ """Test batch scrape pagination functionality."""
+
+ def setup_method(self):
+ """Set up test fixtures."""
+ self.mock_client = Mock()
+ self.job_id = "test-batch-123"
+
+ # Sample document data
+ self.sample_doc = {
+ "url": "https://example.com",
+ "markdown": "# Test Content",
+ "metadata": {
+ "title": "Test Page",
+ "statusCode": 200
+ }
+ }
+
+ def test_get_batch_scrape_status_no_pagination(self):
+ """Test get_batch_scrape_status with auto_paginate=False."""
+ # Mock response with next URL
+ mock_response = Mock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 10,
+ "total": 10,
+ "creditsUsed": 5,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": "https://api.firecrawl.dev/v2/batch/scrape/test-batch-123?page=2",
+ "data": [self.sample_doc]
+ }
+
+ self.mock_client.get.return_value = mock_response
+
+ # Test with auto_paginate=False
+ pagination_config = PaginationConfig(auto_paginate=False)
+ result = get_batch_scrape_status(self.mock_client, self.job_id, pagination_config)
+
+ assert result.status == "completed"
+ assert result.next == "https://api.firecrawl.dev/v2/batch/scrape/test-batch-123?page=2"
+ assert len(result.data) == 1
+ assert isinstance(result.data[0], Document)
+
+ def test_get_batch_scrape_status_with_pagination(self):
+ """Test get_batch_scrape_status with auto_paginate=True."""
+ # Mock first page response
+ mock_response1 = Mock()
+ mock_response1.ok = True
+ mock_response1.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 10,
+ "total": 20,
+ "creditsUsed": 5,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": "https://api.firecrawl.dev/v2/batch/scrape/test-batch-123?page=2",
+ "data": [self.sample_doc]
+ }
+
+ # Mock second page response
+ mock_response2 = Mock()
+ mock_response2.ok = True
+ mock_response2.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 20,
+ "total": 20,
+ "creditsUsed": 10,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": None,
+ "data": [self.sample_doc]
+ }
+
+ self.mock_client.get.side_effect = [mock_response1, mock_response2]
+
+ # Test with auto_paginate=True
+ pagination_config = PaginationConfig(auto_paginate=True)
+ result = get_batch_scrape_status(self.mock_client, self.job_id, pagination_config)
+
+ assert result.status == "completed"
+ assert result.next is None # Should be None when auto_paginate=True
+ assert len(result.data) == 2
+ assert self.mock_client.get.call_count == 2
+
+ def test_fetch_all_batch_pages_limits(self):
+ """Test _fetch_all_batch_pages with various limits."""
+ # Mock responses for multiple pages
+ mock_responses = []
+ for i in range(5): # 5 pages available
+ mock_response = Mock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "success": True,
+ "data": [self.sample_doc, self.sample_doc], # 2 docs per page
+ "next": f"https://api.firecrawl.dev/v2/batch/scrape/test-batch-123?page={i+2}" if i < 4 else None
+ }
+ mock_responses.append(mock_response)
+
+ self.mock_client.get.side_effect = mock_responses
+
+ # Test with max_pages=2, max_results=4 (total docs we want)
+ pagination_config = PaginationConfig(max_pages=2, max_results=4)
+ result = _fetch_all_batch_pages(
+ self.mock_client,
+ "https://api.firecrawl.dev/v2/batch/scrape/test-batch-123?page=2",
+ [Document(**self.sample_doc)], # 1 initial doc
+ pagination_config
+ )
+
+ # Should have 1 initial + 3 from pages (limited by max_results=4)
+ assert len(result) == 4
+ assert self.mock_client.get.call_count == 2 # Should fetch 2 pages
+
+
+class TestAsyncPagination:
+ """Test async pagination functionality."""
+
+ def setup_method(self):
+ """Set up test fixtures."""
+ self.mock_client = AsyncMock()
+ self.job_id = "test-async-123"
+
+ # Sample document data
+ self.sample_doc = {
+ "url": "https://example.com",
+ "markdown": "# Test Content",
+ "metadata": {
+ "title": "Test Page",
+ "statusCode": 200
+ }
+ }
+
+ @pytest.mark.asyncio
+ async def test_get_crawl_status_async_with_pagination(self):
+ """Test async get_crawl_status with pagination."""
+ # Mock first page response
+ mock_response1 = Mock()
+ mock_response1.status_code = 200
+ mock_response1.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 10,
+ "total": 20,
+ "creditsUsed": 5,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": "https://api.firecrawl.dev/v2/crawl/test-async-123?page=2",
+ "data": [self.sample_doc]
+ }
+
+ # Mock second page response
+ mock_response2 = Mock()
+ mock_response2.status_code = 200
+ mock_response2.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 20,
+ "total": 20,
+ "creditsUsed": 10,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": None,
+ "data": [self.sample_doc]
+ }
+
+ self.mock_client.get.side_effect = [mock_response1, mock_response2]
+
+ # Test with auto_paginate=True
+ pagination_config = PaginationConfig(auto_paginate=True)
+ result = await get_crawl_status_async(self.mock_client, self.job_id, pagination_config)
+
+ assert result.status == "completed"
+ assert result.next is None
+ assert len(result.data) == 2
+ assert self.mock_client.get.call_count == 2
+
+ @pytest.mark.asyncio
+ async def test_get_batch_scrape_status_async_with_pagination(self):
+ """Test async get_batch_scrape_status with pagination."""
+ # Mock first page response
+ mock_response1 = Mock()
+ mock_response1.status_code = 200
+ mock_response1.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 10,
+ "total": 20,
+ "creditsUsed": 5,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": "https://api.firecrawl.dev/v2/batch/scrape/test-async-123?page=2",
+ "data": [self.sample_doc]
+ }
+
+ # Mock second page response
+ mock_response2 = Mock()
+ mock_response2.status_code = 200
+ mock_response2.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 20,
+ "total": 20,
+ "creditsUsed": 10,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": None,
+ "data": [self.sample_doc]
+ }
+
+ self.mock_client.get.side_effect = [mock_response1, mock_response2]
+
+ # Test with auto_paginate=True
+ pagination_config = PaginationConfig(auto_paginate=True)
+ result = await get_batch_scrape_status_async(self.mock_client, self.job_id, pagination_config)
+
+ assert result.status == "completed"
+ assert result.next is None
+ assert len(result.data) == 2
+ assert self.mock_client.get.call_count == 2
+
+ @pytest.mark.asyncio
+ async def test_fetch_all_pages_async_limits(self):
+ """Test async _fetch_all_pages_async with limits."""
+ # Mock responses for multiple pages
+ mock_responses = []
+ for i in range(3): # 3 pages available
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "success": True,
+ "data": [self.sample_doc],
+ "next": f"https://api.firecrawl.dev/v2/crawl/test-async-123?page={i+2}" if i < 2 else None
+ }
+ mock_responses.append(mock_response)
+
+ self.mock_client.get.side_effect = mock_responses
+
+ # Test with max_pages=2
+ pagination_config = PaginationConfig(max_pages=2)
+ result = await _fetch_all_pages_async(
+ self.mock_client,
+ "https://api.firecrawl.dev/v2/crawl/test-async-123?page=2",
+ [Document(**self.sample_doc)], # 1 initial doc
+ pagination_config
+ )
+
+ assert len(result) == 3 # 1 initial + 2 from pages
+ assert self.mock_client.get.call_count == 2
+
+
+class TestPaginationEdgeCases:
+ """Test pagination edge cases and error conditions."""
+
+ def setup_method(self):
+ """Set up test fixtures."""
+ self.mock_client = Mock()
+ self.sample_doc = {
+ "url": "https://example.com",
+ "markdown": "# Test Content",
+ "metadata": {"title": "Test Page"}
+ }
+
+ def test_pagination_with_empty_data(self):
+ """Test pagination when API returns empty data."""
+ mock_response = Mock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 0,
+ "total": 0,
+ "creditsUsed": 0,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": None,
+ "data": []
+ }
+
+ self.mock_client.get.return_value = mock_response
+
+ pagination_config = PaginationConfig(auto_paginate=True)
+ result = get_crawl_status(self.mock_client, "test-123", pagination_config)
+
+ assert len(result.data) == 0
+ assert result.next is None
+
+ def test_pagination_with_string_data(self):
+ """Test pagination when API returns string data (should be skipped)."""
+ mock_response = Mock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "success": True,
+ "status": "completed",
+ "completed": 2,
+ "total": 2,
+ "creditsUsed": 1,
+ "expiresAt": "2024-01-01T00:00:00Z",
+ "next": None,
+ "data": ["https://example.com", self.sample_doc] # String + dict
+ }
+
+ self.mock_client.get.return_value = mock_response
+
+ pagination_config = PaginationConfig(auto_paginate=True)
+ result = get_crawl_status(self.mock_client, "test-123", pagination_config)
+
+ assert len(result.data) == 1 # Only the dict should be processed
+ assert isinstance(result.data[0], Document)
+
+ def test_pagination_with_failed_response(self):
+ """Test pagination when API response indicates failure."""
+ mock_response = Mock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "success": False,
+ "error": "Job not found"
+ }
+
+ self.mock_client.get.return_value = mock_response
+
+ pagination_config = PaginationConfig(auto_paginate=True)
+
+ with pytest.raises(Exception, match="Job not found"):
+ get_crawl_status(self.mock_client, "test-123", pagination_config)
+
+ def test_pagination_with_unsuccessful_page(self):
+ """Test pagination when a subsequent page is unsuccessful."""
+ # Mock first page success
+ mock_response1 = Mock()
+ mock_response1.ok = True
+ mock_response1.json.return_value = {
+ "success": True,
+ "data": [self.sample_doc],
+ "next": "https://api.firecrawl.dev/v2/crawl/test-123?page=2"
+ }
+
+ # Mock second page failure
+ mock_response2 = Mock()
+ mock_response2.ok = True
+ mock_response2.json.return_value = {
+ "success": False,
+ "error": "Page not found"
+ }
+
+ self.mock_client.get.side_effect = [mock_response1, mock_response2]
+
+ # Should continue with what we have
+ result = _fetch_all_pages(self.mock_client, "https://api.firecrawl.dev/v2/crawl/test-123?page=2", [], None)
+
+ assert len(result) == 1 # Should have the first page data
+ assert self.mock_client.get.call_count == 2
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-v"])
diff --git a/apps/python-sdk/firecrawl/v2/client.py b/apps/python-sdk/firecrawl/v2/client.py
index 194fa4314..3c37afc0e 100644
--- a/apps/python-sdk/firecrawl/v2/client.py
+++ b/apps/python-sdk/firecrawl/v2/client.py
@@ -35,6 +35,7 @@ from .types import (
ExecuteJavascriptAction,
PDFAction,
Location,
+ PaginationConfig,
)
from .utils.http_client import HttpClient
from .utils.error_handler import FirecrawlError
@@ -356,12 +357,17 @@ class FirecrawlClient:
return crawl_module.start_crawl(self.http_client, request)
- def get_crawl_status(self, job_id: str) -> CrawlJob:
+ def get_crawl_status(
+ self,
+ job_id: str,
+ pagination_config: Optional[PaginationConfig] = None
+ ) -> CrawlJob:
"""
Get the status of a crawl job.
Args:
job_id: ID of the crawl job
+ pagination_config: Optional configuration for pagination behavior
Returns:
CrawlJob with current status and data
@@ -369,7 +375,11 @@ class FirecrawlClient:
Raises:
Exception: If the status check fails
"""
- return crawl_module.get_crawl_status(self.http_client, job_id)
+ return crawl_module.get_crawl_status(
+ self.http_client,
+ job_id,
+ pagination_config=pagination_config
+ )
def get_crawl_errors(self, crawl_id: str) -> CrawlErrorsResponse:
"""
@@ -651,16 +661,25 @@ class FirecrawlClient:
idempotency_key=idempotency_key,
)
- def get_batch_scrape_status(self, job_id: str):
+ def get_batch_scrape_status(
+ self,
+ job_id: str,
+ pagination_config: Optional[PaginationConfig] = None
+ ):
"""Get current status and any scraped data for a batch job.
Args:
job_id: Batch job ID
+ pagination_config: Optional configuration for pagination behavior
Returns:
Status payload including counts and partial data
"""
- return batch_module.get_batch_scrape_status(self.http_client, job_id)
+ return batch_module.get_batch_scrape_status(
+ self.http_client,
+ job_id,
+ pagination_config=pagination_config
+ )
def cancel_batch_scrape(self, job_id: str) -> bool:
"""Cancel a running batch scrape job.
diff --git a/apps/python-sdk/firecrawl/v2/client_async.py b/apps/python-sdk/firecrawl/v2/client_async.py
index 3a8102801..a7d3552fd 100644
--- a/apps/python-sdk/firecrawl/v2/client_async.py
+++ b/apps/python-sdk/firecrawl/v2/client_async.py
@@ -31,6 +31,7 @@ from .types import (
ExecuteJavascriptAction,
PDFAction,
Location,
+ PaginationConfig,
)
from .utils.http_client import HttpClient
from .utils.http_client_async import AsyncHttpClient
@@ -94,8 +95,16 @@ class AsyncFirecrawlClient:
timeout = kwargs.get("timeout")
return await self.wait_crawl(resp.id, poll_interval=poll_interval, timeout=timeout)
- async def get_crawl_status(self, job_id: str) -> CrawlJob:
- return await async_crawl.get_crawl_status(self.async_http_client, job_id)
+ async def get_crawl_status(
+ self,
+ job_id: str,
+ pagination_config: Optional[PaginationConfig] = None
+ ) -> CrawlJob:
+ return await async_crawl.get_crawl_status(
+ self.async_http_client,
+ job_id,
+ pagination_config=pagination_config
+ )
async def cancel_crawl(self, job_id: str) -> bool:
return await async_crawl.cancel_crawl(self.async_http_client, job_id)
@@ -154,8 +163,16 @@ class AsyncFirecrawlClient:
timeout = kwargs.get("timeout")
return await self.wait_batch_scrape(job_id, poll_interval=poll_interval, timeout=timeout)
- async def get_batch_scrape_status(self, job_id: str):
- return await async_batch.get_batch_scrape_status(self.async_http_client, job_id)
+ async def get_batch_scrape_status(
+ self,
+ job_id: str,
+ pagination_config: Optional[PaginationConfig] = None
+ ):
+ return await async_batch.get_batch_scrape_status(
+ self.async_http_client,
+ job_id,
+ pagination_config=pagination_config
+ )
async def cancel_batch_scrape(self, job_id: str) -> bool:
return await async_batch.cancel_batch_scrape(self.async_http_client, job_id)
diff --git a/apps/python-sdk/firecrawl/v2/methods/aio/batch.py b/apps/python-sdk/firecrawl/v2/methods/aio/batch.py
index 4bc92f80c..fbd8ca8e5 100644
--- a/apps/python-sdk/firecrawl/v2/methods/aio/batch.py
+++ b/apps/python-sdk/firecrawl/v2/methods/aio/batch.py
@@ -1,8 +1,10 @@
from typing import Optional, List, Dict, Any
-from ...types import ScrapeOptions, WebhookConfig, Document, BatchScrapeResponse, BatchScrapeJob
+from ...types import ScrapeOptions, WebhookConfig, Document, BatchScrapeResponse, BatchScrapeJob, PaginationConfig
from ...utils.http_client_async import AsyncHttpClient
from ...utils.validation import prepare_scrape_options
from ...utils.error_handler import handle_response_error
+from ...utils.normalize import normalize_document_input
+import time
def _prepare(urls: List[str], *, options: Optional[ScrapeOptions] = None, **kwargs) -> Dict[str, Any]:
@@ -39,7 +41,25 @@ async def start_batch_scrape(client: AsyncHttpClient, urls: List[str], **kwargs)
return BatchScrapeResponse(id=body.get("id"), url=body.get("url"), invalid_urls=body.get("invalidURLs"))
-async def get_batch_scrape_status(client: AsyncHttpClient, job_id: str) -> BatchScrapeJob:
+async def get_batch_scrape_status(
+ client: AsyncHttpClient,
+ job_id: str,
+ pagination_config: Optional[PaginationConfig] = None
+) -> BatchScrapeJob:
+ """
+ Get the status of a batch scrape job.
+
+ Args:
+ client: Async HTTP client instance
+ job_id: ID of the batch scrape job
+ pagination_config: Optional configuration for pagination behavior
+
+ Returns:
+ BatchScrapeJob containing job status and data
+
+ Raises:
+ Exception: If the status check fails
+ """
response = await client.get(f"/v2/batch/scrape/{job_id}")
if response.status_code >= 400:
handle_response_error(response, "get batch scrape status")
@@ -49,23 +69,102 @@ async def get_batch_scrape_status(client: AsyncHttpClient, job_id: str) -> Batch
docs: List[Document] = []
for doc in body.get("data", []) or []:
if isinstance(doc, dict):
- normalized = dict(doc)
- if 'rawHtml' in normalized and 'raw_html' not in normalized:
- normalized['raw_html'] = normalized.pop('rawHtml')
- if 'changeTracking' in normalized and 'change_tracking' not in normalized:
- normalized['change_tracking'] = normalized.pop('changeTracking')
+ normalized = normalize_document_input(doc)
docs.append(Document(**normalized))
+
+ # Handle pagination if requested
+ auto_paginate = pagination_config.auto_paginate if pagination_config else True
+ if auto_paginate and body.get("next"):
+ docs = await _fetch_all_batch_pages_async(
+ client,
+ body.get("next"),
+ docs,
+ pagination_config
+ )
+
return BatchScrapeJob(
status=body.get("status"),
completed=body.get("completed", 0),
total=body.get("total", 0),
credits_used=body.get("creditsUsed"),
expires_at=body.get("expiresAt"),
- next=body.get("next"),
+ next=body.get("next") if not auto_paginate else None,
data=docs,
)
+async def _fetch_all_batch_pages_async(
+ client: AsyncHttpClient,
+ next_url: str,
+ initial_documents: List[Document],
+ pagination_config: Optional[PaginationConfig] = None
+) -> List[Document]:
+ """
+ Fetch all pages of batch scrape results asynchronously.
+
+ Args:
+ client: Async HTTP client instance
+ next_url: URL for the next page
+ initial_documents: Documents from the first page
+ pagination_config: Optional configuration for pagination limits
+
+ Returns:
+ List of all documents from all pages
+ """
+ documents = initial_documents.copy()
+ current_url = next_url
+ page_count = 0
+
+ # Apply pagination limits
+ max_pages = pagination_config.max_pages if pagination_config else None
+ max_results = pagination_config.max_results if pagination_config else None
+ max_wait_time = pagination_config.max_wait_time if pagination_config else None
+
+ start_time = time.monotonic()
+
+ while current_url:
+ # Check pagination limits
+ if (max_pages is not None) and (page_count >= max_pages):
+ break
+
+ if (max_wait_time is not None) and (time.monotonic() - start_time) > max_wait_time:
+ break
+
+ # Fetch next page
+ response = await client.get(current_url)
+
+ if response.status_code >= 400:
+ # Log error but continue with what we have
+ import logging
+ logger = logging.getLogger("firecrawl")
+ logger.warning(f"Failed to fetch next page: {response.status_code}")
+ break
+
+ page_data = response.json()
+
+ if not page_data.get("success"):
+ break
+
+ # Add documents from this page
+ for doc in page_data.get("data", []) or []:
+ if isinstance(doc, dict):
+ # Check max_results limit
+ if (max_results is not None) and (len(documents) >= max_results):
+ break
+ normalized = normalize_document_input(doc)
+ documents.append(Document(**normalized))
+
+ # Check if we hit max_results limit
+ if (max_results is not None) and (len(documents) >= max_results):
+ break
+
+ # Get next URL
+ current_url = page_data.get("next")
+ page_count += 1
+
+ return documents
+
+
async def cancel_batch_scrape(client: AsyncHttpClient, job_id: str) -> bool:
response = await client.delete(f"/v2/batch/scrape/{job_id}")
if response.status_code >= 400:
diff --git a/apps/python-sdk/firecrawl/v2/methods/aio/crawl.py b/apps/python-sdk/firecrawl/v2/methods/aio/crawl.py
index e345b2ce2..2997209f2 100644
--- a/apps/python-sdk/firecrawl/v2/methods/aio/crawl.py
+++ b/apps/python-sdk/firecrawl/v2/methods/aio/crawl.py
@@ -1,4 +1,4 @@
-from typing import Optional, Dict, Any
+from typing import Optional, Dict, Any, List
from ...types import (
CrawlRequest,
CrawlJob,
@@ -10,11 +10,13 @@ from ...types import (
CrawlErrorsResponse,
ActiveCrawlsResponse,
ActiveCrawl,
+ PaginationConfig,
)
from ...utils.error_handler import handle_response_error
from ...utils.validation import prepare_scrape_options
from ...utils.http_client_async import AsyncHttpClient
from ...utils.normalize import normalize_document_input
+import time
def _prepare_crawl_request(request: CrawlRequest) -> dict:
@@ -58,6 +60,20 @@ def _prepare_crawl_request(request: CrawlRequest) -> dict:
async def start_crawl(client: AsyncHttpClient, request: CrawlRequest) -> CrawlResponse:
+ """
+ Start a crawl job for a website.
+
+ Args:
+ client: Async HTTP client instance
+ request: CrawlRequest containing URL and options
+
+ Returns:
+ CrawlResponse with job information
+
+ Raises:
+ ValueError: If request is invalid
+ Exception: If the crawl operation fails to start
+ """
payload = _prepare_crawl_request(request)
response = await client.post("/v2/crawl", payload)
if response.status_code >= 400:
@@ -68,7 +84,25 @@ async def start_crawl(client: AsyncHttpClient, request: CrawlRequest) -> CrawlRe
raise Exception(body.get("error", "Unknown error occurred"))
-async def get_crawl_status(client: AsyncHttpClient, job_id: str) -> CrawlJob:
+async def get_crawl_status(
+ client: AsyncHttpClient,
+ job_id: str,
+ pagination_config: Optional[PaginationConfig] = None
+) -> CrawlJob:
+ """
+ Get the status of a crawl job.
+
+ Args:
+ client: Async HTTP client instance
+ job_id: ID of the crawl job
+ pagination_config: Optional configuration for pagination limits
+
+ Returns:
+ CrawlJob with job information
+
+ Raises:
+ Exception: If the status check fails
+ """
response = await client.get(f"/v2/crawl/{job_id}")
if response.status_code >= 400:
handle_response_error(response, "get crawl status")
@@ -79,19 +113,115 @@ async def get_crawl_status(client: AsyncHttpClient, job_id: str) -> CrawlJob:
if isinstance(doc_data, dict):
normalized = normalize_document_input(doc_data)
documents.append(Document(**normalized))
+
+ # Handle pagination if requested
+ auto_paginate = pagination_config.auto_paginate if pagination_config else True
+ if auto_paginate and body.get("next"):
+ documents = await _fetch_all_pages_async(
+ client,
+ body.get("next"),
+ documents,
+ pagination_config
+ )
+
return CrawlJob(
status=body.get("status"),
completed=body.get("completed", 0),
total=body.get("total", 0),
credits_used=body.get("creditsUsed", 0),
expires_at=body.get("expiresAt"),
- next=body.get("next"),
+ next=body.get("next") if not auto_paginate else None,
data=documents,
)
raise Exception(body.get("error", "Unknown error occurred"))
+async def _fetch_all_pages_async(
+ client: AsyncHttpClient,
+ next_url: str,
+ initial_documents: List[Document],
+ pagination_config: Optional[PaginationConfig] = None
+) -> List[Document]:
+ """
+ Fetch all pages of crawl results asynchronously.
+
+ Args:
+ client: Async HTTP client instance
+ next_url: URL for the next page
+ initial_documents: Documents from the first page
+ pagination_config: Optional configuration for pagination limits
+
+ Returns:
+ List of all documents from all pages
+ """
+ documents = initial_documents.copy()
+ current_url = next_url
+ page_count = 0
+
+ # Apply pagination limits
+ max_pages = pagination_config.max_pages if pagination_config else None
+ max_results = pagination_config.max_results if pagination_config else None
+ max_wait_time = pagination_config.max_wait_time if pagination_config else None
+
+ start_time = time.monotonic()
+
+ while current_url:
+ # Check pagination limits (treat 0 as a valid limit)
+ if (max_pages is not None) and page_count >= max_pages:
+ break
+
+ if (max_wait_time is not None) and (time.monotonic() - start_time) > max_wait_time:
+ break
+
+ # Fetch next page
+ response = await client.get(current_url)
+
+ if response.status_code >= 400:
+ # Log error but continue with what we have
+ import logging
+ logger = logging.getLogger("firecrawl")
+ logger.warning("Failed to fetch next page", extra={"status_code": response.status_code})
+ break
+
+ page_data = response.json()
+
+ if not page_data.get("success"):
+ break
+
+ # Add documents from this page
+ for doc_data in page_data.get("data", []):
+ if isinstance(doc_data, dict):
+ # Check max_results limit
+ if (max_results is not None) and (len(documents) >= max_results):
+ break
+ normalized = normalize_document_input(doc_data)
+ documents.append(Document(**normalized))
+
+ # Check if we hit max_results limit
+ if (max_results is not None) and (len(documents) >= max_results):
+ break
+
+ # Get next URL
+ current_url = page_data.get("next")
+ page_count += 1
+
+ return documents
+
+
async def cancel_crawl(client: AsyncHttpClient, job_id: str) -> bool:
+ """
+ Cancel a crawl job.
+
+ Args:
+ client: Async HTTP client instance
+ job_id: ID of the crawl job
+
+ Returns:
+ True if cancellation was successful
+
+ Raises:
+ Exception: If the cancellation operation fails
+ """
response = await client.delete(f"/v2/crawl/{job_id}")
if response.status_code >= 400:
handle_response_error(response, "cancel crawl")
@@ -100,6 +230,20 @@ async def cancel_crawl(client: AsyncHttpClient, job_id: str) -> bool:
async def crawl_params_preview(client: AsyncHttpClient, request: CrawlParamsRequest) -> CrawlParamsData:
+ """
+ Preview crawl parameters before starting a crawl job.
+
+ Args:
+ client: Async HTTP client instance
+ request: CrawlParamsRequest containing URL and prompt
+
+ Returns:
+ CrawlParamsData containing crawl configuration
+
+ Raises:
+ ValueError: If request is invalid
+ Exception: If the parameter preview fails
+ """
if not request.url or not request.url.strip():
raise ValueError("URL cannot be empty")
if not request.prompt or not request.prompt.strip():
@@ -138,6 +282,19 @@ async def crawl_params_preview(client: AsyncHttpClient, request: CrawlParamsRequ
async def get_crawl_errors(client: AsyncHttpClient, crawl_id: str) -> CrawlErrorsResponse:
+ """
+ Get errors from a crawl job.
+
+ Args:
+ client: Async HTTP client instance
+ crawl_id: ID of the crawl job
+
+ Returns:
+ CrawlErrorsResponse with errors and robots blocked
+
+ Raises:
+ Exception: If the error check operation fails
+ """
response = await client.get(f"/v2/crawl/{crawl_id}/errors")
if response.status_code >= 400:
handle_response_error(response, "check crawl errors")
@@ -151,6 +308,18 @@ async def get_crawl_errors(client: AsyncHttpClient, crawl_id: str) -> CrawlError
async def get_active_crawls(client: AsyncHttpClient) -> ActiveCrawlsResponse:
+ """
+ Get active crawl jobs.
+
+ Args:
+ client: Async HTTP client instance
+
+ Returns:
+ ActiveCrawlsResponse with active crawl jobs
+
+ Raises:
+ Exception: If the active crawl jobs operation fails
+ """
response = await client.get("/v2/crawl/active")
if response.status_code >= 400:
handle_response_error(response, "get active crawls")
diff --git a/apps/python-sdk/firecrawl/v2/methods/batch.py b/apps/python-sdk/firecrawl/v2/methods/batch.py
index 82c8d4460..b57166b82 100644
--- a/apps/python-sdk/firecrawl/v2/methods/batch.py
+++ b/apps/python-sdk/firecrawl/v2/methods/batch.py
@@ -11,6 +11,7 @@ from ..types import (
ScrapeOptions,
Document,
WebhookConfig,
+ PaginationConfig,
)
from ..utils import HttpClient, handle_response_error, validate_scrape_options, prepare_scrape_options
from ..utils.normalize import normalize_document_input
@@ -77,7 +78,8 @@ def start_batch_scrape(
def get_batch_scrape_status(
client: HttpClient,
- job_id: str
+ job_id: str,
+ pagination_config: Optional[PaginationConfig] = None
) -> BatchScrapeJob:
"""
Get the status of a batch scrape job.
@@ -85,9 +87,10 @@ def get_batch_scrape_status(
Args:
client: HTTP client instance
job_id: ID of the batch scrape job
+ pagination_config: Optional configuration for pagination behavior
Returns:
- BatchScrapeStatusResponse containing job status and data
+ BatchScrapeJob containing job status and data
Raises:
FirecrawlError: If the status check fails
@@ -111,17 +114,99 @@ def get_batch_scrape_status(
normalized = normalize_document_input(doc)
documents.append(Document(**normalized))
+ # Handle pagination if requested
+ auto_paginate = pagination_config.auto_paginate if pagination_config else True
+ if auto_paginate and body.get("next"):
+ documents = _fetch_all_batch_pages(
+ client,
+ body.get("next"),
+ documents,
+ pagination_config
+ )
+
return BatchScrapeJob(
status=body.get("status"),
completed=body.get("completed", 0),
total=body.get("total", 0),
credits_used=body.get("creditsUsed"),
expires_at=body.get("expiresAt"),
- next=body.get("next"),
+ next=body.get("next") if not auto_paginate else None,
data=documents,
)
+def _fetch_all_batch_pages(
+ client: HttpClient,
+ next_url: str,
+ initial_documents: List[Document],
+ pagination_config: Optional[PaginationConfig] = None
+) -> List[Document]:
+ """
+ Fetch all pages of batch scrape results.
+
+ Args:
+ client: HTTP client instance
+ next_url: URL for the next page
+ initial_documents: Documents from the first page
+ pagination_config: Optional configuration for pagination limits
+
+ Returns:
+ List of all documents from all pages
+ """
+ documents = initial_documents.copy()
+ current_url = next_url
+ page_count = 0
+
+ # Apply pagination limits
+ max_pages = pagination_config.max_pages if pagination_config else None
+ max_results = pagination_config.max_results if pagination_config else None
+ max_wait_time = pagination_config.max_wait_time if pagination_config else None
+
+ start_time = time.monotonic()
+
+ while current_url:
+ # Check pagination limits (treat 0 as a valid limit)
+ if (max_pages is not None) and page_count >= max_pages:
+ break
+
+ if (max_wait_time is not None) and (time.monotonic() - start_time) > max_wait_time:
+ break
+
+ # Fetch next page
+ response = client.get(current_url)
+
+ if not response.ok:
+ # Log error but continue with what we have
+ import logging
+ logger = logging.getLogger("firecrawl")
+ logger.warning("Failed to fetch next page", extra={"status_code": response.status_code})
+ break
+
+ page_data = response.json()
+
+ if not page_data.get("success"):
+ break
+
+ # Add documents from this page
+ for doc in page_data.get("data", []) or []:
+ if isinstance(doc, dict):
+ # Check max_results limit
+ if max_results is not None and len(documents) >= max_results:
+ break
+ normalized = normalize_document_input(doc)
+ documents.append(Document(**normalized))
+
+ # Check if we hit max_results limit after adding all docs from this page
+ if max_results is not None and len(documents) >= max_results:
+ break
+
+ # Get next URL
+ current_url = page_data.get("next")
+ page_count += 1
+
+ return documents
+
+
def cancel_batch_scrape(
client: HttpClient,
job_id: str
@@ -173,7 +258,7 @@ def wait_for_batch_completion(
FirecrawlError: If the job fails or timeout is reached
TimeoutError: If timeout is reached
"""
- start_time = time.time()
+ start_time = time.monotonic()
while True:
status_job = get_batch_scrape_status(client, job_id)
@@ -183,7 +268,7 @@ def wait_for_batch_completion(
return status_job
# Check timeout
- if timeout and (time.time() - start_time) > timeout:
+ if timeout and (time.monotonic() - start_time) > timeout:
raise TimeoutError(f"Batch scrape job {job_id} did not complete within {timeout} seconds")
# Wait before next poll
diff --git a/apps/python-sdk/firecrawl/v2/methods/crawl.py b/apps/python-sdk/firecrawl/v2/methods/crawl.py
index 99ee81926..0ebf7e1f2 100644
--- a/apps/python-sdk/firecrawl/v2/methods/crawl.py
+++ b/apps/python-sdk/firecrawl/v2/methods/crawl.py
@@ -3,12 +3,12 @@ Crawling functionality for Firecrawl v2 API.
"""
import time
-from typing import Optional, Dict, Any
+from typing import Optional, Dict, Any, List
from ..types import (
CrawlRequest,
CrawlJob,
CrawlResponse, Document, CrawlParamsRequest, CrawlParamsResponse, CrawlParamsData,
- WebhookConfig, CrawlErrorsResponse, ActiveCrawlsResponse, ActiveCrawl
+ WebhookConfig, CrawlErrorsResponse, ActiveCrawlsResponse, ActiveCrawl, PaginationConfig
)
from ..utils import HttpClient, handle_response_error, validate_scrape_options, prepare_scrape_options
from ..utils.normalize import normalize_document_input
@@ -138,13 +138,18 @@ def start_crawl(client: HttpClient, request: CrawlRequest) -> CrawlResponse:
raise Exception(response_data.get("error", "Unknown error occurred"))
-def get_crawl_status(client: HttpClient, job_id: str) -> CrawlJob:
+def get_crawl_status(
+ client: HttpClient,
+ job_id: str,
+ pagination_config: Optional[PaginationConfig] = None
+) -> CrawlJob:
"""
Get the status of a crawl job.
Args:
client: HTTP client instance
job_id: ID of the crawl job
+ pagination_config: Optional configuration for pagination behavior
Returns:
CrawlJob with current status and data
@@ -176,6 +181,16 @@ def get_crawl_status(client: HttpClient, job_id: str) -> CrawlJob:
else:
documents.append(Document(**normalize_document_input(doc_data)))
+ # Handle pagination if requested
+ auto_paginate = pagination_config.auto_paginate if pagination_config else True
+ if auto_paginate and response_data.get("next") and not (pagination_config and pagination_config.max_results is not None and len(documents) >= pagination_config.max_results):
+ documents = _fetch_all_pages(
+ client,
+ response_data.get("next"),
+ documents,
+ pagination_config
+ )
+
# Create CrawlJob with current status and data
return CrawlJob(
status=response_data.get("status"),
@@ -183,13 +198,87 @@ def get_crawl_status(client: HttpClient, job_id: str) -> CrawlJob:
total=response_data.get("total", 0),
credits_used=response_data.get("creditsUsed", 0),
expires_at=response_data.get("expiresAt"),
- next=response_data.get("next", None),
+ next=response_data.get("next", None) if not auto_paginate else None,
data=documents
)
else:
raise Exception(response_data.get("error", "Unknown error occurred"))
+def _fetch_all_pages(
+ client: HttpClient,
+ next_url: str,
+ initial_documents: List[Document],
+ pagination_config: Optional[PaginationConfig] = None
+) -> List[Document]:
+ """
+ Fetch all pages of crawl results.
+
+ Args:
+ client: HTTP client instance
+ next_url: URL for the next page
+ initial_documents: Documents from the first page
+ pagination_config: Optional configuration for pagination limits
+
+ Returns:
+ List of all documents from all pages
+ """
+ documents = initial_documents.copy()
+ current_url = next_url
+ page_count = 0
+
+ # Apply pagination limits
+ max_pages = pagination_config.max_pages if pagination_config else None
+ max_results = pagination_config.max_results if pagination_config else None
+ max_wait_time = pagination_config.max_wait_time if pagination_config else None
+
+ start_time = time.monotonic()
+
+ while current_url:
+ # Check pagination limits (treat 0 as a valid limit)
+ if (max_pages is not None) and page_count >= max_pages:
+ break
+
+ if (max_wait_time is not None) and (time.monotonic() - start_time) > max_wait_time:
+ break
+
+ # Fetch next page
+ response = client.get(current_url)
+
+ if not response.ok:
+ # Log error but continue with what we have
+ import logging
+ logger = logging.getLogger("firecrawl")
+ logger.warning("Failed to fetch next page", extra={"status_code": response.status_code})
+ break
+
+ page_data = response.json()
+
+ if not page_data.get("success"):
+ break
+
+ # Add documents from this page
+ data_list = page_data.get("data", [])
+ for doc_data in data_list:
+ if isinstance(doc_data, str):
+ continue
+ else:
+ # Check max_results limit BEFORE adding each document
+ if max_results is not None and len(documents) >= max_results:
+ break
+ documents.append(Document(**normalize_document_input(doc_data)))
+
+ # Check if we hit max_results limit
+ if max_results is not None and len(documents) >= max_results:
+ break
+
+ # Get next URL
+ current_url = page_data.get("next")
+ page_count += 1
+
+ return documents
+
+
def cancel_crawl(client: HttpClient, job_id: str) -> bool:
"""
Cancel a running crawl job.
@@ -235,7 +324,7 @@ def wait_for_crawl_completion(
Exception: If the job fails
TimeoutError: If timeout is reached
"""
- start_time = time.time()
+ start_time = time.monotonic()
while True:
crawl_job = get_crawl_status(client, job_id)
@@ -245,7 +334,7 @@ def wait_for_crawl_completion(
return crawl_job
# Check timeout
- if timeout and (time.time() - start_time) > timeout:
+ if timeout is not None and (time.monotonic() - start_time) > timeout:
raise TimeoutError(f"Crawl job {job_id} did not complete within {timeout} seconds")
# Wait before next poll
diff --git a/apps/python-sdk/firecrawl/v2/types.py b/apps/python-sdk/firecrawl/v2/types.py
index 148362534..319162e14 100644
--- a/apps/python-sdk/firecrawl/v2/types.py
+++ b/apps/python-sdk/firecrawl/v2/types.py
@@ -671,6 +671,13 @@ class ClientConfig(BaseModel):
max_retries: int = 3
backoff_factor: float = 0.5
+class PaginationConfig(BaseModel):
+ """Configuration for pagination behavior."""
+ auto_paginate: bool = True
+ max_pages: Optional[int] = Field(default=None, ge=0)
+ max_results: Optional[int] = Field(default=None, ge=0)
+ max_wait_time: Optional[int] = Field(default=None, ge=0) # seconds
+
# Response union types
AnyResponse = Union[
ScrapeResponse,
diff --git a/apps/python-sdk/firecrawl/v2/utils/http_client.py b/apps/python-sdk/firecrawl/v2/utils/http_client.py
index c6a33f6de..507457b2f 100644
--- a/apps/python-sdk/firecrawl/v2/utils/http_client.py
+++ b/apps/python-sdk/firecrawl/v2/utils/http_client.py
@@ -4,6 +4,7 @@ HTTP client utilities for v2 API.
import time
from typing import Dict, Any, Optional
+from urllib.parse import urlparse, urlunparse, urljoin
import requests
from .get_version import get_version
@@ -15,6 +16,28 @@ class HttpClient:
def __init__(self, api_key: str, api_url: str):
self.api_key = api_key
self.api_url = api_url
+
+ def _build_url(self, endpoint: str) -> str:
+ base = urlparse(self.api_url)
+ ep = urlparse(endpoint)
+
+ # Absolute or protocol-relative (has netloc)
+ if ep.netloc:
+ # Different host: keep path/query but force base host/scheme (no token leakage)
+ path = ep.path or "/"
+ if (ep.hostname or "") != (base.hostname or ""):
+ return urlunparse((base.scheme or "https", base.netloc, path, "", ep.query, ""))
+ # Same host: normalize scheme to base
+ return urlunparse((base.scheme or "https", base.netloc, path, "", ep.query, ""))
+
+ # Relative (including leading slash or not)
+ base_str = self.api_url if self.api_url.endswith("/") else f"{self.api_url}/"
+ # Guard protocol-relative like //host/path slipping through as “relative”
+ if endpoint.startswith("//"):
+ ep2 = urlparse(f"https:{endpoint}")
+ path = ep2.path or "/"
+ return urlunparse((base.scheme or "https", base.netloc, path, "", ep2.query, ""))
+ return urljoin(base_str, endpoint)
def _prepare_headers(self, idempotency_key: Optional[str] = None) -> Dict[str, str]:
"""Prepare headers for API requests."""
@@ -43,7 +66,7 @@ class HttpClient:
data['origin'] = f'python-sdk@{version}'
- url = f"{self.api_url}{endpoint}"
+ url = self._build_url(endpoint)
last_exception = None
@@ -84,7 +107,7 @@ class HttpClient:
if headers is None:
headers = self._prepare_headers()
- url = f"{self.api_url}{endpoint}"
+ url = self._build_url(endpoint)
last_exception = None
@@ -124,7 +147,7 @@ class HttpClient:
if headers is None:
headers = self._prepare_headers()
- url = f"{self.api_url}{endpoint}"
+ url = self._build_url(endpoint)
last_exception = None