|
| 1 | +"""Official Python client for the EnCarAPI — Korean car data API (Encar.com).""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import os |
| 5 | +from typing import Any, Dict, Optional |
| 6 | + |
| 7 | +import requests |
| 8 | + |
| 9 | +__all__ = ["EnCarAPI", "EnCarAPIError", "MissingApiKeyError"] |
| 10 | + |
| 11 | +DEFAULT_BASE_URL = "https://api.encarapi.com" |
| 12 | +SIGNUP_URL = "https://encarapi.com" |
| 13 | + |
| 14 | + |
| 15 | +class EnCarAPIError(Exception): |
| 16 | + """Raised when the EnCarAPI returns an error response.""" |
| 17 | + |
| 18 | + |
| 19 | +class MissingApiKeyError(EnCarAPIError): |
| 20 | + """Raised when no API key is provided.""" |
| 21 | + |
| 22 | + |
| 23 | +class EnCarAPI: |
| 24 | + """Client for the EnCarAPI Korean car data API. |
| 25 | +
|
| 26 | + An EnCarAPI key is **required**. Get one (5-day trial available) at |
| 27 | + https://encarapi.com — the API and its data are not free. |
| 28 | +
|
| 29 | + from encarapi import EnCarAPI |
| 30 | +
|
| 31 | + client = EnCarAPI("YOUR_API_KEY") # or set ENCARAPI_KEY in the environment |
| 32 | + cars = client.catalog(count=True) |
| 33 | + detail = client.vehicle("12345678") |
| 34 | + """ |
| 35 | + |
| 36 | + def __init__( |
| 37 | + self, |
| 38 | + api_key: Optional[str] = None, |
| 39 | + *, |
| 40 | + base_url: str = DEFAULT_BASE_URL, |
| 41 | + timeout: float = 30.0, |
| 42 | + ) -> None: |
| 43 | + api_key = api_key or os.environ.get("ENCARAPI_KEY") |
| 44 | + if not api_key: |
| 45 | + raise MissingApiKeyError( |
| 46 | + "An EnCarAPI key is required. Pass it as EnCarAPI('YOUR_KEY') or set " |
| 47 | + f"the ENCARAPI_KEY environment variable. Get a key at {SIGNUP_URL}" |
| 48 | + ) |
| 49 | + self.api_key = api_key |
| 50 | + self.base_url = base_url.rstrip("/") |
| 51 | + self.timeout = timeout |
| 52 | + self._session = requests.Session() |
| 53 | + self._session.headers.update( |
| 54 | + {"x-api-key": api_key, "Accept": "application/json"} |
| 55 | + ) |
| 56 | + |
| 57 | + # -- low level ------------------------------------------------------- |
| 58 | + def _get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Any: |
| 59 | + resp = self._session.get( |
| 60 | + f"{self.base_url}{path}", params=params, timeout=self.timeout |
| 61 | + ) |
| 62 | + if resp.status_code == 401 or resp.status_code == 403: |
| 63 | + raise EnCarAPIError( |
| 64 | + f"EnCarAPI rejected the request ({resp.status_code}). " |
| 65 | + f"Check your key or subscription at {SIGNUP_URL}. Body: {resp.text[:300]}" |
| 66 | + ) |
| 67 | + if not resp.ok: |
| 68 | + raise EnCarAPIError(f"EnCarAPI error {resp.status_code}: {resp.text[:300]}") |
| 69 | + return resp.json() |
| 70 | + |
| 71 | + # -- endpoints ------------------------------------------------------- |
| 72 | + def catalog(self, **params: Any) -> Any: |
| 73 | + """Search & filter the Korean car catalog (Encar.com listings).""" |
| 74 | + return self._get("/api/catalog", params or None) |
| 75 | + |
| 76 | + def nav(self, **params: Any) -> Any: |
| 77 | + """Filter facets / navigation metadata (brands, models, counts).""" |
| 78 | + return self._get("/api/nav", params or None) |
| 79 | + |
| 80 | + def vehicle(self, vehicle_id: str) -> Any: |
| 81 | + """Full detail for one vehicle: specs, options, inspection, price.""" |
| 82 | + return self._get(f"/api/vehicle/{vehicle_id}") |
0 commit comments