kederi 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.
- kederi-0.1.0/LICENSE +21 -0
- kederi-0.1.0/PKG-INFO +66 -0
- kederi-0.1.0/README.md +55 -0
- kederi-0.1.0/kederi/__init__.py +7 -0
- kederi-0.1.0/kederi/client.py +245 -0
- kederi-0.1.0/kederi/errors.py +44 -0
- kederi-0.1.0/kederi.egg-info/PKG-INFO +66 -0
- kederi-0.1.0/kederi.egg-info/SOURCES.txt +11 -0
- kederi-0.1.0/kederi.egg-info/dependency_links.txt +1 -0
- kederi-0.1.0/kederi.egg-info/top_level.txt +1 -0
- kederi-0.1.0/pyproject.toml +21 -0
- kederi-0.1.0/setup.cfg +4 -0
- kederi-0.1.0/tests/test_client.py +122 -0
kederi-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tolu Aina.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
kederi-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kederi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Client for the Kederi transaction enrichment API
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Documentation, https://kederi.com/docs
|
|
7
|
+
Requires-Python: >=3.8
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Dynamic: license-file
|
|
11
|
+
|
|
12
|
+
# kederi (Python)
|
|
13
|
+
|
|
14
|
+
A client for the [Kederi API](https://kederi.com/docs). It uses the Python
|
|
15
|
+
standard library only.
|
|
16
|
+
|
|
17
|
+
MIT licensed (see `LICENSE`). Not on PyPI yet: install it from this folder.
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
pip install ./sdk/python
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Use
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from kederi import Kederi, KederiError
|
|
27
|
+
|
|
28
|
+
k = Kederi() # reads KEDERI_API_KEY
|
|
29
|
+
|
|
30
|
+
r = k.enrich("NIP/GTB/ADEBAYO CHUKWU/rent for august", direction="debit")
|
|
31
|
+
print(r["enrichment"]["name"], r["enrichment"]["intent"])
|
|
32
|
+
|
|
33
|
+
# a batch, with your own categories
|
|
34
|
+
results = k.enrich_batch(
|
|
35
|
+
[{"descriptor": "SQ *BLUE BOTTLE 8005551234 CA"}, {"descriptor": "NETFLIX.COM"}],
|
|
36
|
+
category_map={"Coffee": "Eating out", "*": "Other"},
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
# any number of rows, in calls of 1000
|
|
40
|
+
for result in k.enrich_all(rows):
|
|
41
|
+
...
|
|
42
|
+
|
|
43
|
+
# every report over rows you send; nothing is stored
|
|
44
|
+
reports = k.reports(rows, reports=["subscriptions", "counterparties"], account_holder="Ada Obi")
|
|
45
|
+
|
|
46
|
+
# the stable id of a merchant
|
|
47
|
+
m = k.merchant(results[0]["enrichment"]["merchant_id"])
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Errors and retries
|
|
51
|
+
|
|
52
|
+
A failure raises `KederiError` with `status`, `code`, `message` and
|
|
53
|
+
`details`. Branch on `code`. The client tries a 429 or a 5xx answer again,
|
|
54
|
+
twice by default (`max_retries`), and waits for the `Retry-After` the API
|
|
55
|
+
sends. `client.last_rate_limit` holds the budget headers from the last answer.
|
|
56
|
+
|
|
57
|
+
## What it does not cover
|
|
58
|
+
|
|
59
|
+
Signing in and managing keys. An API key cannot manage API keys, so those
|
|
60
|
+
calls need a console session. Use the console at https://kederi.com/console.
|
|
61
|
+
|
|
62
|
+
## Test
|
|
63
|
+
|
|
64
|
+
```sh
|
|
65
|
+
python3 -m unittest discover -s sdk/python/tests
|
|
66
|
+
```
|
kederi-0.1.0/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# kederi (Python)
|
|
2
|
+
|
|
3
|
+
A client for the [Kederi API](https://kederi.com/docs). It uses the Python
|
|
4
|
+
standard library only.
|
|
5
|
+
|
|
6
|
+
MIT licensed (see `LICENSE`). Not on PyPI yet: install it from this folder.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
pip install ./sdk/python
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Use
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from kederi import Kederi, KederiError
|
|
16
|
+
|
|
17
|
+
k = Kederi() # reads KEDERI_API_KEY
|
|
18
|
+
|
|
19
|
+
r = k.enrich("NIP/GTB/ADEBAYO CHUKWU/rent for august", direction="debit")
|
|
20
|
+
print(r["enrichment"]["name"], r["enrichment"]["intent"])
|
|
21
|
+
|
|
22
|
+
# a batch, with your own categories
|
|
23
|
+
results = k.enrich_batch(
|
|
24
|
+
[{"descriptor": "SQ *BLUE BOTTLE 8005551234 CA"}, {"descriptor": "NETFLIX.COM"}],
|
|
25
|
+
category_map={"Coffee": "Eating out", "*": "Other"},
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
# any number of rows, in calls of 1000
|
|
29
|
+
for result in k.enrich_all(rows):
|
|
30
|
+
...
|
|
31
|
+
|
|
32
|
+
# every report over rows you send; nothing is stored
|
|
33
|
+
reports = k.reports(rows, reports=["subscriptions", "counterparties"], account_holder="Ada Obi")
|
|
34
|
+
|
|
35
|
+
# the stable id of a merchant
|
|
36
|
+
m = k.merchant(results[0]["enrichment"]["merchant_id"])
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Errors and retries
|
|
40
|
+
|
|
41
|
+
A failure raises `KederiError` with `status`, `code`, `message` and
|
|
42
|
+
`details`. Branch on `code`. The client tries a 429 or a 5xx answer again,
|
|
43
|
+
twice by default (`max_retries`), and waits for the `Retry-After` the API
|
|
44
|
+
sends. `client.last_rate_limit` holds the budget headers from the last answer.
|
|
45
|
+
|
|
46
|
+
## What it does not cover
|
|
47
|
+
|
|
48
|
+
Signing in and managing keys. An API key cannot manage API keys, so those
|
|
49
|
+
calls need a console session. Use the console at https://kederi.com/console.
|
|
50
|
+
|
|
51
|
+
## Test
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
python3 -m unittest discover -s sdk/python/tests
|
|
55
|
+
```
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""The Kederi API client. Standard library only, so it adds no dependency.
|
|
2
|
+
|
|
3
|
+
Each method is one call to the API, and the method docstring names it. The
|
|
4
|
+
client stores nothing: like the API, it sends a request and returns the
|
|
5
|
+
answer.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import random
|
|
13
|
+
import time
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.parse
|
|
16
|
+
import urllib.request
|
|
17
|
+
from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence
|
|
18
|
+
|
|
19
|
+
from .errors import KederiError
|
|
20
|
+
|
|
21
|
+
__all__ = ["Kederi", "DEFAULT_BASE_URL", "MAX_BATCH"]
|
|
22
|
+
|
|
23
|
+
DEFAULT_BASE_URL = "https://kederi.com/v1"
|
|
24
|
+
# The API refuses a batch of more than this. enrich_all() splits for you.
|
|
25
|
+
MAX_BATCH = 1000
|
|
26
|
+
# Statuses worth a second try. 429 is a rate limit; the rest are transient.
|
|
27
|
+
_RETRY_STATUSES = {429, 500, 502, 503, 504}
|
|
28
|
+
|
|
29
|
+
Json = Dict[str, Any]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Kederi:
|
|
33
|
+
"""A client for the Kederi API.
|
|
34
|
+
|
|
35
|
+
``api_key`` defaults to the ``KEDERI_API_KEY`` environment variable.
|
|
36
|
+
A rate-limited or transient failure is tried again up to ``max_retries``
|
|
37
|
+
times. A 429 waits for the ``Retry-After`` the API sends.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
api_key: Optional[str] = None,
|
|
43
|
+
*,
|
|
44
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
45
|
+
timeout: float = 30.0,
|
|
46
|
+
max_retries: int = 2,
|
|
47
|
+
) -> None:
|
|
48
|
+
self.api_key = api_key if api_key is not None else os.environ.get("KEDERI_API_KEY")
|
|
49
|
+
self.base_url = base_url.rstrip("/")
|
|
50
|
+
self.timeout = timeout
|
|
51
|
+
self.max_retries = max_retries
|
|
52
|
+
# The budget headers from the last answer (RateLimit-Remaining and
|
|
53
|
+
# the others), so a caller can slow down before a 429.
|
|
54
|
+
self.last_rate_limit: Dict[str, str] = {}
|
|
55
|
+
|
|
56
|
+
# ---- enrichment ----
|
|
57
|
+
|
|
58
|
+
def enrich(
|
|
59
|
+
self,
|
|
60
|
+
descriptor: str,
|
|
61
|
+
*,
|
|
62
|
+
direction: Optional[str] = None,
|
|
63
|
+
amount: Optional[float] = None,
|
|
64
|
+
date: Optional[str] = None,
|
|
65
|
+
account_id: Optional[str] = None,
|
|
66
|
+
category_map: Optional[Mapping[str, str]] = None,
|
|
67
|
+
) -> Json:
|
|
68
|
+
"""``POST /enrich``, single form. Returns ``{"input", "enrichment"}``."""
|
|
69
|
+
body: Json = {"descriptor": descriptor}
|
|
70
|
+
for key, value in (("direction", direction), ("amount", amount), ("date", date), ("account_id", account_id)):
|
|
71
|
+
if value is not None:
|
|
72
|
+
body[key] = value
|
|
73
|
+
if category_map is not None:
|
|
74
|
+
body["category_map"] = dict(category_map)
|
|
75
|
+
return self._request("POST", "/enrich", body)
|
|
76
|
+
|
|
77
|
+
def enrich_batch(
|
|
78
|
+
self,
|
|
79
|
+
transactions: Sequence[Mapping[str, Any]],
|
|
80
|
+
*,
|
|
81
|
+
category_map: Optional[Mapping[str, str]] = None,
|
|
82
|
+
) -> List[Json]:
|
|
83
|
+
"""``POST /enrich``, batch form, at most 1000 rows. Returns the ``results`` list.
|
|
84
|
+
|
|
85
|
+
Recurrence is found ACROSS the batch, so send a series in one call.
|
|
86
|
+
"""
|
|
87
|
+
if len(transactions) > MAX_BATCH:
|
|
88
|
+
raise ValueError(f"at most {MAX_BATCH} transactions in one call; use enrich_all() to split")
|
|
89
|
+
body: Json = {"transactions": [dict(t) for t in transactions]}
|
|
90
|
+
if category_map is not None:
|
|
91
|
+
body["category_map"] = dict(category_map)
|
|
92
|
+
return self._request("POST", "/enrich", body)["results"]
|
|
93
|
+
|
|
94
|
+
def enrich_all(
|
|
95
|
+
self,
|
|
96
|
+
transactions: Iterable[Mapping[str, Any]],
|
|
97
|
+
*,
|
|
98
|
+
category_map: Optional[Mapping[str, str]] = None,
|
|
99
|
+
) -> Iterator[Json]:
|
|
100
|
+
"""``POST /enrich`` in batches of 1000, yielding each result in order.
|
|
101
|
+
|
|
102
|
+
A series that crosses a batch boundary is not detected as recurring.
|
|
103
|
+
For recurrence over a whole history, use ``reports()``.
|
|
104
|
+
"""
|
|
105
|
+
chunk: List[Mapping[str, Any]] = []
|
|
106
|
+
for t in transactions:
|
|
107
|
+
chunk.append(t)
|
|
108
|
+
if len(chunk) == MAX_BATCH:
|
|
109
|
+
yield from self.enrich_batch(chunk, category_map=category_map)
|
|
110
|
+
chunk = []
|
|
111
|
+
if chunk:
|
|
112
|
+
yield from self.enrich_batch(chunk, category_map=category_map)
|
|
113
|
+
|
|
114
|
+
def statements(self, content: str, **fields: Any) -> Json:
|
|
115
|
+
"""``POST /statements``: a statement file (CSV, OFX, QIF, JSON, or a PDF as base64).
|
|
116
|
+
|
|
117
|
+
Extra fields (``filename``, ``date_order``, ``mapping``, ``payload``,
|
|
118
|
+
``profile``) go into the body as the API documents them.
|
|
119
|
+
"""
|
|
120
|
+
return self._request("POST", "/statements", {"content": content, **fields})
|
|
121
|
+
|
|
122
|
+
def reports(
|
|
123
|
+
self,
|
|
124
|
+
transactions: Sequence[Mapping[str, Any]],
|
|
125
|
+
*,
|
|
126
|
+
reports: Optional[Sequence[str]] = None,
|
|
127
|
+
account_holder: Optional[str] = None,
|
|
128
|
+
**fields: Any,
|
|
129
|
+
) -> Json:
|
|
130
|
+
"""``POST /reports``: every analytic over the rows you send. Nothing is stored.
|
|
131
|
+
|
|
132
|
+
Each row needs ``amount`` and ``date``. Extra fields (``as_of``,
|
|
133
|
+
``days``, ``balance``, ``category``, ``name``, ``q``) go into the body.
|
|
134
|
+
"""
|
|
135
|
+
body: Json = {"transactions": [dict(t) for t in transactions], **fields}
|
|
136
|
+
if reports is not None:
|
|
137
|
+
body["reports"] = list(reports)
|
|
138
|
+
if account_holder is not None:
|
|
139
|
+
body["account_holder"] = account_holder
|
|
140
|
+
return self._request("POST", "/reports", body)
|
|
141
|
+
|
|
142
|
+
# ---- the directory ----
|
|
143
|
+
|
|
144
|
+
def merchant(self, merchant_id: str) -> Json:
|
|
145
|
+
"""``GET /merchants/{id}``: the record for a ``merchant_id``."""
|
|
146
|
+
return self._request("GET", "/merchants/" + urllib.parse.quote(merchant_id, safe=""))
|
|
147
|
+
|
|
148
|
+
def taxonomy(self) -> Json:
|
|
149
|
+
"""``GET /taxonomy``: the category names and intent labels, with a version."""
|
|
150
|
+
return self._request("GET", "/taxonomy")
|
|
151
|
+
|
|
152
|
+
def coverage(self) -> Json:
|
|
153
|
+
"""``GET /coverage``: the countries and how many merchants each has."""
|
|
154
|
+
return self._request("GET", "/coverage")
|
|
155
|
+
|
|
156
|
+
# ---- corrections ----
|
|
157
|
+
|
|
158
|
+
def report_wrong(
|
|
159
|
+
self,
|
|
160
|
+
descriptor: str,
|
|
161
|
+
*,
|
|
162
|
+
name: Optional[str] = None,
|
|
163
|
+
category: Optional[str] = None,
|
|
164
|
+
intent: Optional[str] = None,
|
|
165
|
+
type: Optional[str] = None,
|
|
166
|
+
note: Optional[str] = None,
|
|
167
|
+
) -> Json:
|
|
168
|
+
"""``POST /feedback``: say what the right answer was. The narration is KEPT."""
|
|
169
|
+
expected = {k: v for k, v in (("name", name), ("category", category), ("intent", intent), ("type", type)) if v is not None}
|
|
170
|
+
body: Json = {"descriptor": descriptor}
|
|
171
|
+
if expected:
|
|
172
|
+
body["expected"] = expected
|
|
173
|
+
if note is not None:
|
|
174
|
+
body["note"] = note
|
|
175
|
+
return self._request("POST", "/feedback", body)
|
|
176
|
+
|
|
177
|
+
def feedback(self, status: Optional[str] = None) -> Json:
|
|
178
|
+
"""``GET /feedback``: what became of the corrections you sent."""
|
|
179
|
+
return self._request("GET", "/feedback", query={"status": status})
|
|
180
|
+
|
|
181
|
+
# ---- the account ----
|
|
182
|
+
|
|
183
|
+
def me(self) -> Json:
|
|
184
|
+
"""``GET /auth/me``: which account and key this client is."""
|
|
185
|
+
return self._request("GET", "/auth/me")
|
|
186
|
+
|
|
187
|
+
def usage(self, *, days: Optional[int] = None, from_: Optional[str] = None, to: Optional[str] = None) -> Json:
|
|
188
|
+
"""``GET /usage``: billable enrichments. ``from_`` is the API's ``from``."""
|
|
189
|
+
return self._request("GET", "/usage", query={"days": days, "from": from_, "to": to})
|
|
190
|
+
|
|
191
|
+
# ---- transport ----
|
|
192
|
+
|
|
193
|
+
def _request(self, method: str, path: str, body: Optional[Json] = None, query: Optional[Mapping[str, Any]] = None) -> Json:
|
|
194
|
+
url = self.base_url + path
|
|
195
|
+
if query:
|
|
196
|
+
q = {k: v for k, v in query.items() if v is not None}
|
|
197
|
+
if q:
|
|
198
|
+
url += "?" + urllib.parse.urlencode(q)
|
|
199
|
+
data = json.dumps(body).encode("utf-8") if body is not None else None
|
|
200
|
+
headers = {"accept": "application/json", "user-agent": "kederi-python/0.1.0"}
|
|
201
|
+
if data is not None:
|
|
202
|
+
headers["content-type"] = "application/json"
|
|
203
|
+
if self.api_key:
|
|
204
|
+
headers["authorization"] = "Bearer " + self.api_key
|
|
205
|
+
|
|
206
|
+
attempt = 0
|
|
207
|
+
while True:
|
|
208
|
+
req = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
209
|
+
try:
|
|
210
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as res:
|
|
211
|
+
self._note_budget(res.headers)
|
|
212
|
+
return json.loads(res.read().decode("utf-8") or "null")
|
|
213
|
+
except urllib.error.HTTPError as e:
|
|
214
|
+
self._note_budget(e.headers)
|
|
215
|
+
raw = e.read().decode("utf-8", "replace")
|
|
216
|
+
if e.code in _RETRY_STATUSES and attempt < self.max_retries:
|
|
217
|
+
time.sleep(self._wait(e.headers, attempt))
|
|
218
|
+
attempt += 1
|
|
219
|
+
continue
|
|
220
|
+
raise KederiError.from_response(e.code, raw, e.headers) from None
|
|
221
|
+
except urllib.error.URLError as e:
|
|
222
|
+
if attempt < self.max_retries:
|
|
223
|
+
time.sleep(self._wait(None, attempt))
|
|
224
|
+
attempt += 1
|
|
225
|
+
continue
|
|
226
|
+
raise KederiError(0, "network_error", str(e.reason)) from None
|
|
227
|
+
|
|
228
|
+
def _note_budget(self, headers: Any) -> None:
|
|
229
|
+
if headers is None:
|
|
230
|
+
return
|
|
231
|
+
self.last_rate_limit = {
|
|
232
|
+
k: v for k, v in headers.items() if k.lower().startswith("ratelimit-") or k.lower() == "retry-after"
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
@staticmethod
|
|
236
|
+
def _wait(headers: Any, attempt: int) -> float:
|
|
237
|
+
# The API says how long, on a 429. Otherwise back off with jitter.
|
|
238
|
+
if headers is not None:
|
|
239
|
+
ra = headers.get("Retry-After")
|
|
240
|
+
if ra:
|
|
241
|
+
try:
|
|
242
|
+
return min(float(ra), 60.0)
|
|
243
|
+
except ValueError:
|
|
244
|
+
pass
|
|
245
|
+
return min(0.5 * (2 ** attempt) + random.random() * 0.25, 8.0)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""The one error type. The API answers an error as
|
|
2
|
+
``{"error": {"code", "message", "details"?}}``, and this carries those fields.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
from typing import Any, Optional
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class KederiError(Exception):
|
|
12
|
+
"""An answer that was not a success.
|
|
13
|
+
|
|
14
|
+
``status`` is the HTTP status (0 when the server was not reached).
|
|
15
|
+
``code`` is the API's error code, for example ``invalid_request``,
|
|
16
|
+
``rate_limited`` or ``quota_exceeded``. Branch on ``code``, not on the
|
|
17
|
+
message, which is written for a person.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, status: int, code: str, message: str, details: Any = None, retry_after: Optional[float] = None) -> None:
|
|
21
|
+
super().__init__(f"{status} {code}: {message}")
|
|
22
|
+
self.status = status
|
|
23
|
+
self.code = code
|
|
24
|
+
self.message = message
|
|
25
|
+
self.details = details
|
|
26
|
+
self.retry_after = retry_after
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def from_response(cls, status: int, raw: str, headers: Any = None) -> "KederiError":
|
|
30
|
+
code, message, details = "http_error", raw[:500] or f"HTTP {status}", None
|
|
31
|
+
try:
|
|
32
|
+
err = json.loads(raw).get("error") or {}
|
|
33
|
+
code = err.get("code", code)
|
|
34
|
+
message = err.get("message", message)
|
|
35
|
+
details = err.get("details")
|
|
36
|
+
except (ValueError, AttributeError):
|
|
37
|
+
pass
|
|
38
|
+
retry_after = None
|
|
39
|
+
if headers is not None and headers.get("Retry-After"):
|
|
40
|
+
try:
|
|
41
|
+
retry_after = float(headers.get("Retry-After"))
|
|
42
|
+
except ValueError:
|
|
43
|
+
pass
|
|
44
|
+
return cls(status, code, message, details, retry_after)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kederi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Client for the Kederi transaction enrichment API
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Documentation, https://kederi.com/docs
|
|
7
|
+
Requires-Python: >=3.8
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Dynamic: license-file
|
|
11
|
+
|
|
12
|
+
# kederi (Python)
|
|
13
|
+
|
|
14
|
+
A client for the [Kederi API](https://kederi.com/docs). It uses the Python
|
|
15
|
+
standard library only.
|
|
16
|
+
|
|
17
|
+
MIT licensed (see `LICENSE`). Not on PyPI yet: install it from this folder.
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
pip install ./sdk/python
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Use
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from kederi import Kederi, KederiError
|
|
27
|
+
|
|
28
|
+
k = Kederi() # reads KEDERI_API_KEY
|
|
29
|
+
|
|
30
|
+
r = k.enrich("NIP/GTB/ADEBAYO CHUKWU/rent for august", direction="debit")
|
|
31
|
+
print(r["enrichment"]["name"], r["enrichment"]["intent"])
|
|
32
|
+
|
|
33
|
+
# a batch, with your own categories
|
|
34
|
+
results = k.enrich_batch(
|
|
35
|
+
[{"descriptor": "SQ *BLUE BOTTLE 8005551234 CA"}, {"descriptor": "NETFLIX.COM"}],
|
|
36
|
+
category_map={"Coffee": "Eating out", "*": "Other"},
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
# any number of rows, in calls of 1000
|
|
40
|
+
for result in k.enrich_all(rows):
|
|
41
|
+
...
|
|
42
|
+
|
|
43
|
+
# every report over rows you send; nothing is stored
|
|
44
|
+
reports = k.reports(rows, reports=["subscriptions", "counterparties"], account_holder="Ada Obi")
|
|
45
|
+
|
|
46
|
+
# the stable id of a merchant
|
|
47
|
+
m = k.merchant(results[0]["enrichment"]["merchant_id"])
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Errors and retries
|
|
51
|
+
|
|
52
|
+
A failure raises `KederiError` with `status`, `code`, `message` and
|
|
53
|
+
`details`. Branch on `code`. The client tries a 429 or a 5xx answer again,
|
|
54
|
+
twice by default (`max_retries`), and waits for the `Retry-After` the API
|
|
55
|
+
sends. `client.last_rate_limit` holds the budget headers from the last answer.
|
|
56
|
+
|
|
57
|
+
## What it does not cover
|
|
58
|
+
|
|
59
|
+
Signing in and managing keys. An API key cannot manage API keys, so those
|
|
60
|
+
calls need a console session. Use the console at https://kederi.com/console.
|
|
61
|
+
|
|
62
|
+
## Test
|
|
63
|
+
|
|
64
|
+
```sh
|
|
65
|
+
python3 -m unittest discover -s sdk/python/tests
|
|
66
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
kederi
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "kederi"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Client for the Kederi transaction enrichment API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
dependencies = []
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
|
|
15
|
+
# Name the package, so setuptools does not discover one. Only `kederi/`
|
|
16
|
+
# goes into the wheel.
|
|
17
|
+
[tool.setuptools]
|
|
18
|
+
packages = ["kederi"]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Documentation = "https://kederi.com/docs"
|
kederi-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Tests against a local fake server. No network and no real key."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
import threading
|
|
6
|
+
import unittest
|
|
7
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
11
|
+
from kederi import Kederi, KederiError # noqa: E402
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Fake(BaseHTTPRequestHandler):
|
|
15
|
+
# a queue of (status, body, headers) answers, and every request seen
|
|
16
|
+
answers = []
|
|
17
|
+
seen = []
|
|
18
|
+
|
|
19
|
+
def _answer(self):
|
|
20
|
+
length = int(self.headers.get("content-length") or 0)
|
|
21
|
+
body = json.loads(self.rfile.read(length)) if length else None
|
|
22
|
+
Fake.seen.append({"method": self.command, "path": self.path, "body": body,
|
|
23
|
+
"auth": self.headers.get("authorization")})
|
|
24
|
+
status, payload, headers = Fake.answers.pop(0) if Fake.answers else (200, {}, {})
|
|
25
|
+
raw = json.dumps(payload).encode()
|
|
26
|
+
self.send_response(status)
|
|
27
|
+
self.send_header("content-type", "application/json")
|
|
28
|
+
for k, v in headers.items():
|
|
29
|
+
self.send_header(k, v)
|
|
30
|
+
self.send_header("content-length", str(len(raw)))
|
|
31
|
+
self.end_headers()
|
|
32
|
+
self.wfile.write(raw)
|
|
33
|
+
|
|
34
|
+
do_GET = _answer
|
|
35
|
+
do_POST = _answer
|
|
36
|
+
|
|
37
|
+
def log_message(self, *args):
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ClientTest(unittest.TestCase):
|
|
42
|
+
@classmethod
|
|
43
|
+
def setUpClass(cls):
|
|
44
|
+
cls.server = HTTPServer(("127.0.0.1", 0), Fake)
|
|
45
|
+
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
|
|
46
|
+
cls.base = f"http://127.0.0.1:{cls.server.server_port}/v1"
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def tearDownClass(cls):
|
|
50
|
+
cls.server.shutdown()
|
|
51
|
+
|
|
52
|
+
def setUp(self):
|
|
53
|
+
Fake.answers, Fake.seen = [], []
|
|
54
|
+
self.k = Kederi("kdr_test", base_url=self.base, max_retries=2)
|
|
55
|
+
|
|
56
|
+
def test_single_enrich_sends_the_key_and_only_the_fields_given(self):
|
|
57
|
+
Fake.answers = [(200, {"enrichment": {"name": "Adebayo Chukwu"}}, {"RateLimit-Remaining": "59"})]
|
|
58
|
+
r = self.k.enrich("NIP/GTB/ADEBAYO CHUKWU/rent", direction="debit")
|
|
59
|
+
self.assertEqual(r["enrichment"]["name"], "Adebayo Chukwu")
|
|
60
|
+
self.assertEqual(Fake.seen[0]["path"], "/v1/enrich")
|
|
61
|
+
self.assertEqual(Fake.seen[0]["body"], {"descriptor": "NIP/GTB/ADEBAYO CHUKWU/rent", "direction": "debit"})
|
|
62
|
+
self.assertEqual(Fake.seen[0]["auth"], "Bearer kdr_test")
|
|
63
|
+
self.assertEqual(self.k.last_rate_limit.get("RateLimit-Remaining"), "59")
|
|
64
|
+
|
|
65
|
+
def test_enrich_all_splits_into_calls_of_1000_in_order(self):
|
|
66
|
+
rows = [{"descriptor": f"ROW {i}"} for i in range(2500)]
|
|
67
|
+
Fake.answers = [(200, {"results": [{"i": i} for i in range(n)]}, {}) for n in (1000, 1000, 500)]
|
|
68
|
+
out = list(self.k.enrich_all(rows, category_map={"*": "Other"}))
|
|
69
|
+
self.assertEqual(len(out), 2500)
|
|
70
|
+
self.assertEqual([len(s["body"]["transactions"]) for s in Fake.seen], [1000, 1000, 500])
|
|
71
|
+
self.assertEqual(Fake.seen[2]["body"]["transactions"][0], {"descriptor": "ROW 2000"})
|
|
72
|
+
self.assertEqual(Fake.seen[0]["body"]["category_map"], {"*": "Other"})
|
|
73
|
+
|
|
74
|
+
def test_a_batch_over_1000_is_refused_before_any_call(self):
|
|
75
|
+
with self.assertRaises(ValueError):
|
|
76
|
+
self.k.enrich_batch([{"descriptor": "X"}] * 1001)
|
|
77
|
+
self.assertEqual(Fake.seen, [])
|
|
78
|
+
|
|
79
|
+
def test_a_429_waits_for_retry_after_and_tries_again(self):
|
|
80
|
+
Fake.answers = [(429, {"error": {"code": "rate_limited", "message": "slow down"}}, {"Retry-After": "0"}),
|
|
81
|
+
(200, {"version": "1.0.0"}, {})]
|
|
82
|
+
self.assertEqual(self.k.taxonomy()["version"], "1.0.0")
|
|
83
|
+
self.assertEqual(len(Fake.seen), 2)
|
|
84
|
+
|
|
85
|
+
def test_an_error_carries_the_api_code_and_is_not_retried_when_it_is_a_400(self):
|
|
86
|
+
Fake.answers = [(400, {"error": {"code": "invalid_request", "message": "descriptor is required", "details": {"index": 3}}}, {})]
|
|
87
|
+
with self.assertRaises(KederiError) as cm:
|
|
88
|
+
self.k.enrich("")
|
|
89
|
+
self.assertEqual((cm.exception.status, cm.exception.code), (400, "invalid_request"))
|
|
90
|
+
self.assertEqual(cm.exception.details, {"index": 3})
|
|
91
|
+
self.assertEqual(len(Fake.seen), 1)
|
|
92
|
+
|
|
93
|
+
def test_retries_stop_at_the_limit(self):
|
|
94
|
+
Fake.answers = [(503, {"error": {"code": "store_unavailable", "message": "x"}}, {"Retry-After": "0"})] * 3
|
|
95
|
+
with self.assertRaises(KederiError) as cm:
|
|
96
|
+
self.k.coverage()
|
|
97
|
+
self.assertEqual(cm.exception.code, "store_unavailable")
|
|
98
|
+
self.assertEqual(len(Fake.seen), 3)
|
|
99
|
+
|
|
100
|
+
def test_query_parameters_skip_none_and_rename_from(self):
|
|
101
|
+
Fake.answers = [(200, {}, {}), (200, {}, {})]
|
|
102
|
+
self.k.usage(from_="2026-08-01", to="2026-08-31")
|
|
103
|
+
self.k.feedback()
|
|
104
|
+
self.assertEqual(Fake.seen[0]["path"], "/v1/usage?from=2026-08-01&to=2026-08-31")
|
|
105
|
+
self.assertEqual(Fake.seen[1]["path"], "/v1/feedback")
|
|
106
|
+
|
|
107
|
+
def test_reports_and_feedback_bodies(self):
|
|
108
|
+
Fake.answers = [(200, {}, {}), (200, {}, {})]
|
|
109
|
+
self.k.reports([{"descriptor": "X", "amount": 1, "date": "2026-01-01"}], reports=["counterparties"], account_holder="Ada Obi")
|
|
110
|
+
self.k.report_wrong("NETFLX", name="Netflix", note="typo")
|
|
111
|
+
self.assertEqual(Fake.seen[0]["body"]["account_holder"], "Ada Obi")
|
|
112
|
+
self.assertEqual(Fake.seen[0]["body"]["reports"], ["counterparties"])
|
|
113
|
+
self.assertEqual(Fake.seen[1]["body"], {"descriptor": "NETFLX", "expected": {"name": "Netflix"}, "note": "typo"})
|
|
114
|
+
|
|
115
|
+
def test_a_merchant_id_is_escaped_into_the_path(self):
|
|
116
|
+
Fake.answers = [(200, {}, {})]
|
|
117
|
+
self.k.merchant("mer_ct299q5tz5")
|
|
118
|
+
self.assertEqual(Fake.seen[0]["path"], "/v1/merchants/mer_ct299q5tz5")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
if __name__ == "__main__":
|
|
122
|
+
unittest.main()
|