Skip to content

Commit 97d53e4

Browse files
shixishclaude
andcommitted
docs(readme): extract options, dql formats, crawl start/poll/download, account/verify_token
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 51f6700 commit 97d53e4

2 files changed

Lines changed: 210 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,8 +143,20 @@ from diffbot import Diffbot
143143

144144
db = Diffbot(token="YOUR_TOKEN")
145145
data = db.extract("https://www.example.com")
146+
147+
# Optional keyword-only options (per-API field names are type-checked):
148+
article = db.extract(
149+
"https://www.example.com/post",
150+
"article",
151+
fmt="json",
152+
timeout=60000, # server-side fetch timeout in ms (default 30000)
153+
fields=["links", "quotes"],
154+
max_tags=5,
155+
)
146156
```
147157

158+
`timeout` is the Diffbot-side fetch timeout in milliseconds; the SDK raises the HTTP transport timeout to at least `timeout + 10s` so the client never aborts first. `mode` overrides the `fmt="markdown"` → `mode=llm` mapping, and `extra={"proxy": ..., "proxyAuth": ...}` passes anything not named.
159+
148160
### Ask Diffbot LLM
149161
```python
150162
from diffbot import Diffbot
@@ -199,12 +211,47 @@ for event in db.crawl("https://www.example.com", hops=1):
199211
print(event)
200212
```
201213

214+
For tools that can't block on a long crawl, start the job without watching, poll it, then download the results:
215+
216+
```python
217+
import time
218+
from diffbot import Diffbot
219+
220+
db = Diffbot(token="YOUR_TOKEN")
221+
for _ in db.crawl("https://www.example.com", job_name="my-crawl", hops=1):
222+
pass # watch=False (the default): only creates the job
223+
224+
while db.crawl_get_job("my-crawl").get("jobStatus", {}).get("status", 0) in (0, 7):
225+
time.sleep(5) # 0 initializing, 7 in progress; 9 complete
226+
227+
records = db.crawl_download("my-crawl") # list of extracted records
228+
csv_text = db.crawl_download("my-crawl", format="csv") # str
229+
```
230+
231+
`crawl_get_job` returns `{}` for a job that doesn't exist (the TypeScript SDK returns `undefined`).
232+
202233
### Query the Knowledge Graph
203234
```python
204235
from diffbot import Diffbot
205236

206237
db = Diffbot(token="YOUR_TOKEN")
207238
results = db.dql('type:Organization name:"Diffbot"')
239+
240+
# The return type follows `format`: DqlResponse (json), str (csv), bytes (xls/xlsx
241+
# or raw=True), or an iterator of entities (jsonl).
242+
csv_text = db.dql('type:Organization name:"Diffbot"', size=5, format="csv")
243+
for entity in db.dql('type:Organization name:"Diffbot"', size=5, format="jsonl"):
244+
print(entity["entity"]["name"])
245+
```
246+
247+
### Account and token check
248+
```python
249+
from diffbot import Diffbot
250+
251+
db = Diffbot(token="YOUR_TOKEN")
252+
if not db.verify_token(): # True/False; only an auth failure means False
253+
raise SystemExit("Diffbot token rejected")
254+
usage = db.account(days=7).get("usage", []) # free call; never print the whole response
208255
```
209256

210257
### Web Search
@@ -248,6 +295,10 @@ async def main():
248295
data = await db.extract("https://www.example.com")
249296
print(data)
250297

298+
article = await db.extract(
299+
"https://www.example.com/post", "article", fmt="json", timeout=60000, fields=["links"]
300+
)
301+
251302
asyncio.run(main())
252303
```
253304

@@ -301,6 +352,24 @@ async def main():
301352
asyncio.run(main())
302353
```
303354

355+
Start, poll, then download, without blocking inside one call:
356+
357+
```python
358+
import asyncio
359+
from diffbot import DiffbotAsync
360+
361+
async def main():
362+
async with DiffbotAsync(token="YOUR_TOKEN") as db:
363+
async for _ in db.crawl("https://www.example.com", job_name="my-crawl", hops=1):
364+
pass # watch=False (the default): only creates the job
365+
while (await db.crawl_get_job("my-crawl")).get("jobStatus", {}).get("status", 0) in (0, 7):
366+
await asyncio.sleep(5)
367+
records = await db.crawl_download("my-crawl")
368+
csv_text = await db.crawl_download("my-crawl", format="csv")
369+
370+
asyncio.run(main())
371+
```
372+
304373
### Query the Knowledge Graph
305374
```python
306375
import asyncio
@@ -311,6 +380,24 @@ async def main():
311380
results = await db.dql('type:Organization name:"Diffbot"')
312381
print(results)
313382

383+
csv_text = await db.dql('type:Organization name:"Diffbot"', size=5, format="csv")
384+
async for entity in await db.dql('type:Organization name:"Diffbot"', size=5, format="jsonl"):
385+
print(entity["entity"]["name"])
386+
387+
asyncio.run(main())
388+
```
389+
390+
### Account and token check
391+
```python
392+
import asyncio
393+
from diffbot import DiffbotAsync
394+
395+
async def main():
396+
async with DiffbotAsync(token="YOUR_TOKEN") as db:
397+
if not await db.verify_token():
398+
raise SystemExit("Diffbot token rejected")
399+
usage = (await db.account(days=7)).get("usage", [])
400+
314401
asyncio.run(main())
315402
```
316403

‎tests/test_readme_examples.py‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,3 +306,126 @@ def handler(request: httpx.Request) -> httpx.Response:
306306
db = Diffbot(token=resolve_token(), transport=httpx.MockTransport(handler))
307307
data = db.extract("https://www.example.com")
308308
assert "objects" in data
309+
310+
311+
# ---------------------------------------------------------------------------
312+
# Extract options, DQL formats, crawl start/poll/download, account
313+
# ---------------------------------------------------------------------------
314+
315+
def test_readme_sync_extract_options():
316+
def handler(request: httpx.Request) -> httpx.Response:
317+
params = request.url.params
318+
assert request.url.path == "/v3/article"
319+
assert params["timeout"] == "60000"
320+
assert params["fields"] == "links,quotes"
321+
assert params["maxTags"] == "5"
322+
assert "mode" not in params # fmt="json" -> no llm mapping
323+
assert request.extensions["timeout"]["read"] == 70
324+
return httpx.Response(200, json={"objects": [{"title": "Post"}]})
325+
326+
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
327+
article = db.extract(
328+
"https://www.example.com/post",
329+
"article",
330+
fmt="json",
331+
timeout=60000,
332+
fields=["links", "quotes"],
333+
max_tags=5,
334+
)
335+
assert article["objects"][0]["title"] == "Post"
336+
337+
338+
def test_readme_sync_dql_formats():
339+
def handler(request: httpx.Request) -> httpx.Response:
340+
fmt = json.loads(request.content)["format"]
341+
if fmt == "csv":
342+
return httpx.Response(200, text="name\nDiffbot\n")
343+
return httpx.Response(200, text='{"entity": {"name": "Diffbot"}}\n')
344+
345+
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
346+
csv_text = db.dql('type:Organization name:"Diffbot"', size=5, format="csv")
347+
assert csv_text == "name\nDiffbot\n"
348+
names = [e["entity"]["name"] for e in db.dql('type:Organization name:"Diffbot"', size=5, format="jsonl")]
349+
assert names == ["Diffbot"]
350+
351+
352+
def _crawl_flow_handler(request: httpx.Request) -> httpx.Response:
353+
if request.url.path == "/v3/crawl/data":
354+
if request.url.params.get("format") == "csv":
355+
return httpx.Response(200, text="Url\nhttps://www.example.com\n")
356+
return httpx.Response(200, json=[{"pageUrl": "https://www.example.com"}])
357+
if "seeds" in request.url.params:
358+
return httpx.Response(200, json={"jobs": [{"name": "my-crawl"}]})
359+
return httpx.Response(200, json={"jobs": [{"name": "my-crawl", "jobStatus": {"status": 9}}]})
360+
361+
362+
def test_readme_sync_crawl_start_poll_download():
363+
db = Diffbot(token="test-token", transport=httpx.MockTransport(_crawl_flow_handler))
364+
for _ in db.crawl("https://www.example.com", job_name="my-crawl", hops=1):
365+
pass
366+
while db.crawl_get_job("my-crawl").get("jobStatus", {}).get("status", 0) in (0, 7):
367+
raise AssertionError("job should already be complete")
368+
records = db.crawl_download("my-crawl")
369+
csv_text = db.crawl_download("my-crawl", format="csv")
370+
assert records == [{"pageUrl": "https://www.example.com"}]
371+
assert csv_text.startswith("Url")
372+
assert db.crawl_get_job.__doc__ and "{}" in db.crawl_get_job.__doc__
373+
374+
375+
def test_readme_sync_account_and_verify_token():
376+
def handler(request: httpx.Request) -> httpx.Response:
377+
assert request.url.path == "/v4/account"
378+
return httpx.Response(200, json={"usage": [{"date": "2026-11-16", "credits": 1}]})
379+
380+
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
381+
assert db.verify_token()
382+
usage = db.account(days=7).get("usage", [])
383+
assert usage[0]["credits"] == 1
384+
385+
386+
@pytest.mark.anyio
387+
async def test_readme_async_extract_options():
388+
def handler(request: httpx.Request) -> httpx.Response:
389+
assert request.url.params["fields"] == "links"
390+
return httpx.Response(200, json={"objects": []})
391+
392+
async with DiffbotAsync(token="test-token", transport=httpx.MockTransport(handler)) as db:
393+
await db.extract("https://www.example.com", "article", fmt="json", timeout=60000, fields=["links"])
394+
395+
396+
@pytest.mark.anyio
397+
async def test_readme_async_dql_formats():
398+
def handler(request: httpx.Request) -> httpx.Response:
399+
if json.loads(request.content)["format"] == "csv":
400+
return httpx.Response(200, text="name\nDiffbot\n")
401+
return httpx.Response(200, text='{"entity": {"name": "Diffbot"}}\n')
402+
403+
async with DiffbotAsync(token="test-token", transport=httpx.MockTransport(handler)) as db:
404+
csv_text = await db.dql('type:Organization name:"Diffbot"', size=5, format="csv")
405+
names = [e["entity"]["name"] async for e in await db.dql('type:Organization name:"Diffbot"', size=5, format="jsonl")]
406+
assert csv_text == "name\nDiffbot\n"
407+
assert names == ["Diffbot"]
408+
409+
410+
@pytest.mark.anyio
411+
async def test_readme_async_crawl_start_poll_download():
412+
async with DiffbotAsync(token="test-token", transport=httpx.MockTransport(_crawl_flow_handler)) as db:
413+
async for _ in db.crawl("https://www.example.com", job_name="my-crawl", hops=1):
414+
pass
415+
while (await db.crawl_get_job("my-crawl")).get("jobStatus", {}).get("status", 0) in (0, 7):
416+
raise AssertionError("job should already be complete")
417+
records = await db.crawl_download("my-crawl")
418+
csv_text = await db.crawl_download("my-crawl", format="csv")
419+
assert records == [{"pageUrl": "https://www.example.com"}]
420+
assert csv_text.startswith("Url")
421+
422+
423+
@pytest.mark.anyio
424+
async def test_readme_async_account_and_verify_token():
425+
def handler(request: httpx.Request) -> httpx.Response:
426+
return httpx.Response(200, json={"usage": []})
427+
428+
async with DiffbotAsync(token="test-token", transport=httpx.MockTransport(handler)) as db:
429+
assert await db.verify_token()
430+
usage = (await db.account(days=7)).get("usage", [])
431+
assert usage == []

0 commit comments

Comments
 (0)