Skip to content

Commit 45e7cdc

Browse files
shixishclaude
andcommitted
fix(crawl): crawl_download urls report and error bodies; keep the real create-error body
- crawl_download(type="urls") returned a JSON decode error: that report is always CSV, whatever format says. Return the text (matching the TypeScript SDK) and add a type="urls" -> str overload. - crawl_download raised nothing for a non-list JSON body such as {errorCode, error} for an unknown job and handed the dict back as records. Raise JobError carrying the job name, as TypeScript does. - crawl create with HTTP 200 + errorCode now raises APIError with the real status, body and headers instead of a synthesized body; message comes from the error field via the APIError fallback. - Document the 30-character job name limit (README, crawl docstring) and add the create-error fix to the 3.3.0 changelog. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 653915b commit 45e7cdc

6 files changed

Lines changed: 66 additions & 15 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,9 @@ workflows. Additive minor: no wire changes. The package version in
1818
`False`, every other error propagates. The account response carries `token` and
1919
`childTokens`: don't log it whole.
2020
- `crawl_download(name, *, format="json", type=None, num=None)` (sync and async):
21-
`GET /v3/crawl/data`. `format="csv"` returns `str`, otherwise a list of records.
22-
The crawl watcher now uses it. For tools that can't block, the recommended
21+
`GET /v3/crawl/data`. `format="csv"` or `type="urls"` (that report is always CSV)
22+
returns `str`, otherwise a list of records; a JSON body that is not a list (e.g. an
23+
unknown job) raises `JobError`. The crawl watcher now uses it. For tools that can't block, the recommended
2324
pattern is `crawl(..., watch=False)` -> `crawl_get_job` -> `crawl_download`.
2425
- `extract()` keyword-only options after `fmt`: `timeout` (server-side fetch timeout
2526
in ms, default still 30000), `mode` (overrides the `fmt="markdown"` -> `llm`
@@ -38,6 +39,10 @@ workflows. Additive minor: no wire changes. The package version in
3839
`response.json()`. `csv` now returns `str`, `xls`/`xlsx` return `bytes`, and
3940
`jsonl` returns an iterator of entities (`AsyncIterator` from the async client).
4041
`raw=True` is unchanged (undecoded `bytes`).
42+
- `crawl()` create failures that the crawler reports as HTTP 200 with `errorCode`/
43+
`error` in the body (e.g. errorCode 505 for a job name over 30 characters, which
44+
creates nothing) now raise `APIError` (status 200, the real body and headers,
45+
`message` from `error`) instead of yielding `JOB_CREATED` for a job that doesn't exist.
4146

4247
### Changed (type-level only)
4348

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,8 @@ for event in db.crawl("https://www.example.com", hops=1):
211211
print(event)
212212
```
213213

214+
Job names are limited to 30 characters. The crawler reports a create failure such as an overlong name as HTTP 200 with an `errorCode` in the body; `crawl()` raises `APIError` for it rather than yielding `JOB_CREATED`.
215+
214216
For tools that can't block on a long crawl, start the job without watching, poll it, then download the results:
215217

216218
```python

‎src/diffbot/client.py‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,10 @@ def crawl_get_job(self, job_name: str) -> CrawlJob:
305305
@overload
306306
def crawl_download(self, name: str, *, format: Literal["csv"], type: Optional[str] = ..., num: Optional[int] = ...) -> str: ...
307307
@overload
308+
def crawl_download(
309+
self, name: str, *, format: CrawlDownloadFormat = ..., type: Literal["urls"], num: Optional[int] = ...
310+
) -> str: ...
311+
@overload
308312
def crawl_download(
309313
self, name: str, *, format: Literal["json"] = ..., type: Optional[str] = ..., num: Optional[int] = ...
310314
) -> List[CrawlDataRecord]: ...
@@ -323,8 +327,9 @@ def crawl_download(
323327
"""Download a crawl job's results (``GET /v3/crawl/data``).
324328
325329
``format="json"`` (default) returns a list of records; ``format="csv"``
326-
returns the CSV text. ``type`` selects the report (e.g. ``"urls"``) and
327-
``num`` caps the number of records.
330+
returns the CSV text. ``type`` selects the report: ``"urls"`` is always CSV
331+
text, whatever ``format`` says. ``num`` caps the number of records. A JSON
332+
body that is not a list (e.g. an unknown job) raises ``JobError``.
328333
"""
329334
return _crawl_download(self, name, format=format, type=type, num=num)
330335

@@ -623,6 +628,10 @@ async def crawl_get_job(self, job_name: str) -> CrawlJob:
623628
@overload
624629
async def crawl_download(self, name: str, *, format: Literal["csv"], type: Optional[str] = ..., num: Optional[int] = ...) -> str: ...
625630
@overload
631+
async def crawl_download(
632+
self, name: str, *, format: CrawlDownloadFormat = ..., type: Literal["urls"], num: Optional[int] = ...
633+
) -> str: ...
634+
@overload
626635
async def crawl_download(
627636
self, name: str, *, format: Literal["json"] = ..., type: Optional[str] = ..., num: Optional[int] = ...
628637
) -> List[CrawlDataRecord]: ...
@@ -641,8 +650,9 @@ async def crawl_download(
641650
"""Download a crawl job's results (``GET /v3/crawl/data``).
642651
643652
``format="json"`` (default) returns a list of records; ``format="csv"``
644-
returns the CSV text. ``type`` selects the report (e.g. ``"urls"``) and
645-
``num`` caps the number of records.
653+
returns the CSV text. ``type`` selects the report: ``"urls"`` is always CSV
654+
text, whatever ``format`` says. ``num`` caps the number of records. A JSON
655+
body that is not a list (e.g. an unknown job) raises ``JobError``.
646656
"""
647657
return await _crawl_download_async(self, name, format=format, type=type, num=num)
648658

‎src/diffbot/crawl.py‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,9 @@ def crawl(
5151
"""Create a crawler job and yield a JOB_CREATED event. If watch=True, poll until
5252
completion and yield URL_PROCESSED events for each crawled URL.
5353
54+
``job_name`` must be at most 30 characters; the crawler answers an overlong name
55+
with HTTP 200 + ``errorCode`` 505 and creates nothing, which raises ``APIError``.
56+
5457
Recommended pattern for tools that can't block on a long crawl: start with
5558
``crawl(..., watch=False)``, poll :func:`crawl_get_job` until its
5659
``jobStatus.status`` is terminal, then fetch results with :func:`crawl_download`."""
@@ -104,14 +107,16 @@ def crawl(
104107

105108

106109
def _raise_on_create_error(response: Any) -> None:
107-
"""The crawler reports some create failures (e.g. a job name over 30 chars) as HTTP 200
108-
with ``errorCode``/``error`` in the body; surface them instead of returning JOB_CREATED."""
110+
"""The crawler reports some create failures (e.g. a job name over 30 chars, errorCode
111+
505) as HTTP 200 with ``errorCode``/``error`` in the body and creates nothing; surface
112+
them instead of returning JOB_CREATED. The error keeps the real status, body and
113+
headers (``APIError.message`` reads the body's ``error`` field)."""
109114
try:
110115
data = response.json()
111116
except ValueError:
112117
return
113118
if isinstance(data, dict) and data.get("errorCode"):
114-
raise APIError(200, json.dumps({"message": data.get("error") or f"errorCode {data['errorCode']}"}))
119+
raise APIError(response.status_code, response.text, headers=dict(response.headers))
115120

116121

117122
def _build_crawl_params(client: Any, job_name: str, site: str, max_to_crawl: int,
@@ -288,10 +293,18 @@ def _download_params(client: Any, name: str, format: CrawlDownloadFormat, type:
288293
return params
289294

290295

291-
def _decode_download(text: str, format: CrawlDownloadFormat) -> Any:
292-
if format == "csv":
296+
def _decode_download(name: str, text: str, format: CrawlDownloadFormat, type: Optional[str]) -> Any:
297+
# The ``urls`` report is always CSV text, whatever ``format`` says.
298+
if format == "csv" or type == "urls":
293299
return text
294-
return json.loads(text) if text.strip() else []
300+
if not text.strip():
301+
return []
302+
data = json.loads(text)
303+
if not isinstance(data, list):
304+
# e.g. ``{"errorCode": ..., "error": ...}`` for an unknown job
305+
error = data.get("error") if isinstance(data, dict) else None
306+
raise JobError(name, f"Crawl data download failed: {error or 'unexpected response'}")
307+
return data
295308

296309

297310
# The public, overloaded signatures live on ``Diffbot.crawl_download`` /
@@ -310,7 +323,7 @@ def crawl_download(
310323
params=_download_params(client, name, format, type, num),
311324
follow_redirects=True,
312325
)
313-
return _decode_download(response.text, format)
326+
return _decode_download(name, response.text, format, type)
314327

315328

316329
async def crawl_download_async(
@@ -327,4 +340,4 @@ async def crawl_download_async(
327340
params=_download_params(client, name, format, type, num),
328341
follow_redirects=True,
329342
)
330-
return _decode_download(response.text, format)
343+
return _decode_download(name, response.text, format, type)

‎tests/test_crawl.py‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import json
2+
13
import httpx
24
import pytest
35

@@ -189,6 +191,20 @@ def test_crawl_download_missing_job_raises_not_found():
189191
db.crawl_download("nope")
190192

191193

194+
def test_crawl_download_urls_report_is_csv_whatever_the_format():
195+
seen = []
196+
db = make_client(_data_handler(seen, text=URLS_CSV))
197+
assert db.crawl_download("job1", type="urls") == URLS_CSV
198+
assert "format" not in seen[0].url.params
199+
200+
201+
def test_crawl_download_non_list_json_raises_job_error():
202+
db = make_client(_data_handler([], json_body={"errorCode": 500, "error": "No collection record"}))
203+
with pytest.raises(JobError, match="No collection record") as exc_info:
204+
db.crawl_download("nope")
205+
assert exc_info.value.job_name == "nope"
206+
207+
192208
@pytest.mark.anyio
193209
async def test_async_crawl_download():
194210
seen = []
@@ -243,8 +259,11 @@ def handler(request: httpx.Request) -> httpx.Response:
243259
return httpx.Response(200, json={"errorCode": 505, "error": "name is over 30 chars"})
244260

245261
db = make_client(handler)
246-
with pytest.raises(APIError, match="name is over 30 chars"):
262+
with pytest.raises(APIError, match="name is over 30 chars") as exc_info:
247263
next(db.crawl("https://example.com", job_name="x" * 31))
264+
assert exc_info.value.status_code == 200
265+
assert exc_info.value.message == "name is over 30 chars"
266+
assert json.loads(exc_info.value.body)["errorCode"] == 505
248267

249268

250269
@pytest.mark.anyio

‎tests/typing/test_types.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ def _crawl_download_and_account_types() -> None:
8787
assert_type(db.crawl_download("j"), List[CrawlDataRecord])
8888
assert_type(db.crawl_download("j", format="json", num=1), List[CrawlDataRecord])
8989
assert_type(db.crawl_download("j", format="csv", type="urls"), str)
90+
assert_type(db.crawl_download("j", type="urls"), str)
9091
assert_type(db.account(), AccountResponse)
9192
assert_type(db.account(days=1), AccountResponse)
9293
assert_type(db.verify_token(), bool)
@@ -97,6 +98,7 @@ async def _async_misc_types() -> None:
9798
assert_type(await adb.entities("x"), EntitiesResponse)
9899
assert_type(await adb.crawl_get_job("j"), CrawlJob)
99100
assert_type(await adb.crawl_download("j", format="csv"), str)
101+
assert_type(await adb.crawl_download("j", type="urls"), str)
100102
assert_type(await adb.crawl_download("j"), List[CrawlDataRecord])
101103
assert_type(await adb.account(), AccountResponse)
102104
assert_type(await adb.verify_token(), bool)

0 commit comments

Comments
 (0)