tradera-cli 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.
@@ -0,0 +1,2 @@
1
+ __all__ = ["__version__"]
2
+ __version__ = "0.1.0"
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
tradera_cli/api.py ADDED
@@ -0,0 +1,137 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from typing import Any
6
+
7
+ import requests
8
+ from requests import RequestException
9
+
10
+
11
+ BASE_URL = "https://www.tradera.com"
12
+
13
+
14
+ class TraderaApiError(RuntimeError):
15
+ pass
16
+
17
+
18
+ @dataclass
19
+ class TraderaClient:
20
+ base_url: str = BASE_URL
21
+ timeout_seconds: int = 20
22
+
23
+ def __post_init__(self) -> None:
24
+ self.session = requests.Session()
25
+ self.session.headers.update(
26
+ {
27
+ "accept": "application/json, text/plain, */*",
28
+ "user-agent": "tradera-cli/0.1.0",
29
+ }
30
+ )
31
+
32
+ def _request(self, method: str, path: str, **kwargs: Any) -> Any:
33
+ headers = dict(kwargs.pop("headers", {}))
34
+ if "json" in kwargs:
35
+ headers.setdefault("content-type", "application/json")
36
+
37
+ needs_token = path.startswith("/api/webapi/") or path.startswith("/ajax/")
38
+ if needs_token and path != "/api/webapi/auth/web/client/token":
39
+ self._ensure_client_token()
40
+
41
+ url = f"{self.base_url}{path}"
42
+ try:
43
+ response = self.session.request(method, url, timeout=self.timeout_seconds, headers=headers, **kwargs)
44
+ except RequestException as exc:
45
+ raise TraderaApiError(f"Request failed for {path}: {exc}") from exc
46
+
47
+ if response.status_code in {400, 401} and needs_token:
48
+ self._ensure_client_token(force=True)
49
+ try:
50
+ response = self.session.request(method, url, timeout=self.timeout_seconds, headers=headers, **kwargs)
51
+ except RequestException as exc:
52
+ raise TraderaApiError(f"Request retry failed for {path}: {exc}") from exc
53
+
54
+ if response.status_code >= 400:
55
+ raise TraderaApiError(f"{response.status_code} {response.reason}: {path}")
56
+ content_type = response.headers.get("content-type", "")
57
+ if "application/json" in content_type:
58
+ try:
59
+ return response.json()
60
+ except ValueError as exc:
61
+ raise TraderaApiError(f"Invalid JSON response from {path}") from exc
62
+ return response.text
63
+
64
+ def _ensure_client_token(self, force: bool = False) -> None:
65
+ if not force and self.session.cookies.get("trd_at"):
66
+ return
67
+ try:
68
+ response = self.session.post(
69
+ f"{self.base_url}/api/webapi/auth/web/client/token",
70
+ timeout=self.timeout_seconds,
71
+ headers={"content-type": "application/json", "accept": "application/json"},
72
+ )
73
+ except RequestException as exc:
74
+ raise TraderaApiError(f"Failed to establish anonymous client token: {exc}") from exc
75
+ if response.status_code >= 400:
76
+ raise TraderaApiError("Failed to establish anonymous client token")
77
+
78
+ def search(
79
+ self,
80
+ query: str,
81
+ page: int = 1,
82
+ page_size: int = 50,
83
+ sort_by: str = "Relevance",
84
+ language_code_iso2: str = "sv",
85
+ shipping_country_code_iso2: str = "SE",
86
+ automatic_translation_preferred: bool = True,
87
+ ) -> dict[str, Any]:
88
+ payload: dict[str, Any] = {
89
+ "isCsaSearchQuery": False,
90
+ "query": query,
91
+ "page": page,
92
+ "pageSize": page_size,
93
+ "sortBy": sort_by,
94
+ "languageCodeIso2": language_code_iso2.lower(),
95
+ "shippingCountryCodeIso2": shipping_country_code_iso2.upper(),
96
+ "automaticTranslationPreferred": automatic_translation_preferred,
97
+ "attributeFilters": [],
98
+ "categoryPath": [],
99
+ "currentCategoryId": 0,
100
+ "filterCounties": None,
101
+ "filterCategories": {},
102
+ "filterPrice": {},
103
+ "filters": {},
104
+ "headerText": None,
105
+ "internalSearch": {"showSearchBar": False},
106
+ "introText": None,
107
+ "isSavedSearchEmailEnabled": False,
108
+ "isShopOwnedByCurrentMember": False,
109
+ "items": [],
110
+ "relatedItems": [],
111
+ "itemsOnDisplay": [],
112
+ "mainText": None,
113
+ "pagination": None,
114
+ "totalItems": 0,
115
+ "searchLanguages": [],
116
+ "itemsMatchedViewModel": None,
117
+ "suggestion": None,
118
+ }
119
+ return self._request("POST", "/api/webapi/discover/web/independent-search", json=payload)
120
+
121
+ def item(self, item_id: int) -> dict[str, Any]:
122
+ data = self._request("GET", f"/ajax/item/{item_id}")
123
+ if not isinstance(data, dict):
124
+ raise TraderaApiError(f"Unexpected item response for item {item_id}")
125
+ return data
126
+
127
+ def categories(self, level: int = 1, lang: str = "sv") -> Any:
128
+ return self._request("GET", f"/api/categories/{level}?languageCodeIso2={lang}&next=1")
129
+
130
+
131
+ def parse_item_id(value: str) -> int:
132
+ if value.isdigit():
133
+ return int(value)
134
+ match = re.search(r"/(\d{6,})", value)
135
+ if not match:
136
+ raise ValueError(f"Could not parse item id from: {value}")
137
+ return int(match.group(1))
tradera_cli/cli.py ADDED
@@ -0,0 +1,111 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from typing import Any
6
+
7
+ from .api import TraderaApiError, TraderaClient, parse_item_id
8
+ from .formatters import (
9
+ normalize_categories_rows,
10
+ normalize_search_rows,
11
+ to_json,
12
+ to_jsonl,
13
+ to_table,
14
+ )
15
+
16
+
17
+ def _print_output(raw: Any, rows: list[dict[str, Any]], fmt: str, columns: list[str]) -> None:
18
+ if fmt == "json":
19
+ print(to_json(raw))
20
+ return
21
+ if fmt == "jsonl":
22
+ print(to_jsonl(rows))
23
+ return
24
+ print(to_table(rows, columns))
25
+
26
+
27
+ def cmd_search(args: argparse.Namespace) -> int:
28
+ client = TraderaClient()
29
+ data = client.search(
30
+ query=args.query,
31
+ page=args.page,
32
+ page_size=args.page_size,
33
+ sort_by=args.sort,
34
+ language_code_iso2=args.lang,
35
+ shipping_country_code_iso2=args.country,
36
+ automatic_translation_preferred=not args.no_translate,
37
+ )
38
+ rows = normalize_search_rows(data)
39
+ _print_output(
40
+ raw=data,
41
+ rows=rows,
42
+ fmt=args.format,
43
+ columns=["itemId", "title", "price", "currency", "endDate", "url"],
44
+ )
45
+ return 0
46
+
47
+
48
+ def cmd_item(args: argparse.Namespace) -> int:
49
+ client = TraderaClient()
50
+ item_id = parse_item_id(args.item)
51
+ data = client.item(item_id)
52
+ if args.format == "table":
53
+ row = {
54
+ "itemId": data.get("itemId") or data.get("id") or item_id,
55
+ "title": data.get("shortDescription") or data.get("title") or "",
56
+ "price": data.get("buyNowPrice") or data.get("nextBid") or data.get("price") or "",
57
+ "currency": data.get("currency") or "SEK",
58
+ "seller": (data.get("seller") or {}).get("alias") if isinstance(data.get("seller"), dict) else "",
59
+ }
60
+ print(to_table([row], ["itemId", "title", "price", "currency", "seller"]))
61
+ else:
62
+ print(to_json(data))
63
+ return 0
64
+
65
+
66
+ def cmd_categories(args: argparse.Namespace) -> int:
67
+ client = TraderaClient()
68
+ data = client.categories(level=args.level, lang=args.lang)
69
+ rows = normalize_categories_rows(data)
70
+ _print_output(raw=data, rows=rows, fmt=args.format, columns=["id", "name", "level"])
71
+ return 0
72
+
73
+
74
+ def build_parser() -> argparse.ArgumentParser:
75
+ parser = argparse.ArgumentParser(prog="tradera", description="Tradera CLI")
76
+ subparsers = parser.add_subparsers(dest="command", required=True)
77
+
78
+ search = subparsers.add_parser("search", help="Search listings")
79
+ search.add_argument("query", help="Search query")
80
+ search.add_argument("--page", type=int, default=1)
81
+ search.add_argument("--page-size", type=int, default=50)
82
+ search.add_argument("--sort", default="Relevance")
83
+ search.add_argument("--lang", default="sv")
84
+ search.add_argument("--country", default="SE")
85
+ search.add_argument("--no-translate", action="store_true")
86
+ search.add_argument("--format", choices=["table", "json", "jsonl"], default="table")
87
+ search.set_defaults(func=cmd_search)
88
+
89
+ item = subparsers.add_parser("item", help="Get item details")
90
+ item.add_argument("item", help="Item id or item URL")
91
+ item.add_argument("--format", choices=["table", "json"], default="json")
92
+ item.set_defaults(func=cmd_item)
93
+
94
+ categories = subparsers.add_parser("categories", help="List categories by level")
95
+ categories.add_argument("--level", type=int, default=1)
96
+ categories.add_argument("--lang", default="sv")
97
+ categories.add_argument("--format", choices=["table", "json", "jsonl"], default="table")
98
+ categories.set_defaults(func=cmd_categories)
99
+
100
+ return parser
101
+
102
+
103
+ def main(argv: list[str] | None = None) -> None:
104
+ parser = build_parser()
105
+ args = parser.parse_args(argv)
106
+ try:
107
+ code = args.func(args)
108
+ except (TraderaApiError, ValueError) as exc:
109
+ print(f"Error: {exc}", file=sys.stderr)
110
+ raise SystemExit(2) from exc
111
+ raise SystemExit(code)
@@ -0,0 +1,67 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import Any
5
+
6
+
7
+ def to_json(data: Any) -> str:
8
+ return json.dumps(data, ensure_ascii=False, indent=2)
9
+
10
+
11
+ def to_jsonl(items: list[dict[str, Any]]) -> str:
12
+ return "\n".join(json.dumps(item, ensure_ascii=False) for item in items)
13
+
14
+
15
+ def to_table(rows: list[dict[str, Any]], columns: list[str]) -> str:
16
+ if not rows:
17
+ return "No results"
18
+
19
+ widths = {column: len(column) for column in columns}
20
+ for row in rows:
21
+ for column in columns:
22
+ widths[column] = max(widths[column], len(str(row.get(column, ""))))
23
+
24
+ def line(values: list[str]) -> str:
25
+ return " | ".join(value.ljust(widths[col]) for value, col in zip(values, columns))
26
+
27
+ header = line(columns)
28
+ sep = "-+-".join("-" * widths[col] for col in columns)
29
+ body = [line([str(row.get(col, "")) for col in columns]) for row in rows]
30
+ return "\n".join([header, sep, *body])
31
+
32
+
33
+ def normalize_search_rows(data: dict[str, Any]) -> list[dict[str, Any]]:
34
+ items = data.get("items") or data.get("result", {}).get("items") or []
35
+ rows: list[dict[str, Any]] = []
36
+ for item in items:
37
+ rows.append(
38
+ {
39
+ "itemId": item.get("itemId") or item.get("id"),
40
+ "title": item.get("shortDescription") or item.get("title") or "",
41
+ "price": item.get("buyNowPrice") or item.get("nextBid") or item.get("price") or "",
42
+ "currency": item.get("currency") or "SEK",
43
+ "endDate": item.get("endDate") or item.get("endTime") or "",
44
+ "url": item.get("itemUrl") or item.get("itemLink") or "",
45
+ }
46
+ )
47
+ return rows
48
+
49
+
50
+ def normalize_categories_rows(data: Any) -> list[dict[str, Any]]:
51
+ if isinstance(data, dict):
52
+ categories = data.get("categories") or data.get("items") or []
53
+ elif isinstance(data, list):
54
+ categories = data
55
+ else:
56
+ categories = []
57
+
58
+ rows: list[dict[str, Any]] = []
59
+ for category in categories:
60
+ rows.append(
61
+ {
62
+ "id": category.get("id") or category.get("categoryId"),
63
+ "name": category.get("name") or category.get("title") or "",
64
+ "level": category.get("level") or "",
65
+ }
66
+ )
67
+ return rows
@@ -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,11 @@
1
+ tradera_cli/__init__.py,sha256=tXbRXsO0NE_UV1kIHiZTTQQH0fj0U2KoxxNusu_gzrM,48
2
+ tradera_cli/__main__.py,sha256=MSmt_5Xg84uHqzTN38JwgseJK8rsJn_11A8WD99VtEo,61
3
+ tradera_cli/api.py,sha256=rGJExNV7tq3z8TrHdAmbVmxw47lStG91k-KVREnvEhc,5047
4
+ tradera_cli/cli.py,sha256=IB0vvV6ctqCO7UskXDJyNVn59C-qVfDN9q-L6-eX0KU,3874
5
+ tradera_cli/formatters.py,sha256=ZGyHycffhHqc3Vm88nwp5ZR_1lyjOOsOlxuiG3bR77U,2287
6
+ tradera_cli-0.1.0.dist-info/licenses/LICENSE,sha256=JlB4zqH_oJ1H4a4kkasUxorVnIpVRo-t3DRvU5akaro,1065
7
+ tradera_cli-0.1.0.dist-info/METADATA,sha256=5hfLNvwKshJMHEDKN0w8zm-QxAGDOuwfUBqPNYtaYoQ,3501
8
+ tradera_cli-0.1.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
9
+ tradera_cli-0.1.0.dist-info/entry_points.txt,sha256=eC23nFxJkduOjEPhI7FGLWRFFh489gje8G6IlQN296M,49
10
+ tradera_cli-0.1.0.dist-info/top_level.txt,sha256=v7bZc-4QcMWcBOk4BwP3g_29soHfURhh2P1HCxZTA_E,12
11
+ tradera_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tradera = tradera_cli.cli:main
@@ -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 @@
1
+ tradera_cli