tradera-cli 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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Johnny W
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.
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.4
2
+ Name: tradera-cli
3
+ Version: 0.1.0
4
+ Summary: CLI for Tradera web endpoints
5
+ Author: Johnny W
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Paatsu/tradera-cli
8
+ Project-URL: Repository, https://github.com/Paatsu/tradera-cli
9
+ Project-URL: Issues, https://github.com/Paatsu/tradera-cli/issues
10
+ Keywords: cli,tradera,marketplace,terminal
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Internet
19
+ Classifier: Topic :: Utilities
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: requests>=2.32.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: build>=1.2.2; extra == "dev"
26
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
27
+ Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
28
+ Requires-Dist: twine>=5.1.1; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # tradera-cli
32
+
33
+ Fast CLI for searching public Tradera listings from the terminal.
34
+
35
+ Designed for scripts, agents, and quick lookups with structured output.
36
+
37
+ ## Install
38
+
39
+ From PyPI:
40
+
41
+ ```bash
42
+ pip install tradera-cli
43
+ ```
44
+
45
+ With `uv`:
46
+
47
+ ```bash
48
+ uv tool install tradera-cli
49
+ ```
50
+
51
+ With `pipx`:
52
+
53
+ ```bash
54
+ pipx install tradera-cli
55
+ ```
56
+
57
+ Upgrade:
58
+
59
+ ```bash
60
+ pip install --upgrade tradera-cli
61
+ ```
62
+
63
+ ## Usage
64
+
65
+ ### Search listings
66
+
67
+ ```bash
68
+ tradera search "iphone"
69
+ tradera search "pokemon" --page 2 --page-size 20
70
+ tradera search "kamera" --sort AddedOn --format json
71
+ tradera search "klocka" --country SE --lang sv --format jsonl
72
+ ```
73
+
74
+ ### Get item details
75
+
76
+ ```bash
77
+ tradera item 717898129
78
+ tradera item 717898129 --format json
79
+ tradera item "https://www.tradera.com/item/340186/717885898/iphone-12-pro"
80
+ ```
81
+
82
+ ### Browse categories
83
+
84
+ ```bash
85
+ tradera categories --level 1
86
+ tradera categories --level 2 --lang sv --format json
87
+ ```
88
+
89
+ ## Output formats
90
+
91
+ | Format | Description | Best for |
92
+ |---|---|---|
93
+ | `table` (default) | Human-readable table | Interactive terminal use |
94
+ | `json` | Pretty JSON object | `jq`, scripts, integrations |
95
+ | `jsonl` | One JSON object per line | Streaming/log pipelines |
96
+
97
+ ## Common options
98
+
99
+ Search command (`tradera search`) supports:
100
+
101
+ | Option | Description |
102
+ |---|---|
103
+ | `--page` | Page number (default: `1`) |
104
+ | `--page-size` | Results per page (default: `50`) |
105
+ | `--sort` | Sort mode (default: `Relevance`) |
106
+ | `--lang` | Language code (default: `sv`) |
107
+ | `--country` | Shipping country code (default: `SE`) |
108
+ | `--no-translate` | Disable automatic translation preference |
109
+ | `--format` | Output format: `table`, `json`, `jsonl` |
110
+
111
+ ## Development
112
+
113
+ From source:
114
+
115
+ ```bash
116
+ git clone https://github.com/Paatsu/tradera-cli.git
117
+ cd tradera-cli
118
+ pip install -e .[dev]
119
+ ```
120
+
121
+ Build distributions:
122
+
123
+ ```bash
124
+ python -m build
125
+ ```
126
+
127
+ Check the package metadata before upload:
128
+
129
+ ```bash
130
+ python -m twine check dist/*
131
+ ```
132
+
133
+ Run tests:
134
+
135
+ ```bash
136
+ pytest -q
137
+ ```
138
+
139
+ ## Agent integration
140
+
141
+ Examples for automation:
142
+
143
+ ```bash
144
+ # Take first 3 listings as JSON
145
+ tradera search "iphone" --format json | jq '.items[:3]'
146
+
147
+ # Stream listings line-by-line
148
+ tradera search "lego" --format jsonl
149
+
150
+ # Pull one item as machine-readable JSON
151
+ tradera item 717898129 --format json
152
+ ```
153
+
154
+ ## Notes
155
+
156
+ - Uses web endpoints from Tradera's frontend.
157
+ - Anonymous client token is fetched automatically when needed.
158
+ - Endpoint behavior can change over time.
@@ -0,0 +1,128 @@
1
+ # tradera-cli
2
+
3
+ Fast CLI for searching public Tradera listings from the terminal.
4
+
5
+ Designed for scripts, agents, and quick lookups with structured output.
6
+
7
+ ## Install
8
+
9
+ From PyPI:
10
+
11
+ ```bash
12
+ pip install tradera-cli
13
+ ```
14
+
15
+ With `uv`:
16
+
17
+ ```bash
18
+ uv tool install tradera-cli
19
+ ```
20
+
21
+ With `pipx`:
22
+
23
+ ```bash
24
+ pipx install tradera-cli
25
+ ```
26
+
27
+ Upgrade:
28
+
29
+ ```bash
30
+ pip install --upgrade tradera-cli
31
+ ```
32
+
33
+ ## Usage
34
+
35
+ ### Search listings
36
+
37
+ ```bash
38
+ tradera search "iphone"
39
+ tradera search "pokemon" --page 2 --page-size 20
40
+ tradera search "kamera" --sort AddedOn --format json
41
+ tradera search "klocka" --country SE --lang sv --format jsonl
42
+ ```
43
+
44
+ ### Get item details
45
+
46
+ ```bash
47
+ tradera item 717898129
48
+ tradera item 717898129 --format json
49
+ tradera item "https://www.tradera.com/item/340186/717885898/iphone-12-pro"
50
+ ```
51
+
52
+ ### Browse categories
53
+
54
+ ```bash
55
+ tradera categories --level 1
56
+ tradera categories --level 2 --lang sv --format json
57
+ ```
58
+
59
+ ## Output formats
60
+
61
+ | Format | Description | Best for |
62
+ |---|---|---|
63
+ | `table` (default) | Human-readable table | Interactive terminal use |
64
+ | `json` | Pretty JSON object | `jq`, scripts, integrations |
65
+ | `jsonl` | One JSON object per line | Streaming/log pipelines |
66
+
67
+ ## Common options
68
+
69
+ Search command (`tradera search`) supports:
70
+
71
+ | Option | Description |
72
+ |---|---|
73
+ | `--page` | Page number (default: `1`) |
74
+ | `--page-size` | Results per page (default: `50`) |
75
+ | `--sort` | Sort mode (default: `Relevance`) |
76
+ | `--lang` | Language code (default: `sv`) |
77
+ | `--country` | Shipping country code (default: `SE`) |
78
+ | `--no-translate` | Disable automatic translation preference |
79
+ | `--format` | Output format: `table`, `json`, `jsonl` |
80
+
81
+ ## Development
82
+
83
+ From source:
84
+
85
+ ```bash
86
+ git clone https://github.com/Paatsu/tradera-cli.git
87
+ cd tradera-cli
88
+ pip install -e .[dev]
89
+ ```
90
+
91
+ Build distributions:
92
+
93
+ ```bash
94
+ python -m build
95
+ ```
96
+
97
+ Check the package metadata before upload:
98
+
99
+ ```bash
100
+ python -m twine check dist/*
101
+ ```
102
+
103
+ Run tests:
104
+
105
+ ```bash
106
+ pytest -q
107
+ ```
108
+
109
+ ## Agent integration
110
+
111
+ Examples for automation:
112
+
113
+ ```bash
114
+ # Take first 3 listings as JSON
115
+ tradera search "iphone" --format json | jq '.items[:3]'
116
+
117
+ # Stream listings line-by-line
118
+ tradera search "lego" --format jsonl
119
+
120
+ # Pull one item as machine-readable JSON
121
+ tradera item 717898129 --format json
122
+ ```
123
+
124
+ ## Notes
125
+
126
+ - Uses web endpoints from Tradera's frontend.
127
+ - Anonymous client token is fetched automatically when needed.
128
+ - Endpoint behavior can change over time.
@@ -0,0 +1,52 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tradera-cli"
7
+ version = "0.1.0"
8
+ description = "CLI for Tradera web endpoints"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [
13
+ { name = "Johnny W" },
14
+ ]
15
+ keywords = ["cli", "tradera", "marketplace", "terminal"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Topic :: Internet",
25
+ "Topic :: Utilities",
26
+ ]
27
+ dependencies = [
28
+ "requests>=2.32.0",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/Paatsu/tradera-cli"
33
+ Repository = "https://github.com/Paatsu/tradera-cli"
34
+ Issues = "https://github.com/Paatsu/tradera-cli/issues"
35
+
36
+ [project.optional-dependencies]
37
+ dev = [
38
+ "build>=1.2.2",
39
+ "pytest>=8.0.0",
40
+ "pytest-cov>=5.0.0",
41
+ "twine>=5.1.1",
42
+ ]
43
+
44
+ [project.scripts]
45
+ tradera = "tradera_cli.cli:main"
46
+
47
+ [tool.setuptools.packages.find]
48
+ include = ["tradera_cli*"]
49
+
50
+ [tool.pytest.ini_options]
51
+ testpaths = ["tests"]
52
+ python_files = ["test_*.py"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,246 @@
1
+ from __future__ import annotations
2
+
3
+ import requests
4
+ import pytest
5
+
6
+ from tradera_cli.api import TraderaApiError, TraderaClient, parse_item_id
7
+
8
+
9
+ class FakeResponse:
10
+ def __init__(
11
+ self,
12
+ status_code: int = 200,
13
+ reason: str = "OK",
14
+ headers: dict[str, str] | None = None,
15
+ json_data: object | None = None,
16
+ text: str = "",
17
+ bad_json: bool = False,
18
+ ) -> None:
19
+ self.status_code = status_code
20
+ self.reason = reason
21
+ self.headers = headers or {}
22
+ self._json_data = json_data
23
+ self.text = text
24
+ self._bad_json = bad_json
25
+
26
+ def json(self) -> object:
27
+ if self._bad_json:
28
+ raise ValueError("bad json")
29
+ return self._json_data
30
+
31
+
32
+ class FakeSession:
33
+ def __init__(
34
+ self,
35
+ request_results: list[FakeResponse | Exception] | None = None,
36
+ post_results: list[FakeResponse | Exception] | None = None,
37
+ ) -> None:
38
+ self.request_results = request_results or []
39
+ self.post_results = post_results or []
40
+ self.request_calls: list[dict[str, object]] = []
41
+ self.post_calls: list[dict[str, object]] = []
42
+ self.cookies: dict[str, str] = {}
43
+ self.headers: dict[str, str] = {}
44
+
45
+ def request(self, method: str, url: str, **kwargs: object) -> FakeResponse:
46
+ self.request_calls.append({"method": method, "url": url, **kwargs})
47
+ result = self.request_results.pop(0)
48
+ if isinstance(result, Exception):
49
+ raise result
50
+ return result
51
+
52
+ def post(self, url: str, **kwargs: object) -> FakeResponse:
53
+ self.post_calls.append({"url": url, **kwargs})
54
+ result = self.post_results.pop(0)
55
+ if isinstance(result, Exception):
56
+ raise result
57
+ return result
58
+
59
+
60
+ def test_request_returns_json_and_sets_content_type() -> None:
61
+ client = TraderaClient()
62
+ fake = FakeSession(
63
+ request_results=[
64
+ FakeResponse(headers={"content-type": "application/json"}, json_data={"ok": True})
65
+ ]
66
+ )
67
+ client.session = fake
68
+
69
+ result = client._request("POST", "/public", json={"a": 1})
70
+
71
+ assert result == {"ok": True}
72
+ assert fake.request_calls[0]["headers"] == {"content-type": "application/json"}
73
+
74
+
75
+ def test_request_returns_text_for_non_json_response() -> None:
76
+ client = TraderaClient()
77
+ fake = FakeSession(request_results=[FakeResponse(headers={"content-type": "text/html"}, text="hello")])
78
+ client.session = fake
79
+
80
+ result = client._request("GET", "/public")
81
+
82
+ assert result == "hello"
83
+
84
+
85
+ def test_request_ensures_token_and_retries_on_401(monkeypatch: pytest.MonkeyPatch) -> None:
86
+ client = TraderaClient()
87
+ fake = FakeSession(
88
+ request_results=[
89
+ FakeResponse(status_code=401, reason="Unauthorized", headers={"content-type": "application/json"}),
90
+ FakeResponse(headers={"content-type": "application/json"}, json_data={"ok": 1}),
91
+ ]
92
+ )
93
+ client.session = fake
94
+
95
+ calls: list[bool] = []
96
+
97
+ def fake_ensure(force: bool = False) -> None:
98
+ calls.append(force)
99
+
100
+ monkeypatch.setattr(client, "_ensure_client_token", fake_ensure)
101
+
102
+ result = client._request("GET", "/api/webapi/discover/web/independent-search")
103
+
104
+ assert result == {"ok": 1}
105
+ assert calls == [False, True]
106
+
107
+
108
+ def test_request_raises_for_http_error() -> None:
109
+ client = TraderaClient()
110
+ fake = FakeSession(request_results=[FakeResponse(status_code=500, reason="Server Error")])
111
+ client.session = fake
112
+
113
+ with pytest.raises(TraderaApiError, match="500 Server Error"):
114
+ client._request("GET", "/public")
115
+
116
+
117
+ def test_request_wraps_request_exception() -> None:
118
+ client = TraderaClient()
119
+ fake = FakeSession(request_results=[requests.RequestException("boom")])
120
+ client.session = fake
121
+
122
+ with pytest.raises(TraderaApiError, match="Request failed"):
123
+ client._request("GET", "/public")
124
+
125
+
126
+ def test_request_wraps_retry_exception(monkeypatch: pytest.MonkeyPatch) -> None:
127
+ client = TraderaClient()
128
+ fake = FakeSession(
129
+ request_results=[
130
+ FakeResponse(status_code=400, reason="Bad Request"),
131
+ requests.RequestException("retry boom"),
132
+ ]
133
+ )
134
+ client.session = fake
135
+ monkeypatch.setattr(client, "_ensure_client_token", lambda force=False: None)
136
+
137
+ with pytest.raises(TraderaApiError, match="Request retry failed"):
138
+ client._request("GET", "/ajax/item/123")
139
+
140
+
141
+ def test_request_raises_on_bad_json() -> None:
142
+ client = TraderaClient()
143
+ fake = FakeSession(request_results=[FakeResponse(headers={"content-type": "application/json"}, bad_json=True)])
144
+ client.session = fake
145
+
146
+ with pytest.raises(TraderaApiError, match="Invalid JSON response"):
147
+ client._request("GET", "/public")
148
+
149
+
150
+ def test_ensure_client_token_skips_when_cookie_exists() -> None:
151
+ client = TraderaClient()
152
+ fake = FakeSession()
153
+ fake.cookies["trd_at"] = "token"
154
+ client.session = fake
155
+
156
+ client._ensure_client_token()
157
+
158
+ assert fake.post_calls == []
159
+
160
+
161
+ def test_ensure_client_token_success_and_force() -> None:
162
+ client = TraderaClient()
163
+ fake = FakeSession(post_results=[FakeResponse(status_code=200)])
164
+ fake.cookies["trd_at"] = "token"
165
+ client.session = fake
166
+
167
+ client._ensure_client_token(force=True)
168
+
169
+ assert len(fake.post_calls) == 1
170
+
171
+
172
+ def test_ensure_client_token_wraps_request_exception() -> None:
173
+ client = TraderaClient()
174
+ fake = FakeSession(post_results=[requests.RequestException("nope")])
175
+ client.session = fake
176
+
177
+ with pytest.raises(TraderaApiError, match="Failed to establish anonymous client token"):
178
+ client._ensure_client_token()
179
+
180
+
181
+ def test_ensure_client_token_raises_on_http_error() -> None:
182
+ client = TraderaClient()
183
+ fake = FakeSession(post_results=[FakeResponse(status_code=500)])
184
+ client.session = fake
185
+
186
+ with pytest.raises(TraderaApiError, match="Failed to establish anonymous client token"):
187
+ client._ensure_client_token()
188
+
189
+
190
+ def test_search_builds_payload() -> None:
191
+ client = TraderaClient()
192
+ captured: dict[str, object] = {}
193
+
194
+ def fake_request(method: str, path: str, **kwargs: object) -> dict[str, object]:
195
+ captured["method"] = method
196
+ captured["path"] = path
197
+ captured["json"] = kwargs["json"]
198
+ return {"items": []}
199
+
200
+ client._request = fake_request # type: ignore[method-assign]
201
+
202
+ result = client.search("kamera", page=2, page_size=10, sort_by="EndDate")
203
+
204
+ assert result == {"items": []}
205
+ assert captured["method"] == "POST"
206
+ assert captured["path"] == "/api/webapi/discover/web/independent-search"
207
+ payload = captured["json"]
208
+ assert isinstance(payload, dict)
209
+ assert payload["query"] == "kamera"
210
+ assert payload["page"] == 2
211
+ assert payload["pageSize"] == 10
212
+ assert payload["sortBy"] == "EndDate"
213
+
214
+
215
+ def test_item_returns_dict_or_raises() -> None:
216
+ client = TraderaClient()
217
+ client._request = lambda *_args, **_kwargs: {"itemId": 123} # type: ignore[method-assign]
218
+ assert client.item(123)["itemId"] == 123
219
+
220
+ client._request = lambda *_args, **_kwargs: "not a dict" # type: ignore[method-assign]
221
+ with pytest.raises(TraderaApiError, match="Unexpected item response"):
222
+ client.item(123)
223
+
224
+
225
+ def test_categories_calls_expected_path() -> None:
226
+ client = TraderaClient()
227
+ captured: dict[str, str] = {}
228
+
229
+ def fake_request(method: str, path: str, **_kwargs: object) -> list[dict[str, object]]:
230
+ captured["method"] = method
231
+ captured["path"] = path
232
+ return [{"id": 1}]
233
+
234
+ client._request = fake_request # type: ignore[method-assign]
235
+
236
+ result = client.categories(level=2, lang="en")
237
+
238
+ assert result == [{"id": 1}]
239
+ assert captured == {"method": "GET", "path": "/api/categories/2?languageCodeIso2=en&next=1"}
240
+
241
+
242
+ def test_parse_item_id_from_digits_and_url_and_invalid() -> None:
243
+ assert parse_item_id("123456") == 123456
244
+ assert parse_item_id("https://www.tradera.com/item/123456789/test") == 123456789
245
+ with pytest.raises(ValueError, match="Could not parse item id"):
246
+ parse_item_id("https://www.tradera.com/item/no-id")