lexapi-client 0.1.0__tar.gz

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.
Files changed (32) hide show
  1. lexapi_client-0.1.0/.github/workflows/ci.yml +24 -0
  2. lexapi_client-0.1.0/.gitignore +14 -0
  3. lexapi_client-0.1.0/PKG-INFO +310 -0
  4. lexapi_client-0.1.0/PLAN.md +128 -0
  5. lexapi_client-0.1.0/README.md +288 -0
  6. lexapi_client-0.1.0/pyproject.toml +43 -0
  7. lexapi_client-0.1.0/src/lexapi/__init__.py +132 -0
  8. lexapi_client-0.1.0/src/lexapi/_base.py +122 -0
  9. lexapi_client-0.1.0/src/lexapi/_meta.py +14 -0
  10. lexapi_client-0.1.0/src/lexapi/_payloads.py +160 -0
  11. lexapi_client-0.1.0/src/lexapi/_response.py +158 -0
  12. lexapi_client-0.1.0/src/lexapi/_retry.py +148 -0
  13. lexapi_client-0.1.0/src/lexapi/async_client.py +417 -0
  14. lexapi_client-0.1.0/src/lexapi/citations.py +231 -0
  15. lexapi_client-0.1.0/src/lexapi/client.py +491 -0
  16. lexapi_client-0.1.0/src/lexapi/errors.py +261 -0
  17. lexapi_client-0.1.0/src/lexapi/export.py +253 -0
  18. lexapi_client-0.1.0/src/lexapi/models.py +1253 -0
  19. lexapi_client-0.1.0/src/lexapi/py.typed +0 -0
  20. lexapi_client-0.1.0/src/lexapi/webhooks.py +220 -0
  21. lexapi_client-0.1.0/tests/conftest.py +28 -0
  22. lexapi_client-0.1.0/tests/test_async_client.py +83 -0
  23. lexapi_client-0.1.0/tests/test_citations.py +304 -0
  24. lexapi_client-0.1.0/tests/test_client.py +149 -0
  25. lexapi_client-0.1.0/tests/test_documents_search.py +424 -0
  26. lexapi_client-0.1.0/tests/test_errors.py +131 -0
  27. lexapi_client-0.1.0/tests/test_export.py +210 -0
  28. lexapi_client-0.1.0/tests/test_point_in_time.py +149 -0
  29. lexapi_client-0.1.0/tests/test_response.py +90 -0
  30. lexapi_client-0.1.0/tests/test_retry.py +196 -0
  31. lexapi_client-0.1.0/tests/test_semantic.py +198 -0
  32. lexapi_client-0.1.0/tests/test_webhooks.py +250 -0
@@ -0,0 +1,24 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ lint-test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ matrix:
13
+ python-version: ["3.9", "3.12"]
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: actions/setup-python@v5
17
+ with:
18
+ python-version: ${{ matrix.python-version }}
19
+ - name: Install
20
+ run: pip install -e ".[dev]"
21
+ - name: Lint
22
+ run: ruff check .
23
+ - name: Test
24
+ run: pytest
@@ -0,0 +1,14 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .venv/
7
+ venv/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .coverage
11
+ htmlcov/
12
+ .mypy_cache/
13
+ .DS_Store
14
+ .env
@@ -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,128 @@
1
+ # lexapi-python — Implementation Plan
2
+
3
+ Official Python SDK for [LexAPI](https://lex-api.com) (`https://lex-api.com/api/v1`, docs at <https://lex-api.com/docs>). Package name: **`lexapi`** (PyPI). Source of truth: `openapi.yaml` in the LexAPI server repo.
4
+
5
+ ## 1. SDK Contract (shared across all LexAPI SDKs)
6
+
7
+ This section is identical in `lexapi-python`, `lexapi-typescript`, `lexapi-kotlin`, and `lexapi-swift`. Any change here must be propagated to all four repos in the same release cycle.
8
+
9
+ Source of truth: `openapi.yaml` (LexAPI 2.0.0, OpenAPI 3.1.0). Production base URL: `https://lex-api.com/api/v1`. Docs: <https://lex-api.com/docs>.
10
+
11
+ ### 1.1 Authentication
12
+
13
+ - Per the OpenAPI `securitySchemes.ApiKeyAuth`: `type: apiKey`, `in: header`, `name: x-api-key`.
14
+ - The SDK sends the key on **every** request as the `x-api-key` header. Keys are prefixed `lex_`.
15
+ - Keys are server-side secrets: SDKs must never log the key, never embed it in URLs, and README/quickstart must warn against shipping keys in client-side code (the API explicitly does not support public keys).
16
+ - Key is provided at client construction time (constructor arg) with an environment-variable fallback (`LEXAPI_API_KEY`).
17
+
18
+ ### 1.2 Retries and rate limiting
19
+
20
+ - Default retry policy: up to 3 retries with exponential backoff + full jitter (base 500 ms, cap 30 s).
21
+ - Retryable: HTTP 429 (`RATE_LIMITED`), 502 (`UPSTREAM_ERROR`), 504 (`TIMEOUT` — spec marks this retry-safe), and transport-level network errors. Non-retryable: all other 4xx (including 402 `CREDITS_EXHAUSTED` — retrying cannot help until top-up/reset) and 500 `INTERNAL` by default.
22
+ - Server-directed wait wins over computed backoff. Resolution order for the wait duration on 429:
23
+ 1. `Retry-After` response header (seconds; documented in the spec's `RateLimited` response),
24
+ 2. `RateLimit-*` headers (`RateLimit-Remaining`, `RateLimit-Reset` / draft IETF forms) when present,
25
+ 3. the JSON `retryAfter` field on the 429 error body, when present,
26
+ 4. computed exponential backoff as fallback.
27
+ - Retry behaviour is configurable (max attempts, disable entirely). Idempotent GETs retry by default; non-GET calls retry only on 429/network-error-before-send unless the caller opts in.
28
+
29
+ ### 1.3 Typed errors
30
+
31
+ - All non-2xx responses map to a typed exception/error hierarchy mirroring the API error envelope:
32
+
33
+ ```json
34
+ { "success": false, "error": { "code": "NOT_FOUND", "message": "...", "details": { } } }
35
+ ```
36
+
37
+ - `error.code` is a stable slug enum (from the spec): `NOT_FOUND`, `INVALID_CELEX`, `INVALID_URL`, `INVALID_PARAMS`, `RATE_LIMITED`, `TIER_FORBIDDEN`, `CREDITS_EXHAUSTED`, `UPSTREAM_ERROR`, `TIMEOUT`, `INTERNAL`. SDK error types carry `code`, `message`, optional `details`, and the HTTP status. Unknown codes must not crash the parser (forward compatibility: keep raw code string).
38
+ - **Legacy tolerance:** some legacy endpoints return a bare `{ "error": "..." }` body without the `success`/typed envelope. The error parser must accept both shapes: if `error` is an object, read `code`/`message`/`details`; if `error` is a string, use it as `message` and derive `code` from the HTTP status (404→`NOT_FOUND`, 429→`RATE_LIMITED`, 401→unauthorized, etc.).
39
+ - 401 (missing/invalid/revoked key) surfaces as a distinct authentication error type.
40
+
41
+ ### 1.4 Pagination helpers
42
+
43
+ - Search endpoints are page-based (`page`/`maxPages`, tier-bounded per the `subscription` block). SDKs provide an iterator/stream helper that walks pages transparently and stops at the tier cap, surfacing `truncated`/`truncatedAt`/`truncatedReason` and `partial`/`partialReason` flags rather than hiding them.
44
+ - `/webhooks/{id}/deliveries` and other list endpoints get the same helper where applicable.
45
+
46
+ ### 1.5 Credit visibility
47
+
48
+ - Every successful response can include a `usage` block (`current`/`limit`/`remaining`/`unit`/`resetsAt`; dual-mode credits-vs-daily-calls) and, on credit-pool (v2) accounts, a `credits` block (`operation_weight`, `current`, `limit`, `remaining`, `included`, `topup`, `resetsAt`).
49
+ - SDKs expose a credit-visibility helper on every response wrapper: `unitsCharged` (mapped from `credits.operation_weight`; 0 for free ops like `/info`), `creditsRemaining` (from `credits.remaining`, falling back to `usage.remaining`), and `resetsAt`. The raw `usage`/`credits` blocks stay accessible untyped-loss-free.
50
+ - Helpers must tolerate the blocks being absent (legacy daily-call accounts omit `credits`).
51
+
52
+ ### 1.6 Timeouts
53
+
54
+ - Defaults: 10 s connect, 60 s read/overall (the API's upstream hard timeout is 90 s; staying under it means the SDK sees the typed 504 rather than cutting the connection). Both configurable per-client and per-call.
55
+
56
+ ### 1.7 User agent
57
+
58
+ - Every request sends `User-Agent: lexapi-<lang>/<version>` (e.g. `lexapi-python/0.1.0`, `lexapi-typescript/0.1.0`, `lexapi-kotlin/0.1.0`, `lexapi-swift/0.1.0`), with an optional caller-supplied suffix.
59
+
60
+ ## 2. Endpoint coverage matrix
61
+
62
+ Priority order: **P0** first (`info` + `search` + `documentContent`), then P1 → P3. One group per release increment where practical.
63
+
64
+ | Status | Group | Operation | Method + Path | Priority |
65
+ | --- | --- | --- | --- | --- |
66
+ | [x] | user/info | `getInfo` | `GET /info` | **P0** |
67
+ | [x] | search | `search` | `POST /search` | **P0** |
68
+ | [x] | documents/content | `getDocumentContent` | `POST /documentContent` | **P0** |
69
+ | [x] | documents/content | `getDocumentContentBatch` | `POST /documentContent/batch` | P1 |
70
+ | [x] | documents/content | `getRecentDocuments` | `GET /documents/recent` | P1 |
71
+ | [x] | documents/content | `getDocumentByUrl` | `POST /documents/url` | P1 |
72
+ | [x] | documents/content | `getDocumentMetadata` | `POST /documents/metadata` | P1 |
73
+ | [x] | resolve | `resolveIdentifier` | `POST /resolve` | P1 |
74
+ | [x] | citations | `extractCitations` | `POST /citations/extract` | P2 |
75
+ | [x] | citations | `getCitedBy` | `GET /citations/cited-by/{celexNumber}` | P2 |
76
+ | [x] | citations | `getCites` | `GET /citations/cites/{celexNumber}` | P2 |
77
+ | [x] | citations | `getCitationNetwork` | `GET /citations/network/{celexNumber}` | P2 |
78
+ | [x] | citations | `getCitationStats` | `GET /citations/stats` | P2 |
79
+ | [x] | citations | `getCitationPath` | `GET /citations/path/{from}/{to}` | P2 |
80
+ | [x] | citations | `getRelatedDocuments` | `GET /citations/related/{celexNumber}` | P2 |
81
+ | [x] | semantic | `semanticCaseLawSearch` | `POST /search/semantic` | P2 |
82
+ | [x] | semantic | `semanticLegislationSearch` | `POST /legislation/semantic` | P2 |
83
+ | [x] | export | `exportCorpus` | `GET /export` | P3 |
84
+ | [x] | webhooks | `listWebhooks` / `createWebhook` | `GET/POST /webhooks` | P3 |
85
+ | [x] | webhooks | `getWebhook` / `updateWebhook` / `deleteWebhook` | `GET/PUT/DELETE /webhooks/{id}` | P3 |
86
+ | [x] | webhooks | `testWebhook` | `POST /webhooks/{id}/test` | P3 |
87
+ | [x] | webhooks | `getWebhookDeliveries` | `GET /webhooks/{id}/deliveries` | P3 |
88
+ | [x] | versions | `listDocumentVersions` | `GET /documents/{celex}/versions` | P3 |
89
+ | [x] | versions | `getDocumentVersion` | `GET /documents/{celex}/versions/{version}` | P3 |
90
+ | [x] | versions | `getDocumentAtDate` | `GET /documents/{celex}/at/{date}` | P3 |
91
+
92
+ Cross-cutting model work per group: `ErrorResponse`, `SubscriptionInfo`, `UsageInfo`, `CreditsInfo` (P0); search filter enums driven from `/info` capability map where possible instead of hardcoding.
93
+ ## 3. Language-specific architecture
94
+
95
+ - **Layout:** `src/lexapi/` (src layout), built with **hatchling** via `pyproject.toml`.
96
+ - **HTTP:** `httpx` — one shared `httpx.Client` per `LexAPI` instance; an `AsyncLexAPI` twin sharing all request-building/parsing code lands with P0 (`httpx` makes sync/async symmetric).
97
+ - **Modules:**
98
+ - `lexapi/client.py` — `LexAPI` client, `_request()` core (auth header, UA, retries, timeout), one method per operation grouped by resource namespaces (`client.search(...)`, `client.documents.content(...)`, `client.citations.cited_by(...)`, `client.webhooks.list(...)`).
99
+ - `lexapi/errors.py` — `LexAPIError` base carrying `code/message/details/status`; subclasses per stable code (`NotFoundError`, `RateLimitedError` with `retry_after`, `CreditsExhaustedError`, ...). Tolerates typed envelope and legacy bare `{error}`.
100
+ - `lexapi/models.py` — typed dataclasses/`TypedDict`s for `SubscriptionInfo`, `UsageInfo`, `CreditsInfo`, search hits, `DocumentContent`; generated-then-curated from the OpenAPI schema (no runtime codegen dependency).
101
+ - `lexapi/pagination.py` — `iter_pages()` / `iter_results()` generators honoring tier caps and surfacing `truncated`/`partial`.
102
+ - `lexapi/_meta.py` — version + user-agent string (`lexapi-python/<version>`).
103
+ - **Responses:** thin `APIResponse` wrapper exposing `.data`, `.usage`, `.credits`, `.units_charged`, `.credits_remaining`, `.resets_at`.
104
+ - **Typing:** fully typed, `py.typed` marker, mypy strict in CI. Python ≥ 3.9.
105
+ - **Lint/format:** ruff (lint + format), configured in `pyproject.toml`.
106
+
107
+ ## 4. Testing strategy
108
+
109
+ - **Unit tests (pytest):** request construction (auth header, UA, timeouts), error-envelope parsing (typed + legacy bare-`{error}` shapes, unknown codes), retry/backoff decisions (`Retry-After`, `RateLimit-*`, JSON `retryAfter` precedence), pagination iteration incl. truncation flags, credit helpers with and without the `credits` block.
110
+ - **Mocked HTTP:** `httpx.MockTransport` for hermetic tests (no live sockets, no test-only HTTP server). Recorded fixtures: real (sanitized) response bodies checked into `tests/fixtures/*.json`, replayed through the mock transport; a `respx`-based layer if matching needs grow.
111
+ - **Contract tests:** validate fixture bodies against `openapi.yaml` schemas in CI (schemathesis or openapi-core) so drift is caught when the spec changes.
112
+ - **Smoke (manual/nightly, not PR-blocking):** `GET /info` against production with a scoped key from CI secrets.
113
+ - Coverage gate: 90% on `client.py`/`errors.py`/`pagination.py`.
114
+
115
+ ## 5. Publishing pipeline (PyPI) — plan only, nothing published yet
116
+
117
+ 1. Reserve the `lexapi` name on PyPI (manual first upload of 0.1.0 once ready — **not now**).
118
+ 2. GitHub Actions release workflow on tag `v*`: build sdist+wheel with `hatch build`, publish via **PyPI Trusted Publishing (OIDC)** — no long-lived tokens.
119
+ 3. TestPyPI dry-run job on `main` merges.
120
+ 4. CHANGELOG.md (keep-a-changelog), tag = version, GitHub Release generated from changelog section.
121
+ 5. Post-publish verification job: `pip install lexapi-client==<v>` in a clean venv + import smoke test.
122
+
123
+ ## 6. Versioning policy
124
+
125
+ - **Semver.** `0.x` until the LexAPI v1 surface freeze; during 0.x, minor bumps may break (documented in CHANGELOG), patch bumps never break.
126
+ - `1.0.0` is tagged only when: P0+P1 endpoint groups are covered, the shared SDK contract (section 1) is fully implemented, and the API team declares the v1 freeze.
127
+ - API additions (new fields/endpoints) → minor. Error-envelope or auth changes → coordinated minor across all four SDKs in the same week.
128
+ - Each release records the `openapi.yaml` revision it was generated/validated against.