encar-api-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.
@@ -0,0 +1,24 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .venv/
8
+ venv/
9
+ .pytest_cache/
10
+ .mypy_cache/
11
+ .ruff_cache/
12
+
13
+ # JavaScript
14
+ node_modules/
15
+ *.tgz
16
+ coverage/
17
+
18
+ # Secrets, editors, OS
19
+ .env
20
+ .env.*
21
+ .idea/
22
+ .vscode/
23
+ .DS_Store
24
+ Thumbs.db
@@ -0,0 +1,6 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 — 2026-11-09
4
+
5
+ - First release: `Client` and `AsyncClient` over `apiauto-space` with the market preset to `kr`,
6
+ `car_id()`, `raw()` and `EncarRaw` types.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 apiauto.space
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,168 @@
1
+ Metadata-Version: 2.5
2
+ Name: encar-api-client
3
+ Version: 0.1.0
4
+ Summary: Encar API client for Python: South Korean used-car listings from Encar as JSON, from the apiauto.space team
5
+ Project-URL: Homepage, https://apiauto.space/en/encar-api/
6
+ Project-URL: Documentation, https://apiauto.space/en/docs/
7
+ Project-URL: Repository, https://github.com/apiauto-space/encar-api
8
+ Project-URL: Issues, https://github.com/apiauto-space/encar-api/issues
9
+ Project-URL: Changelog, https://github.com/apiauto-space/encar-api/blob/main/python/CHANGELOG.md
10
+ Project-URL: Get a demo key, https://t.me/apiautospace_bot?start=demo
11
+ Author: apiauto.space
12
+ License-Expression: MIT
13
+ License-File: LICENSE
14
+ Keywords: api client,car listings,encar,encar api,encar.com,korea used cars,korean cars,used cars,vehicle data
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Topic :: Internet :: WWW/HTTP
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Classifier: Typing :: Typed
28
+ Requires-Python: >=3.10
29
+ Requires-Dist: apiauto-space<0.2,>=0.1.1
30
+ Description-Content-Type: text/markdown
31
+
32
+ # encar-api-client — Encar API client for Python
33
+
34
+ [![PyPI version](https://img.shields.io/pypi/v/encar-api-client.svg)](https://pypi.org/project/encar-api-client/)
35
+ [![Python versions](https://img.shields.io/pypi/pyversions/encar-api-client.svg)](https://pypi.org/project/encar-api-client/)
36
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/apiauto-space/encar-api/blob/main/LICENSE)
37
+
38
+ `encar-api-client` gives you South Korean used-car listings from Encar as clean JSON through the [apiauto.space](https://apiauto.space/en/encar-api/)
39
+ REST API, without writing or maintaining a scraper. Search by make, model, year, price and mileage, page
40
+ through the whole catalog, fetch one listing by its number and follow a feed of new cars, cars taken off sale
41
+ and price changes.
42
+
43
+ It is a thin layer over the general [`apiauto-space`](https://pypi.org/project/apiauto-space/) client with
44
+ the market preset to `kr`, plus types for the Encar-only fields. It comes from the apiauto.space team;
45
+ the project is not affiliated with Encar or SK Encar.
46
+
47
+ - Sync `Client` and `AsyncClient`, retries on 429 and 5xx, one exception class per API error
48
+ - `car("42793038")` takes the Encar listing number as well as the record id
49
+ - `EncarRaw` types for the Encar-only fields in `car["raw"]`
50
+ - Python 3.10+, `py.typed`, checked with `mypy --strict`
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ pip install encar-api-client
56
+ ```
57
+
58
+ The module you import is `encar_api`.
59
+
60
+ ## Get a key
61
+
62
+ Open the Telegram bot [@apiautospace_bot](https://t.me/apiautospace_bot?start=demo) and take a free demo
63
+ key: one day, 100 data requests, up to 20 cars per request. Paid plans are on the
64
+ [pricing page](https://apiauto.space/en/#pricing).
65
+
66
+ Save the key in the `APIAUTO_KEY` environment variable — the client reads it from there:
67
+
68
+ ```bash
69
+ export APIAUTO_KEY="your-key"
70
+ ```
71
+
72
+ Keep the key on your server: the API does not accept browser requests.
73
+
74
+ ## Quick start
75
+
76
+ ```python
77
+ import encar_api
78
+
79
+ with encar_api.Client() as client: # reads APIAUTO_KEY
80
+ page = client.cars(brand="Hyundai", year_min=2020, limit=20)
81
+ for car in page["items"]:
82
+ print(car["id"], car["title"], car["price"]["amount"], car["price"]["currency"])
83
+
84
+ one = client.car("42793038") # a listing number or "encar:42793038"
85
+ print(one["listing_url"], one["photos"][:1])
86
+ ```
87
+
88
+ A record looks like this (shortened; real values from the catalog):
89
+
90
+ ```json
91
+ {
92
+ "id": "encar:42793038",
93
+ "market": "kr",
94
+ "source": "encar",
95
+ "source_id": "42793038",
96
+ "title": "2021 BMW 1 Series (F40) 118d M Sport",
97
+ "brand": "BMW",
98
+ "model": "1 Series (F40)",
99
+ "year": 2021,
100
+ "mileage_km": 122866,
101
+ "fuel": "diesel",
102
+ "transmission": null,
103
+ "body_type": null,
104
+ "price": {
105
+ "amount": "17990000.00",
106
+ "currency": "KRW"
107
+ },
108
+ "price_usd": "13265.53",
109
+ "location": {
110
+ "country": "KR",
111
+ "region": "Gyeonggi",
112
+ "city": null
113
+ },
114
+ "listing_url": "https://fem.encar.com/cars/detail/42793038",
115
+ "is_active": true,
116
+ "first_seen_at": "2026-09-23T11:36:05.145090Z",
117
+ "photos": [
118
+ "https://api.apiauto.space/img/encar:42793038/1.jpg?exp=...&sig=..."
119
+ ],
120
+ "raw": {
121
+ "badge": "118d M 스포츠",
122
+ "sell_type": "normal",
123
+ "office_city": "경기",
124
+ "form_year": "202110"
125
+ }
126
+ }
127
+ ```
128
+
129
+ Every record has the same keys as in the other apiauto.space markets; a value the source does not provide is
130
+ `None`. Prices are decimal strings in KRW, `price_usd` is converted at the ECB daily rate.
131
+
132
+ ## Methods
133
+
134
+ | Method | What it does | Quota |
135
+ |---|---|---|
136
+ | `cars(**filters)` | One page of Encar cars: `brand`, `model`, `year_min`, `year_max`, `price_min`, `price_max`, `mileage_max`, `fuel`, `body_type`, `sort`, `limit`, `cursor` | Cars returned |
137
+ | `iter_cars(max_items=None, **filters)` | Every matching car, page after page | Cars returned |
138
+ | `car(listing)` | One car by listing number or id, including cars taken off sale in the last 14 days | 1 record |
139
+ | `changes(since, type=None)` / `iter_changes(...)` | Feed of `added`, `disappeared`, `price_drop`, `price_up` events | Events returned |
140
+ | `brands()` / `models(brand)` | Makes and models with car counts | Free |
141
+ | `status()` | Plan access, data age and the number of active cars of the market | Free |
142
+ | `usage()` | Your plan, its term and the quota spent | Free |
143
+
144
+ The general client is at `client.core` for anything else. Errors are the `apiauto` exceptions, re-exported
145
+ here: `QuotaExceededError`, `RateLimitError`, `NotFoundError`, `AuthenticationError` and the rest.
146
+
147
+ ## Encar-only fields
148
+
149
+ ```python
150
+ from encar_api import raw
151
+
152
+ extra = raw(car) # typed as EncarRaw
153
+ print(extra.get("source_values"))
154
+ ```
155
+
156
+ `EncarRaw` lists the keys with comments; every key is optional, so read them with `.get`.
157
+
158
+ ## Links
159
+
160
+ - [Encar API on apiauto.space](https://apiauto.space/en/encar-api/) and the [API documentation](https://apiauto.space/en/docs/)
161
+ - [`apiauto-space`](https://pypi.org/project/apiauto-space/): the general client for all markets
162
+ - Clients for the other sources: [`che168-api`](https://pypi.org/project/che168-api/), [`copart-api`](https://pypi.org/project/copart-api/), [`iaai-api`](https://pypi.org/project/iaai-api/)
163
+ - [Examples in curl, Python, JavaScript and PHP](https://github.com/apiauto-space/encar-api-examples)
164
+ - The JavaScript version of this client: [`encar-api-client` on npm](https://www.npmjs.com/package/encar-api-client)
165
+
166
+ ## License
167
+
168
+ MIT. Encar is a trademark of its owner; it is named here only to say which listings the client returns.
@@ -0,0 +1,137 @@
1
+ # encar-api-client — Encar API client for Python
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/encar-api-client.svg)](https://pypi.org/project/encar-api-client/)
4
+ [![Python versions](https://img.shields.io/pypi/pyversions/encar-api-client.svg)](https://pypi.org/project/encar-api-client/)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/apiauto-space/encar-api/blob/main/LICENSE)
6
+
7
+ `encar-api-client` gives you South Korean used-car listings from Encar as clean JSON through the [apiauto.space](https://apiauto.space/en/encar-api/)
8
+ REST API, without writing or maintaining a scraper. Search by make, model, year, price and mileage, page
9
+ through the whole catalog, fetch one listing by its number and follow a feed of new cars, cars taken off sale
10
+ and price changes.
11
+
12
+ It is a thin layer over the general [`apiauto-space`](https://pypi.org/project/apiauto-space/) client with
13
+ the market preset to `kr`, plus types for the Encar-only fields. It comes from the apiauto.space team;
14
+ the project is not affiliated with Encar or SK Encar.
15
+
16
+ - Sync `Client` and `AsyncClient`, retries on 429 and 5xx, one exception class per API error
17
+ - `car("42793038")` takes the Encar listing number as well as the record id
18
+ - `EncarRaw` types for the Encar-only fields in `car["raw"]`
19
+ - Python 3.10+, `py.typed`, checked with `mypy --strict`
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install encar-api-client
25
+ ```
26
+
27
+ The module you import is `encar_api`.
28
+
29
+ ## Get a key
30
+
31
+ Open the Telegram bot [@apiautospace_bot](https://t.me/apiautospace_bot?start=demo) and take a free demo
32
+ key: one day, 100 data requests, up to 20 cars per request. Paid plans are on the
33
+ [pricing page](https://apiauto.space/en/#pricing).
34
+
35
+ Save the key in the `APIAUTO_KEY` environment variable — the client reads it from there:
36
+
37
+ ```bash
38
+ export APIAUTO_KEY="your-key"
39
+ ```
40
+
41
+ Keep the key on your server: the API does not accept browser requests.
42
+
43
+ ## Quick start
44
+
45
+ ```python
46
+ import encar_api
47
+
48
+ with encar_api.Client() as client: # reads APIAUTO_KEY
49
+ page = client.cars(brand="Hyundai", year_min=2020, limit=20)
50
+ for car in page["items"]:
51
+ print(car["id"], car["title"], car["price"]["amount"], car["price"]["currency"])
52
+
53
+ one = client.car("42793038") # a listing number or "encar:42793038"
54
+ print(one["listing_url"], one["photos"][:1])
55
+ ```
56
+
57
+ A record looks like this (shortened; real values from the catalog):
58
+
59
+ ```json
60
+ {
61
+ "id": "encar:42793038",
62
+ "market": "kr",
63
+ "source": "encar",
64
+ "source_id": "42793038",
65
+ "title": "2021 BMW 1 Series (F40) 118d M Sport",
66
+ "brand": "BMW",
67
+ "model": "1 Series (F40)",
68
+ "year": 2021,
69
+ "mileage_km": 122866,
70
+ "fuel": "diesel",
71
+ "transmission": null,
72
+ "body_type": null,
73
+ "price": {
74
+ "amount": "17990000.00",
75
+ "currency": "KRW"
76
+ },
77
+ "price_usd": "13265.53",
78
+ "location": {
79
+ "country": "KR",
80
+ "region": "Gyeonggi",
81
+ "city": null
82
+ },
83
+ "listing_url": "https://fem.encar.com/cars/detail/42793038",
84
+ "is_active": true,
85
+ "first_seen_at": "2026-09-23T11:36:05.145090Z",
86
+ "photos": [
87
+ "https://api.apiauto.space/img/encar:42793038/1.jpg?exp=...&sig=..."
88
+ ],
89
+ "raw": {
90
+ "badge": "118d M 스포츠",
91
+ "sell_type": "normal",
92
+ "office_city": "경기",
93
+ "form_year": "202110"
94
+ }
95
+ }
96
+ ```
97
+
98
+ Every record has the same keys as in the other apiauto.space markets; a value the source does not provide is
99
+ `None`. Prices are decimal strings in KRW, `price_usd` is converted at the ECB daily rate.
100
+
101
+ ## Methods
102
+
103
+ | Method | What it does | Quota |
104
+ |---|---|---|
105
+ | `cars(**filters)` | One page of Encar cars: `brand`, `model`, `year_min`, `year_max`, `price_min`, `price_max`, `mileage_max`, `fuel`, `body_type`, `sort`, `limit`, `cursor` | Cars returned |
106
+ | `iter_cars(max_items=None, **filters)` | Every matching car, page after page | Cars returned |
107
+ | `car(listing)` | One car by listing number or id, including cars taken off sale in the last 14 days | 1 record |
108
+ | `changes(since, type=None)` / `iter_changes(...)` | Feed of `added`, `disappeared`, `price_drop`, `price_up` events | Events returned |
109
+ | `brands()` / `models(brand)` | Makes and models with car counts | Free |
110
+ | `status()` | Plan access, data age and the number of active cars of the market | Free |
111
+ | `usage()` | Your plan, its term and the quota spent | Free |
112
+
113
+ The general client is at `client.core` for anything else. Errors are the `apiauto` exceptions, re-exported
114
+ here: `QuotaExceededError`, `RateLimitError`, `NotFoundError`, `AuthenticationError` and the rest.
115
+
116
+ ## Encar-only fields
117
+
118
+ ```python
119
+ from encar_api import raw
120
+
121
+ extra = raw(car) # typed as EncarRaw
122
+ print(extra.get("source_values"))
123
+ ```
124
+
125
+ `EncarRaw` lists the keys with comments; every key is optional, so read them with `.get`.
126
+
127
+ ## Links
128
+
129
+ - [Encar API on apiauto.space](https://apiauto.space/en/encar-api/) and the [API documentation](https://apiauto.space/en/docs/)
130
+ - [`apiauto-space`](https://pypi.org/project/apiauto-space/): the general client for all markets
131
+ - Clients for the other sources: [`che168-api`](https://pypi.org/project/che168-api/), [`copart-api`](https://pypi.org/project/copart-api/), [`iaai-api`](https://pypi.org/project/iaai-api/)
132
+ - [Examples in curl, Python, JavaScript and PHP](https://github.com/apiauto-space/encar-api-examples)
133
+ - The JavaScript version of this client: [`encar-api-client` on npm](https://www.npmjs.com/package/encar-api-client)
134
+
135
+ ## License
136
+
137
+ MIT. Encar is a trademark of its owner; it is named here only to say which listings the client returns.
@@ -0,0 +1,70 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "encar-api-client"
7
+ dynamic = ["version"]
8
+ description = "Encar API client for Python: South Korean used-car listings from Encar as JSON, from the apiauto.space team"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "apiauto.space" }]
14
+ keywords = ["encar", "encar api", "encar.com", "korean cars", "korea used cars", "used cars", "car listings", "vehicle data", "api client"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
26
+ "Topic :: Internet :: WWW/HTTP",
27
+ "Topic :: Software Development :: Libraries :: Python Modules",
28
+ "Typing :: Typed",
29
+ ]
30
+ dependencies = ["apiauto-space>=0.1.1,<0.2"]
31
+
32
+ [project.urls]
33
+ Homepage = "https://apiauto.space/en/encar-api/"
34
+ Documentation = "https://apiauto.space/en/docs/"
35
+ Repository = "https://github.com/apiauto-space/encar-api"
36
+ Issues = "https://github.com/apiauto-space/encar-api/issues"
37
+ Changelog = "https://github.com/apiauto-space/encar-api/blob/main/python/CHANGELOG.md"
38
+ "Get a demo key" = "https://t.me/apiautospace_bot?start=demo"
39
+
40
+ [dependency-groups]
41
+ dev = ["pytest>=8", "ruff>=0.15", "mypy>=1.15", "typing_extensions>=4.12"]
42
+
43
+ [tool.hatch.version]
44
+ path = "src/encar_api/_version.py"
45
+
46
+ [tool.hatch.build.targets.sdist]
47
+ include = ["src", "tests", "CHANGELOG.md", "README.md", "LICENSE"]
48
+
49
+ [tool.hatch.build.targets.wheel]
50
+ packages = ["src/encar_api"]
51
+
52
+ [tool.pytest.ini_options]
53
+ testpaths = ["tests"]
54
+ addopts = "-ra"
55
+
56
+ [tool.ruff]
57
+ line-length = 110
58
+ target-version = "py310"
59
+ src = ["src", "tests"]
60
+
61
+ [tool.ruff.lint]
62
+ select = ["E", "W", "F", "I", "UP", "B", "A", "C4", "SIM", "PT", "RUF", "S", "T20"]
63
+
64
+ [tool.ruff.lint.per-file-ignores]
65
+ "tests/*" = ["S101", "S105", "S106"]
66
+
67
+ [tool.mypy]
68
+ strict = true
69
+ python_version = "3.10"
70
+ files = ["src", "tests"]
@@ -0,0 +1,72 @@
1
+ """Encar API client for Python: South Korean used-car listings from Encar as JSON.
2
+
3
+ A thin layer over the apiauto.space client (``apiauto``) with the market preset::
4
+
5
+ import encar_api
6
+
7
+ with encar_api.Client() as client: # the key comes from APIAUTO_KEY
8
+ for car in client.cars(brand="Hyundai", year_min=2020, limit=20)["items"]:
9
+ print(car["id"], car["title"], car["price"]["amount"])
10
+
11
+ From the apiauto.space team. Not affiliated with Encar or SK Encar.
12
+ """
13
+
14
+ from apiauto import (
15
+ ApiautoError,
16
+ APIConnectionError,
17
+ AuthenticationError,
18
+ BadRequestError,
19
+ Car,
20
+ CarFilters,
21
+ CarsPage,
22
+ Change,
23
+ ChangesPage,
24
+ ChangeType,
25
+ Market,
26
+ NotFoundError,
27
+ PermissionDeniedError,
28
+ Price,
29
+ QuotaExceededError,
30
+ RateLimitError,
31
+ ReferenceItem,
32
+ ServerError,
33
+ ServiceUnavailableError,
34
+ Usage,
35
+ )
36
+
37
+ from ._client import MARKET, SHARED_MARKET, SOURCE, AsyncClient, Client, car_id
38
+ from ._version import __version__
39
+ from .types import EncarRaw, FxQuote, raw
40
+
41
+ __all__ = [
42
+ "MARKET",
43
+ "SHARED_MARKET",
44
+ "SOURCE",
45
+ "APIConnectionError",
46
+ "ApiautoError",
47
+ "AsyncClient",
48
+ "AuthenticationError",
49
+ "BadRequestError",
50
+ "Car",
51
+ "CarFilters",
52
+ "CarsPage",
53
+ "Change",
54
+ "ChangeType",
55
+ "ChangesPage",
56
+ "Client",
57
+ "EncarRaw",
58
+ "FxQuote",
59
+ "Market",
60
+ "NotFoundError",
61
+ "PermissionDeniedError",
62
+ "Price",
63
+ "QuotaExceededError",
64
+ "RateLimitError",
65
+ "ReferenceItem",
66
+ "ServerError",
67
+ "ServiceUnavailableError",
68
+ "Usage",
69
+ "__version__",
70
+ "car_id",
71
+ "raw",
72
+ ]
@@ -0,0 +1,285 @@
1
+ """Encar clients: the apiauto clients with the market preset to ``kr``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import AsyncIterator, Iterator, Sequence
6
+ from datetime import datetime
7
+ from decimal import Decimal
8
+ from types import TracebackType
9
+ from typing import TYPE_CHECKING, Any, Literal
10
+
11
+ import apiauto
12
+ from apiauto import (
13
+ Car,
14
+ CarsPage,
15
+ Change,
16
+ ChangesPage,
17
+ ChangeType,
18
+ Dictionaries,
19
+ Market,
20
+ ReferenceItem,
21
+ Usage,
22
+ )
23
+
24
+ if TYPE_CHECKING:
25
+ import httpx
26
+ from apiauto import CarFilters
27
+ from typing_extensions import Self, Unpack
28
+
29
+ MARKET: Literal["kr"] = "kr"
30
+ """The apiauto.space market of Encar."""
31
+ SOURCE: Literal["encar"] = "encar"
32
+ """The ``source`` of every record this package returns."""
33
+ SHARED_MARKET = False
34
+ """``True`` when the market also holds another source and records are filtered on the client."""
35
+
36
+
37
+ def car_id(listing: str | int) -> str:
38
+ """The full record id for a Encar listing number: ``42793038`` -> ``encar:42793038``.
39
+
40
+ An id that already has the ``encar:`` prefix is returned as is; another
41
+ source's prefix raises ``ValueError``.
42
+ """
43
+ text = str(listing).strip()
44
+ if not text:
45
+ raise ValueError("listing must not be empty")
46
+ prefix, sep, number = text.partition(":")
47
+ if not sep:
48
+ return f"{SOURCE}:{text}"
49
+ if prefix != SOURCE or not number:
50
+ raise ValueError(f"not a Encar id: {text!r}")
51
+ return text
52
+
53
+
54
+ def _ours(car: Car) -> bool:
55
+ return car.get("source") == SOURCE
56
+
57
+
58
+ def _our_change(change: Change) -> bool:
59
+ return change["car_id"].startswith(SOURCE + ":")
60
+
61
+
62
+ def _core_options(base_url: str | None) -> dict[str, Any]:
63
+ return {} if base_url is None else {"base_url": base_url}
64
+
65
+
66
+ def _own_market(markets: list[Market]) -> Market:
67
+ for market in markets:
68
+ if market["market"] == MARKET:
69
+ return market
70
+ raise apiauto.ApiautoError(f"the API did not list the {MARKET} market")
71
+
72
+
73
+ class Client:
74
+ """Encar client of the apiauto.space API, synchronous.
75
+
76
+ Args:
77
+ api_key: Your key; defaults to the ``APIAUTO_KEY`` environment variable.
78
+ base_url: The API root; ``https://api.apiauto.space/v1`` when omitted.
79
+ timeout: Seconds to wait for a response.
80
+ max_retries: Retries after 429, 5xx or a network error.
81
+ http_client: Your own ``httpx.Client``; the client does not close it.
82
+
83
+ Use it as a context manager or call :meth:`close`::
84
+
85
+ with encar_api.Client() as client:
86
+ page = client.cars(brand="Hyundai", limit=20)
87
+
88
+ The general client is available as :attr:`core` for anything this one does not wrap.
89
+ """
90
+
91
+ def __init__(
92
+ self,
93
+ api_key: str | None = None,
94
+ *,
95
+ base_url: str | None = None,
96
+ timeout: float = 30.0,
97
+ max_retries: int = 2,
98
+ http_client: httpx.Client | None = None,
99
+ ) -> None:
100
+ self.core = apiauto.Client(
101
+ api_key,
102
+ timeout=timeout,
103
+ max_retries=max_retries,
104
+ http_client=http_client,
105
+ **_core_options(base_url),
106
+ )
107
+
108
+ def close(self) -> None:
109
+ """Close the HTTP connections (unless the ``http_client`` was yours)."""
110
+ self.core.close()
111
+
112
+ def __enter__(self) -> Self:
113
+ return self
114
+
115
+ def __exit__(
116
+ self,
117
+ exc_type: type[BaseException] | None,
118
+ exc: BaseException | None,
119
+ tb: TracebackType | None,
120
+ ) -> None:
121
+ self.close()
122
+
123
+ def cars(self, **filters: Unpack[CarFilters]) -> CarsPage:
124
+ """One page of Encar cars: ``GET /cars?market=kr``.
125
+
126
+ Takes the filters of :meth:`apiauto.Client.cars`: ``brand``, ``model``, ``year_min``,
127
+ ``year_max``, ``price_min``, ``price_max`` (in KRW), ``mileage_max``, ``sort``,
128
+ ``limit``, ``cursor`` and more. Every car returned counts against the quota.
129
+ """
130
+ page = self.core.cars(MARKET, **filters)
131
+ return page
132
+
133
+ def iter_cars(self, *, max_items: int | None = None, **filters: Unpack[CarFilters]) -> Iterator[Car]:
134
+ """Every Encar car matching the filters, following ``next_cursor``.
135
+
136
+ Args:
137
+ max_items: Stop after this many cars.
138
+ **filters: The filters of :meth:`cars`; ``limit`` sets the page size.
139
+ """
140
+ yield from self.core.iter_cars(MARKET, max_items=max_items, **filters)
141
+
142
+ def car(self, listing: str | int) -> Car:
143
+ """One car by listing number (``42793038``) or record id (``encar:42793038``).
144
+
145
+ Cars taken off sale stay available for 14 days with ``is_active=False``.
146
+ """
147
+ return self.core.car(car_id(listing))
148
+
149
+ def changes(
150
+ self,
151
+ since: datetime | str,
152
+ *,
153
+ type: ChangeType | Sequence[ChangeType] | None = None, # noqa: A002
154
+ min_pct: float | Decimal | None = None,
155
+ limit: int | None = None,
156
+ cursor: str | None = None,
157
+ ) -> ChangesPage:
158
+ """One page of the change feed: new cars, cars taken off sale and price changes since a moment."""
159
+ page = self.core.changes(MARKET, since, type=type, min_pct=min_pct, limit=limit, cursor=cursor)
160
+ return page
161
+
162
+ def iter_changes(
163
+ self,
164
+ since: datetime | str,
165
+ *,
166
+ type: ChangeType | Sequence[ChangeType] | None = None, # noqa: A002
167
+ min_pct: float | Decimal | None = None,
168
+ limit: int | None = None,
169
+ max_items: int | None = None,
170
+ ) -> Iterator[Change]:
171
+ """Every event of the change feed since a moment, following ``next_cursor``."""
172
+ yield from self.core.iter_changes(
173
+ MARKET, since, type=type, min_pct=min_pct, limit=limit, max_items=max_items
174
+ )
175
+
176
+ def brands(self) -> list[ReferenceItem]:
177
+ """Makes of the kr market with car counts, most frequent first. Free."""
178
+ return self.core.brands(MARKET)
179
+
180
+ def models(self, brand: str) -> list[ReferenceItem]:
181
+ """Models of a make with car counts. Free."""
182
+ return self.core.models(MARKET, brand)
183
+
184
+ def dictionaries(self) -> Dictionaries:
185
+ """Canonical values of ``fuel``, ``transmission``, ``body_type`` and more. Free."""
186
+ return self.core.dictionaries()
187
+
188
+ def status(self) -> Market:
189
+ """The kr market: plan access, data age and the number of active cars. Free."""
190
+ return _own_market(self.core.markets())
191
+
192
+ def usage(self) -> Usage:
193
+ """The plan, its term and how much of the quota is spent. Free."""
194
+ return self.core.usage()
195
+
196
+
197
+ class AsyncClient:
198
+ """Encar client of the apiauto.space API for asyncio; the methods of :class:`Client`.
199
+
200
+ ::
201
+
202
+ async with encar_api.AsyncClient() as client:
203
+ page = await client.cars(brand="Hyundai", limit=20)
204
+ """
205
+
206
+ def __init__(
207
+ self,
208
+ api_key: str | None = None,
209
+ *,
210
+ base_url: str | None = None,
211
+ timeout: float = 30.0,
212
+ max_retries: int = 2,
213
+ http_client: httpx.AsyncClient | None = None,
214
+ ) -> None:
215
+ self.core = apiauto.AsyncClient(
216
+ api_key,
217
+ timeout=timeout,
218
+ max_retries=max_retries,
219
+ http_client=http_client,
220
+ **_core_options(base_url),
221
+ )
222
+
223
+ async def close(self) -> None:
224
+ """Close the HTTP connections (unless the ``http_client`` was yours)."""
225
+ await self.core.close()
226
+
227
+ async def __aenter__(self) -> Self:
228
+ return self
229
+
230
+ async def __aexit__(
231
+ self,
232
+ exc_type: type[BaseException] | None,
233
+ exc: BaseException | None,
234
+ tb: TracebackType | None,
235
+ ) -> None:
236
+ await self.close()
237
+
238
+ async def cars(self, **filters: Unpack[CarFilters]) -> CarsPage:
239
+ """One page of Encar cars; see :meth:`Client.cars`."""
240
+ page = await self.core.cars(MARKET, **filters)
241
+ return page
242
+
243
+ async def iter_cars(
244
+ self, *, max_items: int | None = None, **filters: Unpack[CarFilters]
245
+ ) -> AsyncIterator[Car]:
246
+ """Every Encar car matching the filters; see :meth:`Client.iter_cars`."""
247
+ async for car in self.core.iter_cars(MARKET, max_items=max_items, **filters):
248
+ yield car
249
+
250
+ async def car(self, listing: str | int) -> Car:
251
+ """One car by listing number or record id; see :meth:`Client.car`."""
252
+ return await self.core.car(car_id(listing))
253
+
254
+ async def changes(
255
+ self,
256
+ since: datetime | str,
257
+ *,
258
+ type: ChangeType | Sequence[ChangeType] | None = None, # noqa: A002
259
+ min_pct: float | Decimal | None = None,
260
+ limit: int | None = None,
261
+ cursor: str | None = None,
262
+ ) -> ChangesPage:
263
+ """One page of the change feed; see :meth:`Client.changes`."""
264
+ page = await self.core.changes(MARKET, since, type=type, min_pct=min_pct, limit=limit, cursor=cursor)
265
+ return page
266
+
267
+ async def brands(self) -> list[ReferenceItem]:
268
+ """Makes of the kr market with car counts. Free."""
269
+ return await self.core.brands(MARKET)
270
+
271
+ async def models(self, brand: str) -> list[ReferenceItem]:
272
+ """Models of a make with car counts. Free."""
273
+ return await self.core.models(MARKET, brand)
274
+
275
+ async def dictionaries(self) -> Dictionaries:
276
+ """Canonical values of ``fuel``, ``transmission``, ``body_type`` and more. Free."""
277
+ return await self.core.dictionaries()
278
+
279
+ async def status(self) -> Market:
280
+ """The kr market: plan access, data age and the number of active cars. Free."""
281
+ return _own_market(await self.core.markets())
282
+
283
+ async def usage(self) -> Usage:
284
+ """The plan, its term and how much of the quota is spent. Free."""
285
+ return await self.core.usage()
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
File without changes
@@ -0,0 +1,55 @@
1
+ """Types of the Encar-only fields of a record.
2
+
3
+ Every record has the same common keys in every market (see :class:`apiauto.Car`);
4
+ the fields only Encar has are in ``car["raw"]``. :func:`raw` returns them typed::
5
+
6
+ from encar_api import raw
7
+
8
+ extra = raw(car)
9
+ print(extra.get("source_values"))
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import TypedDict, cast
15
+
16
+ from apiauto import Car
17
+
18
+ __all__ = ["EncarRaw", "FxQuote", "raw"]
19
+
20
+
21
+ class FxQuote(TypedDict):
22
+ """The ECB daily rate behind ``price_usd``."""
23
+
24
+ currency: str
25
+ usd_per_unit: str
26
+ """Decimal string: US dollars for one unit of ``currency``."""
27
+ date: str
28
+ source: str
29
+
30
+
31
+ class EncarRaw(TypedDict, total=False):
32
+ """Encar-only fields of a record (``car["raw"]``). Keys can be missing; read them with ``.get``."""
33
+
34
+ badge: str | None
35
+ """Encar's badge (trim) in Korean, as the listing shows it."""
36
+ badge_detail: str | None
37
+ office_city: str | None
38
+ """The dealer's province in Korean, for example ``경기``."""
39
+ sell_type: str | None
40
+ """``normal``, ``lease`` or ``rental``: lease and rental listings show a monthly payment, not a price."""
41
+ has_vin: bool
42
+ form_year: str | None
43
+ """The model-year code, ``YYYYMM``."""
44
+ body_class: str | None
45
+ condition: list[str]
46
+ trust: list[str]
47
+ service_mark: list[str]
48
+ source_values: dict[str, str | None]
49
+ """Encar's own Korean spellings of make, model, trim, fuel and region."""
50
+ fx: FxQuote | None
51
+
52
+
53
+ def raw(car: Car) -> EncarRaw:
54
+ """The Encar-only fields of a record, typed as :class:`EncarRaw`."""
55
+ return cast(EncarRaw, car.get("raw") or {})
@@ -0,0 +1,151 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ import httpx
9
+ import pytest
10
+
11
+ import encar_api
12
+
13
+ KEY = "test-key-1234567890"
14
+
15
+
16
+ def car(car_id: str) -> dict[str, Any]:
17
+ source = car_id.split(":", 1)[0]
18
+ return {"id": car_id, "market": "kr", "source": source, "title": "car", "price": {"amount": "1.00"}}
19
+
20
+
21
+ def page(ids: list[str], next_cursor: str | None = None, count: int | None = None) -> dict[str, Any]:
22
+ return {"items": [car(i) for i in ids], "next_cursor": next_cursor, "count": count}
23
+
24
+
25
+ class Recorder:
26
+ """Replays queued JSON bodies and records the requests."""
27
+
28
+ def __init__(self, *bodies: Any) -> None:
29
+ self.bodies = list(bodies)
30
+ self.requests: list[httpx.Request] = []
31
+
32
+ def __call__(self, request: httpx.Request) -> httpx.Response:
33
+ self.requests.append(request)
34
+ return httpx.Response(200, json=self.bodies.pop(0))
35
+
36
+ def params(self, index: int = -1) -> dict[str, str]:
37
+ return dict(self.requests[index].url.params)
38
+
39
+
40
+ def client(recorder: Callable[[httpx.Request], httpx.Response]) -> encar_api.Client:
41
+ http = httpx.Client(transport=httpx.MockTransport(recorder))
42
+ return encar_api.Client(KEY, http_client=http, max_retries=0)
43
+
44
+
45
+ def test_constants() -> None:
46
+ assert encar_api.MARKET == "kr"
47
+ assert encar_api.SOURCE == "encar"
48
+ assert encar_api.SHARED_MARKET is False
49
+ assert encar_api.__version__ == "0.1.0"
50
+
51
+
52
+ def test_cars_presets_the_market() -> None:
53
+ rec = Recorder(page(["encar:1", "encar:2"], count=2))
54
+ with client(rec) as api:
55
+ result = api.cars(brand="Hyundai", year_min=2020, limit=2)
56
+ assert [c["id"] for c in result["items"]] == ["encar:1", "encar:2"]
57
+ assert rec.requests[0].url.path == "/v1/cars"
58
+ assert rec.params() == {"market": "kr", "brand": "Hyundai", "year_min": "2020", "limit": "2"}
59
+ assert rec.requests[0].headers["x-api-key"] == KEY
60
+
61
+
62
+ def test_unknown_filter_is_rejected() -> None:
63
+ with client(Recorder()) as api, pytest.raises(TypeError):
64
+ api.cars(market="kr") # type: ignore[call-arg]
65
+
66
+
67
+ @pytest.mark.parametrize(
68
+ ("listing", "path"),
69
+ [
70
+ ("42793038", "/v1/cars/encar:42793038"),
71
+ (42793038, "/v1/cars/encar:42793038"),
72
+ ("encar:42793038", "/v1/cars/encar:42793038"),
73
+ ],
74
+ )
75
+ def test_car_accepts_number_or_id(listing: str | int, path: str) -> None:
76
+ rec = Recorder(car("encar:42793038"))
77
+ with client(rec) as api:
78
+ assert api.car(listing)["id"] == "encar:42793038"
79
+ assert rec.requests[0].url.path == path
80
+
81
+
82
+ @pytest.mark.parametrize("bad", ["", " ", "other:123", "encar:"])
83
+ def test_car_id_rejects_foreign_ids(bad: str) -> None:
84
+ with pytest.raises(ValueError, match=r"\S"):
85
+ encar_api.car_id(bad)
86
+
87
+
88
+ def test_brands_models_and_status() -> None:
89
+ markets = {
90
+ "items": [
91
+ {"market": "kr", "source": "encar", "active_cars": 1},
92
+ {"market": "cn", "source": "che168", "active_cars": 2},
93
+ {"market": "us", "source": "copart+iaai", "active_cars": 3},
94
+ ]
95
+ }
96
+ rec = Recorder([{"name": "Hyundai", "count": 5}], [{"name": "Grandeur", "count": 2}], markets)
97
+ with client(rec) as api:
98
+ assert api.brands()[0]["name"] == "Hyundai"
99
+ assert rec.params(0) == {"market": "kr"}
100
+ assert api.models("Hyundai")[0]["count"] == 2
101
+ assert rec.params(1) == {"market": "kr", "brand": "Hyundai"}
102
+ assert api.status()["market"] == "kr"
103
+
104
+
105
+ def test_raw_is_typed_view() -> None:
106
+ record: Any = {"id": "encar:42793038", "raw": {"source_values": {"brand": "x"}}}
107
+ assert encar_api.raw(record).get("source_values") == {"brand": "x"}
108
+ assert encar_api.raw({"id": "encar:42793038"}) == {} # type: ignore[typeddict-item]
109
+
110
+
111
+ def test_iter_cars_passes_max_items_to_the_last_page() -> None:
112
+ rec = Recorder(page(["encar:1", "encar:2"], next_cursor="c2"), page(["encar:3"]))
113
+ with client(rec) as api:
114
+ ids = [c["id"] for c in api.iter_cars(max_items=3, limit=2)]
115
+ assert ids == ["encar:1", "encar:2", "encar:3"]
116
+ assert rec.params(1)["cursor"] == "c2"
117
+ assert rec.params(1)["limit"] == "1"
118
+
119
+
120
+ def test_changes_presets_the_market() -> None:
121
+ rec = Recorder({"items": [{"id": 1, "car_id": "encar:1", "type": "added"}], "next_cursor": None})
122
+ with client(rec) as api:
123
+ result = api.changes("2026-11-01T00:00:00Z", type=["added", "price_drop"])
124
+ assert result["items"][0]["car_id"] == "encar:1"
125
+ assert rec.requests[0].url.params.get_list("type") == ["added", "price_drop"]
126
+ assert rec.params()["market"] == "kr"
127
+
128
+
129
+ def test_async_client() -> None:
130
+ rec = Recorder(page(["encar:1"]), car("encar:42793038"), page(["encar:1"]))
131
+
132
+ async def run() -> list[str]:
133
+ http = httpx.AsyncClient(transport=httpx.MockTransport(rec))
134
+ async with encar_api.AsyncClient(KEY, http_client=http, max_retries=0) as api:
135
+ first = await api.cars(limit=1)
136
+ one = await api.car("42793038")
137
+ more = [c["id"] async for c in api.iter_cars(max_items=1, limit=1)]
138
+ await http.aclose()
139
+ return [first["items"][0]["id"], one["id"], *more]
140
+
141
+ assert asyncio.run(run()) == ["encar:1", "encar:42793038", "encar:1"]
142
+ assert all(r.url.params.get("market") in (None, "kr") for r in rec.requests)
143
+
144
+
145
+ def test_errors_are_the_apiauto_ones() -> None:
146
+ def handler(request: httpx.Request) -> httpx.Response:
147
+ body = {"error": {"code": "not_found", "message": "no such car"}}
148
+ return httpx.Response(404, content=json.dumps(body), headers={"content-type": "application/json"})
149
+
150
+ with client(handler) as api, pytest.raises(encar_api.NotFoundError):
151
+ api.car("1")
@@ -0,0 +1,22 @@
1
+ """Smoke test against the live API; runs only when APIAUTO_KEY is set and spends a few records."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ import pytest
8
+
9
+ import encar_api
10
+
11
+ pytestmark = pytest.mark.skipif(not os.environ.get("APIAUTO_KEY"), reason="set APIAUTO_KEY to run")
12
+
13
+
14
+ def test_live_cars_and_car() -> None:
15
+ with encar_api.Client() as api:
16
+ assert api.status()["market"] == "kr"
17
+ cars = list(api.iter_cars(max_items=3, limit=3))
18
+ assert cars, "the catalog returned no Encar cars"
19
+ assert all(car["source"] == "encar" for car in cars)
20
+ one = api.car(cars[0]["source_id"])
21
+ assert one["id"] == cars[0]["id"]
22
+ assert isinstance(encar_api.raw(one), dict)