Skip to content

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

fix(python-sdk): poll /v1/batch/scrape/{id} in v1 batch_scrape_urls (#4919)

Gergő Móricz0be5955a33ba
diff --git a/apps/python-sdk/firecrawl/__init__.py b/apps/python-sdk/firecrawl/__init__.py
index 1d2aa7d53..f860587a3 100644
--- a/apps/python-sdk/firecrawl/__init__.py
+++ b/apps/python-sdk/firecrawl/__init__.py
@@ -28,7 +28,7 @@ from .v1 import (
V1ChangeTrackingOptions,
)
-__version__ = "4.46.1"
+__version__ = "4.46.2"
# Define the logger for the Firecrawl project
logger: logging.Logger = logging.getLogger("firecrawl")
diff --git a/apps/python-sdk/firecrawl/__tests__/unit/test_v1_batch_scrape_polling.py b/apps/python-sdk/firecrawl/__tests__/unit/test_v1_batch_scrape_polling.py
new file mode 100644
index 000000000..d2949de79
--- /dev/null
+++ b/apps/python-sdk/firecrawl/__tests__/unit/test_v1_batch_scrape_polling.py
@@ -0,0 +1,98 @@
+"""v1 batch_scrape_urls must poll the batch scrape status endpoint; crawl_url keeps polling crawl status."""
+
+import asyncio
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from firecrawl.v1.client import (
+ AsyncV1FirecrawlApp,
+ V1BatchScrapeStatusResponse,
+ V1CrawlStatusResponse,
+ V1FirecrawlApp,
+)
+
+API_URL = "https://api.firecrawl.dev"
+
+
+def _page(status, markdown=None, next_url=None):
+ page = {"success": True, "status": status, "completed": 2, "total": 2,
+ "creditsUsed": 2, "expiresAt": "2026-10-01T00:00:00Z",
+ "data": [{"markdown": markdown}] if markdown else []}
+ if next_url:
+ page["next"] = next_url
+ return page
+
+
+def _pages(path):
+ return [
+ _page("scraping"),
+ _page("completed", "a", f"https://evil.example.com{path}?skip=1"),
+ _page("completed", "b"),
+ ]
+
+
+def _expected_urls(path):
+ return [f"{API_URL}{path}", f"{API_URL}{path}", f"{API_URL}{path}?skip=1"]
+
+
+SYNC_JOBS = [
+ ("batch_scrape_urls", lambda app: app.batch_scrape_urls(["https://example.com"]), "/v1/batch/scrape/job-id", V1BatchScrapeStatusResponse),
+ ("crawl_url", lambda app: app.crawl_url("https://example.com"), "/v1/crawl/job-id", V1CrawlStatusResponse),
+]
+
+
[email protected]("name, call, path, response_type", SYNC_JOBS, ids=[j[0] for j in SYNC_JOBS])
+def test_sync_waiter_polls_matching_status_endpoint(name, call, path, response_type):
+ app = V1FirecrawlApp(api_key="fc-test-key", api_url=API_URL)
+ start = MagicMock(status_code=200, json=MagicMock(return_value={"success": True, "id": "job-id"}))
+ polls = [MagicMock(status_code=200, json=MagicMock(return_value=p)) for p in _pages(path)]
+
+ with patch("firecrawl.v1.client.requests.post", return_value=start), \
+ patch("firecrawl.v1.client.requests.get", side_effect=polls) as get, \
+ patch("firecrawl.v1.client.time.sleep"):
+ result = call(app)
+
+ assert [c.args[0] for c in get.call_args_list] == _expected_urls(path)
+ assert type(result) is response_type
+ assert [d.markdown for d in result.data] == ["a", "b"]
+
+
+def test_sync_batch_scrape_failure_mentions_batch_scrape():
+ app = V1FirecrawlApp(api_key="fc-test-key", api_url=API_URL)
+ start = MagicMock(status_code=200, json=MagicMock(return_value={"success": True, "id": "job-id"}))
+ failed = MagicMock(status_code=200, json=MagicMock(return_value=_page("failed")))
+
+ with patch("firecrawl.v1.client.requests.post", return_value=start), \
+ patch("firecrawl.v1.client.requests.get", return_value=failed):
+ with pytest.raises(Exception, match="Batch scrape job failed"):
+ app.batch_scrape_urls(["https://example.com"])
+
+
+ASYNC_JOBS = [
+ ("batch_scrape_urls", lambda app: app.batch_scrape_urls(["https://example.com"]), "/v1/batch/scrape/job-id", V1BatchScrapeStatusResponse),
+ ("crawl_url", lambda app: app.crawl_url("https://example.com"), "/v1/crawl/job-id", V1CrawlStatusResponse),
+]
+
+
[email protected]("name, call, path, response_type", ASYNC_JOBS, ids=[j[0] for j in ASYNC_JOBS])
+def test_async_waiter_polls_matching_status_endpoint(name, call, path, response_type):
+ app = AsyncV1FirecrawlApp(api_key="fc-test-key", api_url=API_URL)
+ app._async_post_request = AsyncMock(return_value={"success": True, "id": "job-id"})
+ app._async_get_request = AsyncMock(side_effect=_pages(path))
+
+ with patch("firecrawl.v1.client.asyncio.sleep", new=AsyncMock()):
+ result = asyncio.run(call(app))
+
+ assert [c.args[0] for c in app._async_get_request.await_args_list] == _expected_urls(path)
+ assert type(result) is response_type
+ assert [d.markdown for d in result.data] == ["a", "b"]
+
+
+def test_async_batch_scrape_failure_mentions_batch_scrape():
+ app = AsyncV1FirecrawlApp(api_key="fc-test-key", api_url=API_URL)
+ app._async_post_request = AsyncMock(return_value={"success": True, "id": "job-id"})
+ app._async_get_request = AsyncMock(return_value=_page("failed"))
+
+ with pytest.raises(Exception, match="Batch scrape job failed"):
+ asyncio.run(app.batch_scrape_urls(["https://example.com"]))
diff --git a/apps/python-sdk/firecrawl/v1/client.py b/apps/python-sdk/firecrawl/v1/client.py
index a6895af43..e82ee6c07 100644
--- a/apps/python-sdk/firecrawl/v1/client.py
+++ b/apps/python-sdk/firecrawl/v1/client.py
@@ -1579,7 +1579,7 @@ class V1FirecrawlApp:
id = response.json().get('id')
except:
raise Exception(f'Failed to parse Firecrawl response as JSON.')
- return self._monitor_job_status(id, headers, poll_interval)
+ return self._monitor_job_status(id, headers, poll_interval, 'batch_scrape')
else:
self._handle_error(response, 'start batch scrape job')
@@ -2511,24 +2511,29 @@ class V1FirecrawlApp:
self,
id: str,
headers: Dict[str, str],
- poll_interval: int) -> V1CrawlStatusResponse:
+ poll_interval: int,
+ job_type: Literal["crawl", "batch_scrape"] = "crawl") -> Union[V1CrawlStatusResponse, V1BatchScrapeStatusResponse]:
"""
- Monitor the status of a crawl job until completion.
+ Monitor the status of a crawl or batch scrape job until completion.
Args:
- id (str): The ID of the crawl job.
+ id (str): The ID of the job.
headers (Dict[str, str]): The headers to include in the status check requests.
poll_interval (int): Seconds between status checks.
+ job_type (str): "crawl" or "batch_scrape"; selects the status endpoint and response type.
Returns:
- CrawlStatusResponse: The crawl results if the job is completed successfully.
+ V1CrawlStatusResponse or V1BatchScrapeStatusResponse: The job results if the job is completed successfully.
Raises:
Exception: If the job fails or an error occurs during status checks.
"""
- while True:
- api_url = f'{self.api_url}/v1/crawl/{id}'
+ is_batch = job_type == "batch_scrape"
+ api_url = f'{self.api_url}/v1/batch/scrape/{id}' if is_batch else f'{self.api_url}/v1/crawl/{id}'
+ label = 'Batch scrape' if is_batch else 'Crawl'
+ response_model = V1BatchScrapeStatusResponse if is_batch else V1CrawlStatusResponse
+ while True:
status_response = self._get_request(api_url, headers)
if status_response.status_code == 200:
try:
@@ -2538,7 +2543,7 @@ class V1FirecrawlApp:
if status_data['status'] == 'completed':
if 'data' in status_data:
data = status_data['data']
- while 'next' in status_data:
+ while status_data.get('next'):
if len(status_data['data']) == 0:
break
status_response = self._get_request(pin_to_api_origin(self.api_url, status_data['next']), headers)
@@ -2548,16 +2553,16 @@ class V1FirecrawlApp:
raise Exception(f'Failed to parse Firecrawl response as JSON.')
data.extend(status_data.get('data', []))
status_data['data'] = data
- return V1CrawlStatusResponse(**status_data)
+ return response_model(**status_data)
else:
- raise Exception('Crawl job completed but no data was returned')
+ raise Exception(f'{label} job completed but no data was returned')
elif status_data['status'] in ['active', 'paused', 'pending', 'queued', 'waiting', 'scraping']:
poll_interval=max(poll_interval,2)
time.sleep(poll_interval) # Wait for the specified interval before checking again
else:
- raise Exception(f'Crawl job failed or was stopped. Status: {status_data["status"]}')
+ raise Exception(f'{label} job failed or was stopped. Status: {status_data["status"]}')
else:
- self._handle_error(status_response, 'check crawl status')
+ self._handle_error(status_response, f'check {label.lower()} status')
def _handle_error(
self,
@@ -3885,7 +3890,7 @@ class AsyncV1FirecrawlApp(V1FirecrawlApp):
id = response.get('id')
except:
raise Exception(f'Failed to parse Firecrawl response as JSON.')
- return await self._async_monitor_job_status(id, headers, poll_interval)
+ return await self._async_monitor_job_status(id, headers, poll_interval, 'batch_scrape')
else:
self._handle_error(response, 'start batch scrape job')
@@ -4330,26 +4335,34 @@ class AsyncV1FirecrawlApp(V1FirecrawlApp):
return response
- async def _async_monitor_job_status(self, id: str, headers: Dict[str, str], poll_interval: int = 2) -> V1CrawlStatusResponse:
+ async def _async_monitor_job_status(
+ self,
+ id: str,
+ headers: Dict[str, str],
+ poll_interval: int = 2,
+ job_type: Literal["crawl", "batch_scrape"] = "crawl") -> Union[V1CrawlStatusResponse, V1BatchScrapeStatusResponse]:
"""
- Monitor the status of an asynchronous job until completion.
+ Monitor the status of an asynchronous crawl or batch scrape job until completion.
Args:
id (str): The ID of the job to monitor
headers (Dict[str, str]): Headers to include in status check requests
poll_interval (int): Seconds between status checks (default: 2)
+ job_type (str): "crawl" or "batch_scrape"; selects the status endpoint and response type (default: "crawl")
Returns:
- V1CrawlStatusResponse: The job results if completed successfully
+ V1CrawlStatusResponse or V1BatchScrapeStatusResponse: The job results if completed successfully
Raises:
Exception: If the job fails or an error occurs during status checks
"""
+ is_batch = job_type == "batch_scrape"
+ api_url = f'{self.api_url}/v1/batch/scrape/{id}' if is_batch else f'{self.api_url}/v1/crawl/{id}'
+ label = 'Batch scrape' if is_batch else 'Crawl'
+ response_model = V1BatchScrapeStatusResponse if is_batch else V1CrawlStatusResponse
+
while True:
- status_data = await self._async_get_request(
- f'{self.api_url}/v1/crawl/{id}',
- headers
- )
+ status_data = await self._async_get_request(api_url, headers)
if status_data.get('status') == 'completed':
if 'data' in status_data:
@@ -4365,13 +4378,13 @@ class AsyncV1FirecrawlApp(V1FirecrawlApp):
data.extend(next_data.get('data', []))
status_data = next_data
status_data['data'] = data
- return V1CrawlStatusResponse(**status_data)
+ return response_model(**status_data)
else:
- raise Exception('Job completed but no data was returned')
+ raise Exception(f'{label} job completed but no data was returned')
elif status_data.get('status') in ['active', 'paused', 'pending', 'queued', 'waiting', 'scraping']:
await asyncio.sleep(max(poll_interval, 2))
else:
- raise Exception(f'Job failed or was stopped. Status: {status_data["status"]}')
+ raise Exception(f'{label} job failed or was stopped. Status: {status_data["status"]}')
async def map_url(
self,