Skip to content

Commit 92fc982

Browse files
shixishclaude
andcommitted
feat(dql): send DQL as POST with a JSON body
dql()/dql_parallel() and async twins now POST to the DQL endpoint with a JSON body; the token stays in the query string. Public contract unchanged. extra widens to Mapping[str, Any]. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent b022907 commit 92fc982

7 files changed

Lines changed: 155 additions & 53 deletions

File tree

‎src/diffbot/client.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import pathlib
44
from types import TracebackType
5-
from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Sequence, Type, Union
5+
from typing import Any, AsyncIterator, Dict, Iterator, List, Mapping, Optional, Sequence, Type, Union
66

77
import httpx
88

@@ -215,7 +215,7 @@ def dql(
215215
format: ExportFormat = "json",
216216
filter: Optional[str] = None,
217217
exportspec: Optional[str] = None,
218-
extra: Optional[Dict[str, str]] = None,
218+
extra: Optional[Mapping[str, Any]] = None,
219219
raw: bool = False,
220220
) -> Union[Dict[str, Any], bytes]:
221221
"""Run a DQL query against the Diffbot Knowledge Graph.
@@ -415,7 +415,7 @@ async def dql(
415415
format: ExportFormat = "json",
416416
filter: Optional[str] = None,
417417
exportspec: Optional[str] = None,
418-
extra: Optional[Dict[str, str]] = None,
418+
extra: Optional[Mapping[str, Any]] = None,
419419
raw: bool = False,
420420
) -> Union[Dict[str, Any], bytes]:
421421
"""Run a DQL query against the Diffbot Knowledge Graph.

‎src/diffbot/kg.py‎

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import asyncio
44
import pathlib
55
from concurrent.futures import ThreadPoolExecutor
6-
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union
6+
from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, Sequence, Union
77

88
from ._constants import KG_BASE
99
from .ontology import Ontology
@@ -16,28 +16,29 @@
1616
KG_ONTOLOGY_ENDPOINT = f"{KG_BASE}/kg/ontology"
1717

1818

19-
def _build_dql_params(
20-
client: Any,
19+
def _build_dql_body(
2120
query: str,
2221
size: int,
2322
from_: int,
2423
format: ExportFormat,
2524
filter: Optional[str],
2625
exportspec: Optional[str],
27-
extra: Optional[Dict[str, str]],
26+
extra: Optional[Mapping[str, Any]],
2827
) -> Dict[str, Any]:
29-
params: Dict[str, Any] = {"token": client.token, "query": query, "size": size}
28+
"""JSON body for ``POST /kg/v3/dql`` (``DqlPostRequest``). The token is *not* part
29+
of the body; it travels in the query string, as the spec's security scheme says."""
30+
body: Dict[str, Any] = {"query": query, "size": size}
3031
if from_:
31-
params["from"] = from_
32+
body["from"] = from_
3233
if format != "json":
33-
params["format"] = format
34+
body["format"] = format
3435
if filter is not None:
35-
params["filter"] = filter
36+
body["filter"] = filter
3637
if exportspec is not None:
37-
params["exportspec"] = exportspec
38+
body["exportspec"] = exportspec
3839
if extra:
39-
params.update(extra)
40-
return params
40+
body.update(extra)
41+
return body
4142

4243

4344
def dql(
@@ -49,11 +50,11 @@ def dql(
4950
format: ExportFormat = "json",
5051
filter: Optional[str] = None,
5152
exportspec: Optional[str] = None,
52-
extra: Optional[Dict[str, str]] = None,
53+
extra: Optional[Mapping[str, Any]] = None,
5354
raw: bool = False,
5455
) -> Union[Dict[str, Any], bytes]:
55-
params = _build_dql_params(client, query, size, from_, format, filter, exportspec, extra)
56-
response = client.request("GET", client.dql_url, params=params)
56+
body = _build_dql_body(query, size, from_, format, filter, exportspec, extra)
57+
response = client.request("POST", client.dql_url, params={"token": client.token}, json=body)
5758
return response.content if raw else response.json()
5859

5960

@@ -66,11 +67,11 @@ async def dql_async(
6667
format: ExportFormat = "json",
6768
filter: Optional[str] = None,
6869
exportspec: Optional[str] = None,
69-
extra: Optional[Dict[str, str]] = None,
70+
extra: Optional[Mapping[str, Any]] = None,
7071
raw: bool = False,
7172
) -> Union[Dict[str, Any], bytes]:
72-
params = _build_dql_params(client, query, size, from_, format, filter, exportspec, extra)
73-
response = await client.request("GET", client.dql_url, params=params)
73+
body = _build_dql_body(query, size, from_, format, filter, exportspec, extra)
74+
response = await client.request("POST", client.dql_url, params={"token": client.token}, json=body)
7475
return response.content if raw else response.json()
7576

7677

‎tests/test_dql.py‎

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

@@ -114,3 +116,102 @@ def test_live_dql(db):
114116
assert len(result["data"]) > 0
115117
entity = result["data"][0]["entity"]
116118
assert entity.get("name") == "Diffbot"
119+
120+
121+
"""
122+
DQL is sent as POST with a JSON body
123+
"""
124+
125+
126+
def _capture():
127+
seen = []
128+
129+
def handler(request: httpx.Request) -> httpx.Response:
130+
seen.append(request)
131+
return httpx.Response(200, json={"data": [], "hits": 0})
132+
133+
return seen, handler
134+
135+
136+
def test_dql_posts_json_body_with_token_in_query():
137+
seen, handler = _capture()
138+
db = Diffbot(token="secret-tok", transport=httpx.MockTransport(handler))
139+
db.dql('type:Organization name:"Diffbot"')
140+
(req,) = seen
141+
assert req.method == "POST"
142+
assert req.headers["content-type"] == "application/json"
143+
assert req.url.params["token"] == "secret-tok"
144+
assert "query" not in req.url.params
145+
assert "Diffbot" not in str(req.url)
146+
body = json.loads(req.content)
147+
assert body == {"query": 'type:Organization name:"Diffbot"', "size": 10}
148+
assert "token" not in body
149+
150+
151+
def test_dql_body_defaults_and_options():
152+
seen, handler = _capture()
153+
db = Diffbot(token="t", transport=httpx.MockTransport(handler))
154+
db.dql("q", size=0, from_=5, format="csv", filter="f", exportspec="a;b", extra={"jsonmode": "extended", "n": 3})
155+
body = json.loads(seen[0].content)
156+
assert body == {
157+
"query": "q", "size": 0, "from": 5, "format": "csv", "filter": "f",
158+
"exportspec": "a;b", "jsonmode": "extended", "n": 3,
159+
}
160+
seen.clear()
161+
db.dql("q", format="json", from_=0)
162+
assert json.loads(seen[0].content) == {"query": "q", "size": 10}
163+
164+
165+
def test_dql_long_query_is_not_in_url():
166+
seen, handler = _capture()
167+
db = Diffbot(token="t", transport=httpx.MockTransport(handler))
168+
query = " OR ".join(f'name:"Company {i}"' for i in range(1000))
169+
assert len(query) > 8000
170+
db.dql(query, size=0)
171+
assert len(str(seen[0].url)) < 200
172+
assert json.loads(seen[0].content)["query"] == query
173+
174+
175+
def test_dql_retries_post_on_503():
176+
calls = []
177+
178+
def handler(request: httpx.Request) -> httpx.Response:
179+
calls.append(request.method)
180+
if len(calls) == 1:
181+
return httpx.Response(503, text="busy")
182+
return httpx.Response(200, json={"hits": 1})
183+
184+
from diffbot import RetryPolicy
185+
186+
db = Diffbot(token="t", transport=httpx.MockTransport(handler), retry=RetryPolicy(base_delay=0, jitter=False))
187+
assert db.dql("q", size=0) == {"hits": 1}
188+
assert calls == ["POST", "POST"]
189+
190+
191+
def test_dql_get_escape_hatch_still_works():
192+
seen, handler = _capture()
193+
db = Diffbot(token="t", transport=httpx.MockTransport(handler))
194+
db.request("GET", db.dql_url, params={"token": "t", "query": "q", "size": 1})
195+
assert seen[0].method == "GET"
196+
assert seen[0].url.params["query"] == "q"
197+
198+
199+
@pytest.mark.anyio
200+
async def test_async_dql_posts_json_body_with_token_in_query():
201+
seen, handler = _capture()
202+
db = DiffbotAsync(token="secret-tok", transport=httpx.MockTransport(handler))
203+
await db.dql("type:Person", size=0, from_=2)
204+
(req,) = seen
205+
assert req.method == "POST"
206+
assert req.url.params["token"] == "secret-tok"
207+
assert "query" not in req.url.params
208+
assert json.loads(req.content) == {"query": "type:Person", "size": 0, "from": 2}
209+
210+
211+
@pytest.mark.anyio
212+
async def test_async_dql_parallel_posts():
213+
seen, handler = _capture()
214+
db = DiffbotAsync(token="t", transport=httpx.MockTransport(handler))
215+
await db.dql_parallel([{"query": "a", "size": 0}, {"query": "b", "size": 0}])
216+
assert {r.method for r in seen} == {"POST"}
217+
assert sorted(json.loads(r.content)["query"] for r in seen) == ["a", "b"]

‎tests/test_dql_cli.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,8 @@ def test_cli_ontology_types(ontology_cache):
7979

8080
def test_cli_probe_table(monkeypatch):
8181
def handler(request: httpx.Request) -> httpx.Response:
82-
assert request.url.params["size"] == "0"
83-
hits = 5 if "Diffbot" in request.url.params["query"] else 100
82+
assert json.loads(request.content)["size"] == 0
83+
hits = 5 if "Diffbot" in json.loads(request.content)["query"] else 100
8484
return httpx.Response(200, json={"hits": hits, "results": 0})
8585

8686
use_mock_client(monkeypatch, handler)
@@ -107,7 +107,7 @@ def handler(request):
107107

108108
def test_cli_export_writes_file(monkeypatch, tmp_path):
109109
def handler(request: httpx.Request) -> httpx.Response:
110-
assert request.url.params["format"] == "csv"
110+
assert json.loads(request.content)["format"] == "csv"
111111
return httpx.Response(200, content=b"Name\nDiffbot\n")
112112

113113
use_mock_client(monkeypatch, handler)

‎tests/test_ontology.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def handler(request: httpx.Request) -> httpx.Response:
105105
@pytest.mark.anyio
106106
async def test_async_dql_parallel_runs_all_queries():
107107
def handler(request: httpx.Request) -> httpx.Response:
108-
q = request.url.params["query"]
108+
q = json.loads(request.content)["query"]
109109
hits = 5 if "Diffbot" in q else 100
110110
return httpx.Response(200, json={"hits": hits, "results": 0})
111111

‎tests/test_readme_examples.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ def handler(request: httpx.Request) -> httpx.Response:
144144

145145
def test_readme_sync_dql():
146146
def handler(request: httpx.Request) -> httpx.Response:
147-
assert "Diffbot" in request.url.params["query"]
147+
assert "Diffbot" in json.loads(request.content)["query"]
148148
return httpx.Response(200, json={"data": [{"entity": {"name": "Diffbot"}}]})
149149

150150
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))

‎uv.lock‎

Lines changed: 28 additions & 28 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)