lexapi-client 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lexapi/__init__.py +132 -0
- lexapi/_base.py +122 -0
- lexapi/_meta.py +14 -0
- lexapi/_payloads.py +160 -0
- lexapi/_response.py +158 -0
- lexapi/_retry.py +148 -0
- lexapi/async_client.py +417 -0
- lexapi/citations.py +231 -0
- lexapi/client.py +491 -0
- lexapi/errors.py +261 -0
- lexapi/export.py +253 -0
- lexapi/models.py +1253 -0
- lexapi/py.typed +0 -0
- lexapi/webhooks.py +220 -0
- lexapi_client-0.1.0.dist-info/METADATA +310 -0
- lexapi_client-0.1.0.dist-info/RECORD +17 -0
- lexapi_client-0.1.0.dist-info/WHEEL +4 -0
lexapi/py.typed
ADDED
|
File without changes
|
lexapi/webhooks.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Webhooks resource namespace: ``client.webhooks.*``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterator, Iterator
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from lexapi._payloads import drop_none
|
|
9
|
+
from lexapi.models import (
|
|
10
|
+
WebhookDeliveriesResponse,
|
|
11
|
+
WebhookDelivery,
|
|
12
|
+
WebhookListResponse,
|
|
13
|
+
WebhookResponse,
|
|
14
|
+
WebhookTestResponse,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
18
|
+
from lexapi.async_client import AsyncLexAPI
|
|
19
|
+
from lexapi.client import LexAPI
|
|
20
|
+
|
|
21
|
+
_DELIVERIES_PAGE_SIZE = 50
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _update_body(
|
|
25
|
+
name: str | None, url: str | None, search_criteria: dict | None, status: str | None
|
|
26
|
+
) -> dict:
|
|
27
|
+
return drop_none(
|
|
28
|
+
{"name": name, "url": url, "searchCriteria": search_criteria, "status": status}
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class WebhooksResource:
|
|
33
|
+
"""Synchronous ``/webhooks`` operations (``client.webhooks``)."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, client: LexAPI) -> None:
|
|
36
|
+
self._client = client
|
|
37
|
+
|
|
38
|
+
def list(self) -> WebhookListResponse:
|
|
39
|
+
"""GET /webhooks — every webhook owned by the caller, newest first.
|
|
40
|
+
|
|
41
|
+
Secrets are never returned here — only on :meth:`create`.
|
|
42
|
+
"""
|
|
43
|
+
return self._client._request("GET", "/webhooks", cast=WebhookListResponse)
|
|
44
|
+
|
|
45
|
+
def create(
|
|
46
|
+
self,
|
|
47
|
+
name: str,
|
|
48
|
+
url: str,
|
|
49
|
+
search_criteria: dict,
|
|
50
|
+
*,
|
|
51
|
+
secret: str | None = None,
|
|
52
|
+
) -> WebhookResponse:
|
|
53
|
+
"""POST /webhooks — subscribe ``url`` to documents matching
|
|
54
|
+
``search_criteria`` (same shape as a /search request body).
|
|
55
|
+
|
|
56
|
+
If ``secret`` is omitted the server generates one; **store
|
|
57
|
+
``response.webhook.secret`` now** — this is the only response that
|
|
58
|
+
ever contains it. Creation fails with 400 at the tier's webhook cap.
|
|
59
|
+
"""
|
|
60
|
+
body = drop_none(
|
|
61
|
+
{"name": name, "url": url, "searchCriteria": search_criteria, "secret": secret}
|
|
62
|
+
)
|
|
63
|
+
return self._client._request("POST", "/webhooks", json=body, cast=WebhookResponse)
|
|
64
|
+
|
|
65
|
+
def get(self, webhook_id: str) -> WebhookResponse:
|
|
66
|
+
"""GET /webhooks/{id} — full details incl. up to 20 recent deliveries."""
|
|
67
|
+
return self._client._request(
|
|
68
|
+
"GET", f"/webhooks/{webhook_id}", cast=WebhookResponse
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
def update(
|
|
72
|
+
self,
|
|
73
|
+
webhook_id: str,
|
|
74
|
+
*,
|
|
75
|
+
name: str | None = None,
|
|
76
|
+
url: str | None = None,
|
|
77
|
+
search_criteria: dict | None = None,
|
|
78
|
+
status: str | None = None,
|
|
79
|
+
) -> WebhookResponse:
|
|
80
|
+
"""PUT /webhooks/{id} — partial update; only passed fields change.
|
|
81
|
+
|
|
82
|
+
``status="ACTIVE"`` also resets ``consecutiveFailures`` to zero —
|
|
83
|
+
that's how you re-enable a webhook the system auto-paused.
|
|
84
|
+
"""
|
|
85
|
+
return self._client._request(
|
|
86
|
+
"PUT",
|
|
87
|
+
f"/webhooks/{webhook_id}",
|
|
88
|
+
json=_update_body(name, url, search_criteria, status),
|
|
89
|
+
cast=WebhookResponse,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def delete(self, webhook_id: str) -> None:
|
|
93
|
+
"""DELETE /webhooks/{id} — permanent, cascades to delivery history.
|
|
94
|
+
|
|
95
|
+
Returns ``None`` on the 204 success; re-deletes raise
|
|
96
|
+
:class:`~lexapi.NotFoundError`.
|
|
97
|
+
"""
|
|
98
|
+
self._client._request("DELETE", f"/webhooks/{webhook_id}")
|
|
99
|
+
|
|
100
|
+
def test(self, webhook_id: str) -> WebhookTestResponse:
|
|
101
|
+
"""POST /webhooks/{id}/test — synchronously deliver a ``webhook.test``
|
|
102
|
+
payload (HMAC-SHA256 signed via ``X-Webhook-Signature``).
|
|
103
|
+
|
|
104
|
+
A failed upstream delivery is still HTTP 200 — check
|
|
105
|
+
``response.ok`` and ``response.delivery.error_message``.
|
|
106
|
+
"""
|
|
107
|
+
return self._client._request(
|
|
108
|
+
"POST", f"/webhooks/{webhook_id}/test", cast=WebhookTestResponse
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
def deliveries(
|
|
112
|
+
self, webhook_id: str, *, limit: int | None = None, offset: int | None = None
|
|
113
|
+
) -> WebhookDeliveriesResponse:
|
|
114
|
+
"""GET /webhooks/{id}/deliveries — one page of delivery history."""
|
|
115
|
+
return self._client._request(
|
|
116
|
+
"GET",
|
|
117
|
+
f"/webhooks/{webhook_id}/deliveries",
|
|
118
|
+
params=drop_none({"limit": limit, "offset": offset}),
|
|
119
|
+
cast=WebhookDeliveriesResponse,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
def iter_deliveries(
|
|
123
|
+
self, webhook_id: str, *, page_size: int = _DELIVERIES_PAGE_SIZE
|
|
124
|
+
) -> Iterator[WebhookDelivery]:
|
|
125
|
+
"""Iterate the full delivery history, walking offset pages transparently."""
|
|
126
|
+
offset = 0
|
|
127
|
+
while True:
|
|
128
|
+
page = self.deliveries(webhook_id, limit=page_size, offset=offset)
|
|
129
|
+
deliveries = page.deliveries
|
|
130
|
+
yield from deliveries
|
|
131
|
+
offset += len(deliveries)
|
|
132
|
+
total = page.total
|
|
133
|
+
if not deliveries or (total is not None and offset >= total):
|
|
134
|
+
return
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class AsyncWebhooksResource:
|
|
138
|
+
"""Asynchronous ``/webhooks`` operations (``client.webhooks``)."""
|
|
139
|
+
|
|
140
|
+
def __init__(self, client: AsyncLexAPI) -> None:
|
|
141
|
+
self._client = client
|
|
142
|
+
|
|
143
|
+
async def list(self) -> WebhookListResponse:
|
|
144
|
+
"""GET /webhooks — see :meth:`WebhooksResource.list`."""
|
|
145
|
+
return await self._client._request("GET", "/webhooks", cast=WebhookListResponse)
|
|
146
|
+
|
|
147
|
+
async def create(
|
|
148
|
+
self,
|
|
149
|
+
name: str,
|
|
150
|
+
url: str,
|
|
151
|
+
search_criteria: dict,
|
|
152
|
+
*,
|
|
153
|
+
secret: str | None = None,
|
|
154
|
+
) -> WebhookResponse:
|
|
155
|
+
"""POST /webhooks — see :meth:`WebhooksResource.create`."""
|
|
156
|
+
body = drop_none(
|
|
157
|
+
{"name": name, "url": url, "searchCriteria": search_criteria, "secret": secret}
|
|
158
|
+
)
|
|
159
|
+
return await self._client._request(
|
|
160
|
+
"POST", "/webhooks", json=body, cast=WebhookResponse
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
async def get(self, webhook_id: str) -> WebhookResponse:
|
|
164
|
+
"""GET /webhooks/{id} — see :meth:`WebhooksResource.get`."""
|
|
165
|
+
return await self._client._request(
|
|
166
|
+
"GET", f"/webhooks/{webhook_id}", cast=WebhookResponse
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
async def update(
|
|
170
|
+
self,
|
|
171
|
+
webhook_id: str,
|
|
172
|
+
*,
|
|
173
|
+
name: str | None = None,
|
|
174
|
+
url: str | None = None,
|
|
175
|
+
search_criteria: dict | None = None,
|
|
176
|
+
status: str | None = None,
|
|
177
|
+
) -> WebhookResponse:
|
|
178
|
+
"""PUT /webhooks/{id} — see :meth:`WebhooksResource.update`."""
|
|
179
|
+
return await self._client._request(
|
|
180
|
+
"PUT",
|
|
181
|
+
f"/webhooks/{webhook_id}",
|
|
182
|
+
json=_update_body(name, url, search_criteria, status),
|
|
183
|
+
cast=WebhookResponse,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
async def delete(self, webhook_id: str) -> None:
|
|
187
|
+
"""DELETE /webhooks/{id} — see :meth:`WebhooksResource.delete`."""
|
|
188
|
+
await self._client._request("DELETE", f"/webhooks/{webhook_id}")
|
|
189
|
+
|
|
190
|
+
async def test(self, webhook_id: str) -> WebhookTestResponse:
|
|
191
|
+
"""POST /webhooks/{id}/test — see :meth:`WebhooksResource.test`."""
|
|
192
|
+
return await self._client._request(
|
|
193
|
+
"POST", f"/webhooks/{webhook_id}/test", cast=WebhookTestResponse
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
async def deliveries(
|
|
197
|
+
self, webhook_id: str, *, limit: int | None = None, offset: int | None = None
|
|
198
|
+
) -> WebhookDeliveriesResponse:
|
|
199
|
+
"""GET /webhooks/{id}/deliveries — see :meth:`WebhooksResource.deliveries`."""
|
|
200
|
+
return await self._client._request(
|
|
201
|
+
"GET",
|
|
202
|
+
f"/webhooks/{webhook_id}/deliveries",
|
|
203
|
+
params=drop_none({"limit": limit, "offset": offset}),
|
|
204
|
+
cast=WebhookDeliveriesResponse,
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
async def iter_deliveries(
|
|
208
|
+
self, webhook_id: str, *, page_size: int = _DELIVERIES_PAGE_SIZE
|
|
209
|
+
) -> AsyncIterator[WebhookDelivery]:
|
|
210
|
+
"""Async-iterate the full delivery history across offset pages."""
|
|
211
|
+
offset = 0
|
|
212
|
+
while True:
|
|
213
|
+
page = await self.deliveries(webhook_id, limit=page_size, offset=offset)
|
|
214
|
+
deliveries = page.deliveries
|
|
215
|
+
for delivery in deliveries:
|
|
216
|
+
yield delivery
|
|
217
|
+
offset += len(deliveries)
|
|
218
|
+
total = page.total
|
|
219
|
+
if not deliveries or (total is not None and offset >= total):
|
|
220
|
+
return
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lexapi-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for LexAPI - European legal data, made queryable.
|
|
5
|
+
Project-URL: Homepage, https://lex-api.com
|
|
6
|
+
Project-URL: Documentation, https://lex-api.com/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/Lex-API/lexapi-python
|
|
8
|
+
Project-URL: Issues, https://github.com/Lex-API/lexapi-python/issues
|
|
9
|
+
Author-email: LexAPI <support@lex-api.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
Keywords: api,eu,eur-lex,law,legal,sdk
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Requires-Dist: httpx<1,>=0.27
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
20
|
+
Requires-Dist: ruff>=0.4; extra == 'dev'
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# lexapi (Python)
|
|
24
|
+
|
|
25
|
+
Official Python SDK for [LexAPI](https://lex-api.com) — European legal data, made queryable. EUR-Lex, CJEU case law, and the Official Journal behind one REST API.
|
|
26
|
+
|
|
27
|
+
> **Status: pre-release scaffold (0.x).** API coverage and installation instructions below are placeholders until the first PyPI release. See [PLAN.md](PLAN.md).
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install lexapi-client
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
> The PyPI distribution is `lexapi-client` (same name as npm’s `@lexapi/client`); the import is `lexapi` — `from lexapi import LexAPI`.
|
|
36
|
+
|
|
37
|
+
## Quickstart
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from lexapi import LexAPI
|
|
41
|
+
|
|
42
|
+
client = LexAPI(api_key="lex_...") # or set LEXAPI_API_KEY
|
|
43
|
+
info = client.get_info()
|
|
44
|
+
print(info["subscription"]["tier"], info["usage"]["remaining"])
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Keys come from the [LexAPI dashboard](https://lex-api.com) and are prefixed `lex_`. Keep them server-side — never ship them in client-side code.
|
|
48
|
+
|
|
49
|
+
### Search
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
results = client.search(
|
|
53
|
+
"cybersecurity",
|
|
54
|
+
author=["court-of-justice"],
|
|
55
|
+
year=2024,
|
|
56
|
+
document_type="judgment",
|
|
57
|
+
max_pages=1,
|
|
58
|
+
)
|
|
59
|
+
for hit in results.results:
|
|
60
|
+
print(hit.celex, hit.document_type_code, hit.title)
|
|
61
|
+
|
|
62
|
+
# Capping is surfaced, never hidden:
|
|
63
|
+
if results.truncated:
|
|
64
|
+
print("tier-capped:", results.truncated_reason)
|
|
65
|
+
if results.partial:
|
|
66
|
+
print("an upstream page timed out:", results.partial_reason)
|
|
67
|
+
if results.post_filtered_by:
|
|
68
|
+
print("controller post-filter fired on:", results.post_filtered_by)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Documents
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
doc = client.get_document("32016R0679", language="en").document
|
|
75
|
+
print(doc.title, doc.date_of_document_iso)
|
|
76
|
+
for article in doc.content.articles[:3]:
|
|
77
|
+
print(article.number, article.title)
|
|
78
|
+
|
|
79
|
+
# Trim the payload: only metadata + one article
|
|
80
|
+
resp = client.get_document("32016R0679", include=["metadata", "articles"], article_id="17")
|
|
81
|
+
print(resp.source) # "corpus" or "live" (X-Source header)
|
|
82
|
+
|
|
83
|
+
# Batch — per-CELEX failures don't abort the batch
|
|
84
|
+
batch = client.get_documents_batch(["32016R0679", "62018CJ0311"])
|
|
85
|
+
print(batch.successful, "ok /", batch.failed, "failed")
|
|
86
|
+
if batch.trimmed: # tier ceiling hit — mirrored from X-Warning too
|
|
87
|
+
print(batch.trimmed_reason)
|
|
88
|
+
|
|
89
|
+
recent = client.get_recent_documents(days=3, document_type="regulation")
|
|
90
|
+
by_url = client.get_document_by_url(
|
|
91
|
+
"https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32016R0679"
|
|
92
|
+
)
|
|
93
|
+
meta = client.get_document_metadata("32016R0679").metadata # faster, no body parse
|
|
94
|
+
celex = client.resolve("ECLI:EU:C:2020:559").celex # CELEX/URL/ELI/ECLI → CELEX
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Typed responses stay mapping-compatible (`results["totalResults"]` works) and
|
|
98
|
+
every typed model keeps the raw payload on `.raw`.
|
|
99
|
+
|
|
100
|
+
### Citations
|
|
101
|
+
|
|
102
|
+
The typed citation graph lives under `client.citations`:
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
client.citations.extract("32016R0679") # crawl + persist edges (idempotent)
|
|
106
|
+
|
|
107
|
+
inbound = client.citations.cited_by("31995L0046", citation_type="repeal", limit=50)
|
|
108
|
+
print(inbound.total_citations, "edges from", inbound.unique_documents, "documents")
|
|
109
|
+
|
|
110
|
+
outbound = client.citations.cites("32016R0679")
|
|
111
|
+
network = client.citations.network("32016R0679", limit=100)
|
|
112
|
+
if network.partial: # server-side budget expired — 200, not an error
|
|
113
|
+
print(network.message)
|
|
114
|
+
|
|
115
|
+
path = client.citations.path("32016R0679", "31995L0046", max_depth=4)
|
|
116
|
+
if path.found:
|
|
117
|
+
print(" -> ".join(node.celex_number for node in path.path))
|
|
118
|
+
|
|
119
|
+
related = client.citations.related("32016R0679", limit=10) # bibliographic coupling
|
|
120
|
+
stats = client.citations.stats()
|
|
121
|
+
print(stats.most_cited[0].celex_number)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### Semantic search
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
# Case law (CJEU) — concept queries, similarity-ranked
|
|
128
|
+
resp = client.semantic_search(
|
|
129
|
+
"transfer of personal data to third countries",
|
|
130
|
+
min_score=0.5, # widen recall past the ~0.7 default relevance floor
|
|
131
|
+
limit=10,
|
|
132
|
+
)
|
|
133
|
+
for hit in resp.results:
|
|
134
|
+
print(f"{hit.score:.2f}", hit.celex, hit.case_number, hit.case_name)
|
|
135
|
+
if resp.hint: # present only on low-confidence (best-effort) responses
|
|
136
|
+
print(resp.hint)
|
|
137
|
+
|
|
138
|
+
# HyDE query rewriting for terse/keyword queries — 15 credits instead of 5
|
|
139
|
+
resp = client.semantic_search("credit scoring article 22", hyde=True)
|
|
140
|
+
print(resp.hyde) # False means the LLM fell back — premium auto-refunded
|
|
141
|
+
print(resp.units_charged) # 15 when HyDE ran, 5 after a fallback
|
|
142
|
+
print(resp.hypothetical_document) # the LLM-drafted passage (when HyDE ran)
|
|
143
|
+
|
|
144
|
+
# Legislation — article-level matches (HyDE is case-law only)
|
|
145
|
+
laws = client.semantic_legislation_search("right to be forgotten", limit=5)
|
|
146
|
+
for hit in laws.results:
|
|
147
|
+
print(hit.law_id, hit.article_ref, hit.law_title)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### Webhooks
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
# The secret is returned ONLY on create — store it to verify X-Webhook-Signature
|
|
154
|
+
created = client.webhooks.create(
|
|
155
|
+
"New CJEU judgments",
|
|
156
|
+
"https://example.com/webhooks/lexapi",
|
|
157
|
+
{"documentType": "judgment", "author": ["court-of-justice"]}, # /search body shape
|
|
158
|
+
)
|
|
159
|
+
secret = created.webhook.secret
|
|
160
|
+
|
|
161
|
+
hooks = client.webhooks.list()
|
|
162
|
+
hook = client.webhooks.get(created.webhook.id) # incl. 20 recent deliveries
|
|
163
|
+
client.webhooks.update(hook.webhook.id, status="ACTIVE") # also resets failure counter
|
|
164
|
+
result = client.webhooks.test(hook.webhook.id) # synchronous test delivery
|
|
165
|
+
if not result.ok: # HTTP 200 either way
|
|
166
|
+
print(result.delivery.error_message)
|
|
167
|
+
|
|
168
|
+
page = client.webhooks.deliveries(hook.webhook.id, limit=50)
|
|
169
|
+
for delivery in client.webhooks.iter_deliveries(hook.webhook.id): # walks all pages
|
|
170
|
+
print(delivery.status, delivery.response_status)
|
|
171
|
+
|
|
172
|
+
client.webhooks.delete(hook.webhook.id)
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Corpus export (BUSINESS tier)
|
|
176
|
+
|
|
177
|
+
`export()` streams NDJSON rows with constant memory; the `_meta` /
|
|
178
|
+
`_done` envelopes and export headers are exposed on the stream:
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
with client.export(document_type="regulation", date_from="2024-01-01", limit=10_000) as stream:
|
|
182
|
+
print(stream.total, stream.streaming) # X-Export-Total / X-Export-Streaming
|
|
183
|
+
for row in stream: # one dict per corpus row
|
|
184
|
+
ingest(row["celex"], row.get("parsedContent"))
|
|
185
|
+
print(stream.meta) # leading _meta envelope
|
|
186
|
+
print(stream.done, stream.truncated) # trailing _done line / row-cap flag
|
|
187
|
+
|
|
188
|
+
# Async
|
|
189
|
+
async with await client.export(fetched_since="2026-06-01T00:00:00Z") as stream:
|
|
190
|
+
async for row in stream:
|
|
191
|
+
ingest(row)
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
### Async
|
|
195
|
+
|
|
196
|
+
Every operation is also available on the async client:
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
import asyncio
|
|
200
|
+
from lexapi import AsyncLexAPI
|
|
201
|
+
|
|
202
|
+
async def main():
|
|
203
|
+
async with AsyncLexAPI() as client: # LEXAPI_API_KEY from the env
|
|
204
|
+
info = await client.get_info()
|
|
205
|
+
print(info["service"])
|
|
206
|
+
|
|
207
|
+
asyncio.run(main())
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
### Credit visibility
|
|
211
|
+
|
|
212
|
+
Every response wrapper exposes the pricing-v2 credit envelope without
|
|
213
|
+
losing access to the raw body:
|
|
214
|
+
|
|
215
|
+
```python
|
|
216
|
+
info = client.get_info()
|
|
217
|
+
info["usage"] # raw body access still works (Mapping)
|
|
218
|
+
info.units_charged # credits this request cost (0 for /info)
|
|
219
|
+
info.credits_remaining # credits.remaining, falling back to usage.remaining
|
|
220
|
+
info.resets_at # ISO-8601 timestamp of the next quota reset
|
|
221
|
+
info.credits # full typed CreditsInfo (None on legacy daily-call accounts)
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
### Typed errors
|
|
225
|
+
|
|
226
|
+
All non-2xx responses raise a typed exception mirroring the API's stable
|
|
227
|
+
error-code enum (both the typed envelope and the legacy bare `{"error": ...}`
|
|
228
|
+
shape are handled):
|
|
229
|
+
|
|
230
|
+
```python
|
|
231
|
+
from lexapi import (
|
|
232
|
+
LexAPIError, # base — code / message / status / details / body
|
|
233
|
+
NotFoundError, # 404 NOT_FOUND
|
|
234
|
+
InvalidCelexError, # 400 INVALID_CELEX
|
|
235
|
+
RateLimitedError, # 429 RATE_LIMITED — .retry_after (seconds)
|
|
236
|
+
CreditsExhaustedError,# 402 CREDITS_EXHAUSTED — .resets_at
|
|
237
|
+
TierForbiddenError, # 403 TIER_FORBIDDEN
|
|
238
|
+
UpstreamError, # 502 UPSTREAM_ERROR
|
|
239
|
+
TimeoutError, # 504 TIMEOUT (server-side upstream timeout, retry-safe)
|
|
240
|
+
AuthenticationError, # 401 — missing/invalid/revoked key
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
try:
|
|
244
|
+
client.get_info()
|
|
245
|
+
except RateLimitedError as err:
|
|
246
|
+
print(f"rate limited, retry in {err.retry_after}s")
|
|
247
|
+
except LexAPIError as err:
|
|
248
|
+
print(err.code, err.status, err.message)
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
### Retries
|
|
252
|
+
|
|
253
|
+
Idempotent requests are retried automatically (default: up to 3 retries on
|
|
254
|
+
429/502/503/504 and connect errors) with exponential backoff + full jitter,
|
|
255
|
+
honoring the server's `Retry-After` header when present. Non-idempotent
|
|
256
|
+
POSTs are only retried on 429 and connect-phase failures.
|
|
257
|
+
|
|
258
|
+
```python
|
|
259
|
+
from lexapi import LexAPI, RetryConfig
|
|
260
|
+
|
|
261
|
+
client = LexAPI(max_retries=5) # just the budget
|
|
262
|
+
client = LexAPI(retry_config=RetryConfig( # full control
|
|
263
|
+
max_retries=2, backoff_base=1.0, backoff_cap=10.0,
|
|
264
|
+
))
|
|
265
|
+
client = LexAPI(max_retries=0) # disable retries
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
### Configuration
|
|
269
|
+
|
|
270
|
+
```python
|
|
271
|
+
client = LexAPI(
|
|
272
|
+
api_key="lex_...", # or LEXAPI_API_KEY env var
|
|
273
|
+
base_url="https://lex-api.com/api/v1",
|
|
274
|
+
timeout=60.0, # read/overall seconds (or an httpx.Timeout)
|
|
275
|
+
connect_timeout=10.0,
|
|
276
|
+
user_agent_suffix="myapp/1.0", # appended to lexapi-python/<version>
|
|
277
|
+
)
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
## Point-in-time versions
|
|
281
|
+
|
|
282
|
+
> Requires a LexAPI deployment with the point-in-time endpoints (lex-api PR #72).
|
|
283
|
+
> Versions are LexAPI *observation snapshots* — the document as fetched — not
|
|
284
|
+
> legal in-force reconstructions; history begins at first ingestion.
|
|
285
|
+
|
|
286
|
+
```python
|
|
287
|
+
history = client.list_document_versions("32016R0679")
|
|
288
|
+
print(history.current_version, history.tracked_since)
|
|
289
|
+
for v in history.versions:
|
|
290
|
+
print(v.version, v.fetched_at, v.content_hash, "(current)" if v.is_current else "")
|
|
291
|
+
|
|
292
|
+
snapshot = client.get_document_version("32016R0679", 2)
|
|
293
|
+
print(snapshot.document.parsed_content)
|
|
294
|
+
|
|
295
|
+
as_of = client.get_document_at_date("32016R0679", "2026-03-20")
|
|
296
|
+
print(as_of.as_of, as_of.document.version)
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
Each call costs 1 credit. Dates before the document entered the corpus raise
|
|
300
|
+
`NotFoundError` with the tracking start date in the message.
|
|
301
|
+
|
|
302
|
+
## Development
|
|
303
|
+
|
|
304
|
+
```bash
|
|
305
|
+
pip install -e ".[dev]"
|
|
306
|
+
pytest
|
|
307
|
+
ruff check .
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
Docs: <https://lex-api.com/docs>
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
lexapi/__init__.py,sha256=u9WJpr8Ka9Avix1Rrq1x8BbhXfjJFAfp3cdbCsYEik8,3196
|
|
2
|
+
lexapi/_base.py,sha256=gwU-3XEQbMiT6DlpkSYH5EaLj_X7XgI7J37EVvXiPPI,3714
|
|
3
|
+
lexapi/_meta.py,sha256=y-r0WeSfIWx-5r3TrtBcImnypptEizkuK81yhFkngsw,384
|
|
4
|
+
lexapi/_payloads.py,sha256=R7vv-gs-PFiqYu92JEOqO-2g3_ntVIUlL8IuWkJY7Qg,4214
|
|
5
|
+
lexapi/_response.py,sha256=RRylePAlBwwpqdbh6f2Me2ouz2XN-8y8732hfmH8PqU,5840
|
|
6
|
+
lexapi/_retry.py,sha256=Y80-o34CZftThMVwrGglxDlYDITYi02rkAlNyO0cqPI,5251
|
|
7
|
+
lexapi/async_client.py,sha256=Au_xVrwXCsmZVOsAgoKNM5e8k7BMmPLs1V5SRB3W54I,15550
|
|
8
|
+
lexapi/citations.py,sha256=iDYGhmq_EcqhUj_kNhsBDleJDmCRHdKvxqy84-HAn8w,7742
|
|
9
|
+
lexapi/client.py,sha256=7zi0KHpcoTgrqCBjdQLXssMS3FwmJp1unEThN9PDhVc,19613
|
|
10
|
+
lexapi/errors.py,sha256=jImnOuZP6OR-utfm06ln9sUqbW6djUWiHreOkcYwz8g,8499
|
|
11
|
+
lexapi/export.py,sha256=P64ZQLyZkFUEb4y5bHmScb8kf974trKMh3Ya-ONmSEo,8479
|
|
12
|
+
lexapi/models.py,sha256=ar5imOWqs4k0FUdhOM93hFOzIwmYO1LN5SKVMvFTSaQ,38993
|
|
13
|
+
lexapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
14
|
+
lexapi/webhooks.py,sha256=6Em0csTadptnauoZqHIgYsZu0-Csi7fCPRJv_FyJz3c,7970
|
|
15
|
+
lexapi_client-0.1.0.dist-info/METADATA,sha256=qDumjmoqrwZEVwM2QoqGXJK8qs2ZfCz2SK8SU4XQmVs,10894
|
|
16
|
+
lexapi_client-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
17
|
+
lexapi_client-0.1.0.dist-info/RECORD,,
|