copart-api 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 `us`,
6
+ `car_id()`, `raw()` and `CopartRaw` 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,183 @@
1
+ Metadata-Version: 2.5
2
+ Name: copart-api
3
+ Version: 0.1.0
4
+ Summary: Copart API client for Python: Copart auction lots (USA) with VIN, damage and sale date as JSON, from the apiauto.space team
5
+ Project-URL: Homepage, https://apiauto.space/en/copart-api/
6
+ Project-URL: Documentation, https://apiauto.space/en/docs/
7
+ Project-URL: Repository, https://github.com/apiauto-space/copart-api
8
+ Project-URL: Issues, https://github.com/apiauto-space/copart-api/issues
9
+ Project-URL: Changelog, https://github.com/apiauto-space/copart-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 auction,copart,copart api,salvage cars,usa cars,used cars,vehicle data,vin
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
+ # copart-api — Copart API client for Python
33
+
34
+ [![PyPI version](https://img.shields.io/pypi/v/copart-api.svg)](https://pypi.org/project/copart-api/)
35
+ [![Python versions](https://img.shields.io/pypi/pyversions/copart-api.svg)](https://pypi.org/project/copart-api/)
36
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/apiauto-space/copart-api/blob/main/LICENSE)
37
+
38
+ `copart-api` gives you Copart auction lots (USA) with VIN, damage and sale date as clean JSON through the [apiauto.space](https://apiauto.space/en/copart-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 `us`, plus types for the Copart-only fields. It comes from the apiauto.space team;
45
+ the project is not affiliated with Copart.
46
+
47
+ - Sync `Client` and `AsyncClient`, retries on 429 and 5xx, one exception class per API error
48
+ - `car("68055056")` takes the Copart listing number as well as the record id
49
+ - `CopartRaw` types for the Copart-only fields in `car["raw"]`
50
+ - Python 3.10+, `py.typed`, checked with `mypy --strict`
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ pip install copart-api
56
+ ```
57
+
58
+ The module you import is `copart_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 copart_api
78
+
79
+ with copart_api.Client() as client: # reads APIAUTO_KEY
80
+ page = client.cars(brand="Toyota", 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("68055056") # a listing number or "copart:68055056"
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": "copart:68055056",
93
+ "market": "us",
94
+ "source": "copart",
95
+ "source_id": "68055056",
96
+ "title": "2019 Hyundai Elantra",
97
+ "brand": "Hyundai",
98
+ "model": "Elantra",
99
+ "year": 2019,
100
+ "mileage_km": 239240,
101
+ "fuel": "gasoline",
102
+ "transmission": "automatic",
103
+ "body_type": null,
104
+ "vin": "5NPD84LF8KH406860",
105
+ "price": {
106
+ "amount": "4000.00",
107
+ "currency": "USD"
108
+ },
109
+ "price_usd": "4000.00",
110
+ "location": {
111
+ "country": "US",
112
+ "region": "TN",
113
+ "city": "Nashville"
114
+ },
115
+ "listing_url": null,
116
+ "is_active": true,
117
+ "first_seen_at": "2026-09-23T00:21:16.304888Z",
118
+ "photos": [
119
+ "https://api.apiauto.space/img/copart:68055056/1.jpg?exp=...&sig=..."
120
+ ],
121
+ "raw": {
122
+ "lot_number": "68055056",
123
+ "sale_date": "2026-09-28T17:00:00+00:00",
124
+ "buy_now": 4000,
125
+ "damage_main": "front",
126
+ "title_doc": "clean",
127
+ "location_branch": "Nashville (TN)"
128
+ }
129
+ }
130
+ ```
131
+
132
+ Every record has the same keys as in the other apiauto.space markets; a value the source does not provide is
133
+ `None`. Prices are decimal strings in USD, `price_usd` is converted at the ECB daily rate.
134
+
135
+ ## Copart and IAAI share one market
136
+
137
+ The API keeps Copart and IAAI lots together in the `us` market and does not filter by auction yet. This client
138
+ asks for `us` cars and keeps only Copart lots on the client side. What that means for you:
139
+
140
+ - a page from `cars()` can hold fewer than `limit` lots, and its `count` is `None`;
141
+ - the IAAI lots that were dropped still count against your quota;
142
+ - `iter_cars(max_items=...)` reads pages until it has collected `max_items` Copart lots.
143
+
144
+ When you need both auctions, use the general `apiauto` client with `client.cars("us")`.
145
+
146
+ ## Methods
147
+
148
+ | Method | What it does | Quota |
149
+ |---|---|---|
150
+ | `cars(**filters)` | One page of Copart cars: `brand`, `model`, `year_min`, `year_max`, `price_min`, `price_max`, `mileage_max`, `fuel`, `body_type`, `sort`, `limit`, `cursor` | Cars returned |
151
+ | `iter_cars(max_items=None, **filters)` | Every matching car, page after page | Cars returned |
152
+ | `car(listing)` | One car by listing number or id, including cars taken off sale in the last 14 days | 1 record |
153
+ | `changes(since, type=None)` / `iter_changes(...)` | Feed of `added`, `disappeared`, `price_drop`, `price_up` events | Events returned |
154
+ | `brands()` / `models(brand)` | Makes and models with car counts | Free |
155
+ | `status()` | Plan access, data age and the number of active cars of the market | Free |
156
+ | `usage()` | Your plan, its term and the quota spent | Free |
157
+ | `live(make=..., model=...)` | Live search at the auction data provider for lots not in the catalog yet, Pro and Max plans | Separate counter |
158
+
159
+ The general client is at `client.core` for anything else. Errors are the `apiauto` exceptions, re-exported
160
+ here: `QuotaExceededError`, `RateLimitError`, `NotFoundError`, `AuthenticationError` and the rest.
161
+
162
+ ## Copart-only fields
163
+
164
+ ```python
165
+ from copart_api import raw
166
+
167
+ extra = raw(car) # typed as CopartRaw
168
+ print(extra.get("source_values"))
169
+ ```
170
+
171
+ `CopartRaw` lists the keys with comments; every key is optional, so read them with `.get`.
172
+
173
+ ## Links
174
+
175
+ - [Copart API on apiauto.space](https://apiauto.space/en/copart-api/) and the [API documentation](https://apiauto.space/en/docs/)
176
+ - [`apiauto-space`](https://pypi.org/project/apiauto-space/): the general client for all markets
177
+ - Clients for the other sources: [`encar-api-client`](https://pypi.org/project/encar-api-client/), [`che168-api`](https://pypi.org/project/che168-api/), [`iaai-api`](https://pypi.org/project/iaai-api/)
178
+ - [Examples in curl, Python, JavaScript and PHP](https://github.com/apiauto-space/copart-api-examples)
179
+ - The JavaScript version of this client: [`copart-api` on npm](https://www.npmjs.com/package/copart-api)
180
+
181
+ ## License
182
+
183
+ MIT. Copart is a trademark of its owner; it is named here only to say which listings the client returns.
@@ -0,0 +1,152 @@
1
+ # copart-api — Copart API client for Python
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/copart-api.svg)](https://pypi.org/project/copart-api/)
4
+ [![Python versions](https://img.shields.io/pypi/pyversions/copart-api.svg)](https://pypi.org/project/copart-api/)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/apiauto-space/copart-api/blob/main/LICENSE)
6
+
7
+ `copart-api` gives you Copart auction lots (USA) with VIN, damage and sale date as clean JSON through the [apiauto.space](https://apiauto.space/en/copart-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 `us`, plus types for the Copart-only fields. It comes from the apiauto.space team;
14
+ the project is not affiliated with Copart.
15
+
16
+ - Sync `Client` and `AsyncClient`, retries on 429 and 5xx, one exception class per API error
17
+ - `car("68055056")` takes the Copart listing number as well as the record id
18
+ - `CopartRaw` types for the Copart-only fields in `car["raw"]`
19
+ - Python 3.10+, `py.typed`, checked with `mypy --strict`
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install copart-api
25
+ ```
26
+
27
+ The module you import is `copart_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 copart_api
47
+
48
+ with copart_api.Client() as client: # reads APIAUTO_KEY
49
+ page = client.cars(brand="Toyota", 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("68055056") # a listing number or "copart:68055056"
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": "copart:68055056",
62
+ "market": "us",
63
+ "source": "copart",
64
+ "source_id": "68055056",
65
+ "title": "2019 Hyundai Elantra",
66
+ "brand": "Hyundai",
67
+ "model": "Elantra",
68
+ "year": 2019,
69
+ "mileage_km": 239240,
70
+ "fuel": "gasoline",
71
+ "transmission": "automatic",
72
+ "body_type": null,
73
+ "vin": "5NPD84LF8KH406860",
74
+ "price": {
75
+ "amount": "4000.00",
76
+ "currency": "USD"
77
+ },
78
+ "price_usd": "4000.00",
79
+ "location": {
80
+ "country": "US",
81
+ "region": "TN",
82
+ "city": "Nashville"
83
+ },
84
+ "listing_url": null,
85
+ "is_active": true,
86
+ "first_seen_at": "2026-09-23T00:21:16.304888Z",
87
+ "photos": [
88
+ "https://api.apiauto.space/img/copart:68055056/1.jpg?exp=...&sig=..."
89
+ ],
90
+ "raw": {
91
+ "lot_number": "68055056",
92
+ "sale_date": "2026-09-28T17:00:00+00:00",
93
+ "buy_now": 4000,
94
+ "damage_main": "front",
95
+ "title_doc": "clean",
96
+ "location_branch": "Nashville (TN)"
97
+ }
98
+ }
99
+ ```
100
+
101
+ Every record has the same keys as in the other apiauto.space markets; a value the source does not provide is
102
+ `None`. Prices are decimal strings in USD, `price_usd` is converted at the ECB daily rate.
103
+
104
+ ## Copart and IAAI share one market
105
+
106
+ The API keeps Copart and IAAI lots together in the `us` market and does not filter by auction yet. This client
107
+ asks for `us` cars and keeps only Copart lots on the client side. What that means for you:
108
+
109
+ - a page from `cars()` can hold fewer than `limit` lots, and its `count` is `None`;
110
+ - the IAAI lots that were dropped still count against your quota;
111
+ - `iter_cars(max_items=...)` reads pages until it has collected `max_items` Copart lots.
112
+
113
+ When you need both auctions, use the general `apiauto` client with `client.cars("us")`.
114
+
115
+ ## Methods
116
+
117
+ | Method | What it does | Quota |
118
+ |---|---|---|
119
+ | `cars(**filters)` | One page of Copart cars: `brand`, `model`, `year_min`, `year_max`, `price_min`, `price_max`, `mileage_max`, `fuel`, `body_type`, `sort`, `limit`, `cursor` | Cars returned |
120
+ | `iter_cars(max_items=None, **filters)` | Every matching car, page after page | Cars returned |
121
+ | `car(listing)` | One car by listing number or id, including cars taken off sale in the last 14 days | 1 record |
122
+ | `changes(since, type=None)` / `iter_changes(...)` | Feed of `added`, `disappeared`, `price_drop`, `price_up` events | Events returned |
123
+ | `brands()` / `models(brand)` | Makes and models with car counts | Free |
124
+ | `status()` | Plan access, data age and the number of active cars of the market | Free |
125
+ | `usage()` | Your plan, its term and the quota spent | Free |
126
+ | `live(make=..., model=...)` | Live search at the auction data provider for lots not in the catalog yet, Pro and Max plans | Separate counter |
127
+
128
+ The general client is at `client.core` for anything else. Errors are the `apiauto` exceptions, re-exported
129
+ here: `QuotaExceededError`, `RateLimitError`, `NotFoundError`, `AuthenticationError` and the rest.
130
+
131
+ ## Copart-only fields
132
+
133
+ ```python
134
+ from copart_api import raw
135
+
136
+ extra = raw(car) # typed as CopartRaw
137
+ print(extra.get("source_values"))
138
+ ```
139
+
140
+ `CopartRaw` lists the keys with comments; every key is optional, so read them with `.get`.
141
+
142
+ ## Links
143
+
144
+ - [Copart API on apiauto.space](https://apiauto.space/en/copart-api/) and the [API documentation](https://apiauto.space/en/docs/)
145
+ - [`apiauto-space`](https://pypi.org/project/apiauto-space/): the general client for all markets
146
+ - Clients for the other sources: [`encar-api-client`](https://pypi.org/project/encar-api-client/), [`che168-api`](https://pypi.org/project/che168-api/), [`iaai-api`](https://pypi.org/project/iaai-api/)
147
+ - [Examples in curl, Python, JavaScript and PHP](https://github.com/apiauto-space/copart-api-examples)
148
+ - The JavaScript version of this client: [`copart-api` on npm](https://www.npmjs.com/package/copart-api)
149
+
150
+ ## License
151
+
152
+ MIT. Copart 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 = "copart-api"
7
+ dynamic = ["version"]
8
+ description = "Copart API client for Python: Copart auction lots (USA) with VIN, damage and sale date 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 = ["copart", "copart api", "car auction", "salvage cars", "usa cars", "vin", "used cars", "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/copart-api/"
34
+ Documentation = "https://apiauto.space/en/docs/"
35
+ Repository = "https://github.com/apiauto-space/copart-api"
36
+ Issues = "https://github.com/apiauto-space/copart-api/issues"
37
+ Changelog = "https://github.com/apiauto-space/copart-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/copart_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/copart_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
+ """Copart API client for Python: Copart auction lots (USA) with VIN, damage and sale date as JSON.
2
+
3
+ A thin layer over the apiauto.space client (``apiauto``) with the market preset::
4
+
5
+ import copart_api
6
+
7
+ with copart_api.Client() as client: # the key comes from APIAUTO_KEY
8
+ for car in client.cars(brand="Toyota", 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 Copart.
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 CopartRaw, 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
+ "CopartRaw",
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,342 @@
1
+ """Copart clients: the apiauto clients with the market preset to ``us``."""
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["us"] = "us"
30
+ """The apiauto.space market of Copart."""
31
+ SOURCE: Literal["copart"] = "copart"
32
+ """The ``source`` of every record this package returns."""
33
+ SHARED_MARKET = True
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 Copart listing number: ``68055056`` -> ``copart:68055056``.
39
+
40
+ An id that already has the ``copart:`` 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 Copart 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
+ """Copart 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 copart_api.Client() as client:
86
+ page = client.cars(brand="Toyota", 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 Copart cars: ``GET /cars?market=us``.
125
+
126
+ Takes the filters of :meth:`apiauto.Client.cars`: ``brand``, ``model``, ``year_min``,
127
+ ``year_max``, ``price_min``, ``price_max`` (in USD), ``mileage_max``, ``sort``,
128
+ ``limit``, ``cursor`` and more. Every car returned counts against the quota.
129
+ """
130
+ page = self.core.cars(MARKET, **filters)
131
+ # The us market mixes Copart and IAAI: keep this source's lots. The page can hold
132
+ # fewer than `limit` cars, and `count` is unknown for one source.
133
+ return {
134
+ "items": [car for car in page["items"] if _ours(car)],
135
+ "next_cursor": page["next_cursor"],
136
+ "count": None,
137
+ }
138
+
139
+ def iter_cars(self, *, max_items: int | None = None, **filters: Unpack[CarFilters]) -> Iterator[Car]:
140
+ """Every Copart car matching the filters, following ``next_cursor``.
141
+
142
+ Args:
143
+ max_items: Stop after this many cars.
144
+ **filters: The filters of :meth:`cars`; ``limit`` sets the page size.
145
+ """
146
+ if max_items is not None and max_items <= 0:
147
+ return
148
+ taken = 0
149
+ for car in self.core.iter_cars(MARKET, **filters):
150
+ if _ours(car):
151
+ yield car
152
+ taken += 1
153
+ if max_items is not None and taken >= max_items:
154
+ return
155
+
156
+ def car(self, listing: str | int) -> Car:
157
+ """One car by listing number (``68055056``) or record id (``copart:68055056``).
158
+
159
+ Cars taken off sale stay available for 14 days with ``is_active=False``.
160
+ """
161
+ return self.core.car(car_id(listing))
162
+
163
+ def changes(
164
+ self,
165
+ since: datetime | str,
166
+ *,
167
+ type: ChangeType | Sequence[ChangeType] | None = None, # noqa: A002
168
+ min_pct: float | Decimal | None = None,
169
+ limit: int | None = None,
170
+ cursor: str | None = None,
171
+ ) -> ChangesPage:
172
+ """One page of the change feed: new cars, cars taken off sale and price changes since a moment."""
173
+ page = self.core.changes(MARKET, since, type=type, min_pct=min_pct, limit=limit, cursor=cursor)
174
+ return {
175
+ "items": [change for change in page["items"] if _our_change(change)],
176
+ "next_cursor": page["next_cursor"],
177
+ }
178
+
179
+ def iter_changes(
180
+ self,
181
+ since: datetime | str,
182
+ *,
183
+ type: ChangeType | Sequence[ChangeType] | None = None, # noqa: A002
184
+ min_pct: float | Decimal | None = None,
185
+ limit: int | None = None,
186
+ max_items: int | None = None,
187
+ ) -> Iterator[Change]:
188
+ """Every event of the change feed since a moment, following ``next_cursor``."""
189
+ if max_items is not None and max_items <= 0:
190
+ return
191
+ taken = 0
192
+ for change in self.core.iter_changes(MARKET, since, type=type, min_pct=min_pct, limit=limit):
193
+ if _our_change(change):
194
+ yield change
195
+ taken += 1
196
+ if max_items is not None and taken >= max_items:
197
+ return
198
+
199
+ def brands(self) -> list[ReferenceItem]:
200
+ """Makes of the us market with car counts, most frequent first. Free."""
201
+ return self.core.brands(MARKET)
202
+
203
+ def models(self, brand: str) -> list[ReferenceItem]:
204
+ """Models of a make with car counts. Free."""
205
+ return self.core.models(MARKET, brand)
206
+
207
+ def dictionaries(self) -> Dictionaries:
208
+ """Canonical values of ``fuel``, ``transmission``, ``body_type`` and more. Free."""
209
+ return self.core.dictionaries()
210
+
211
+ def status(self) -> Market:
212
+ """The us market: plan access, data age and the number of active cars. Free."""
213
+ return _own_market(self.core.markets())
214
+
215
+ def usage(self) -> Usage:
216
+ """The plan, its term and how much of the quota is spent. Free."""
217
+ return self.core.usage()
218
+
219
+ def live(
220
+ self,
221
+ *,
222
+ make: str | None = None,
223
+ model: str | None = None,
224
+ year_min: int | None = None,
225
+ year_max: int | None = None,
226
+ price_max: int | None = None,
227
+ page: int | None = None,
228
+ ) -> list[Car]:
229
+ """Search lots live at the auction data provider: ``GET /us/live``, this source's lots only.
230
+
231
+ For lots that are not in the catalog copy yet. Pro and Max plans; it spends a
232
+ separate monthly counter. ``price_max`` is in US dollars, ``page`` is 1-100.
233
+ """
234
+ lots = self.core.us_live(
235
+ make=make, model=model, year_min=year_min, year_max=year_max, price_max=price_max, page=page
236
+ )
237
+ return [car for car in lots if _ours(car)]
238
+
239
+
240
+ class AsyncClient:
241
+ """Copart client of the apiauto.space API for asyncio; the methods of :class:`Client`.
242
+
243
+ ::
244
+
245
+ async with copart_api.AsyncClient() as client:
246
+ page = await client.cars(brand="Toyota", limit=20)
247
+ """
248
+
249
+ def __init__(
250
+ self,
251
+ api_key: str | None = None,
252
+ *,
253
+ base_url: str | None = None,
254
+ timeout: float = 30.0,
255
+ max_retries: int = 2,
256
+ http_client: httpx.AsyncClient | None = None,
257
+ ) -> None:
258
+ self.core = apiauto.AsyncClient(
259
+ api_key,
260
+ timeout=timeout,
261
+ max_retries=max_retries,
262
+ http_client=http_client,
263
+ **_core_options(base_url),
264
+ )
265
+
266
+ async def close(self) -> None:
267
+ """Close the HTTP connections (unless the ``http_client`` was yours)."""
268
+ await self.core.close()
269
+
270
+ async def __aenter__(self) -> Self:
271
+ return self
272
+
273
+ async def __aexit__(
274
+ self,
275
+ exc_type: type[BaseException] | None,
276
+ exc: BaseException | None,
277
+ tb: TracebackType | None,
278
+ ) -> None:
279
+ await self.close()
280
+
281
+ async def cars(self, **filters: Unpack[CarFilters]) -> CarsPage:
282
+ """One page of Copart cars; see :meth:`Client.cars`."""
283
+ page = await self.core.cars(MARKET, **filters)
284
+ return {
285
+ "items": [car for car in page["items"] if _ours(car)],
286
+ "next_cursor": page["next_cursor"],
287
+ "count": None,
288
+ }
289
+
290
+ async def iter_cars(
291
+ self, *, max_items: int | None = None, **filters: Unpack[CarFilters]
292
+ ) -> AsyncIterator[Car]:
293
+ """Every Copart car matching the filters; see :meth:`Client.iter_cars`."""
294
+ if max_items is not None and max_items <= 0:
295
+ return
296
+ taken = 0
297
+ async for car in self.core.iter_cars(MARKET, **filters):
298
+ if _ours(car):
299
+ yield car
300
+ taken += 1
301
+ if max_items is not None and taken >= max_items:
302
+ return
303
+
304
+ async def car(self, listing: str | int) -> Car:
305
+ """One car by listing number or record id; see :meth:`Client.car`."""
306
+ return await self.core.car(car_id(listing))
307
+
308
+ async def changes(
309
+ self,
310
+ since: datetime | str,
311
+ *,
312
+ type: ChangeType | Sequence[ChangeType] | None = None, # noqa: A002
313
+ min_pct: float | Decimal | None = None,
314
+ limit: int | None = None,
315
+ cursor: str | None = None,
316
+ ) -> ChangesPage:
317
+ """One page of the change feed; see :meth:`Client.changes`."""
318
+ page = await self.core.changes(MARKET, since, type=type, min_pct=min_pct, limit=limit, cursor=cursor)
319
+ return {
320
+ "items": [change for change in page["items"] if _our_change(change)],
321
+ "next_cursor": page["next_cursor"],
322
+ }
323
+
324
+ async def brands(self) -> list[ReferenceItem]:
325
+ """Makes of the us market with car counts. Free."""
326
+ return await self.core.brands(MARKET)
327
+
328
+ async def models(self, brand: str) -> list[ReferenceItem]:
329
+ """Models of a make with car counts. Free."""
330
+ return await self.core.models(MARKET, brand)
331
+
332
+ async def dictionaries(self) -> Dictionaries:
333
+ """Canonical values of ``fuel``, ``transmission``, ``body_type`` and more. Free."""
334
+ return await self.core.dictionaries()
335
+
336
+ async def status(self) -> Market:
337
+ """The us market: plan access, data age and the number of active cars. Free."""
338
+ return _own_market(await self.core.markets())
339
+
340
+ async def usage(self) -> Usage:
341
+ """The plan, its term and how much of the quota is spent. Free."""
342
+ return await self.core.usage()
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
File without changes
@@ -0,0 +1,77 @@
1
+ """Types of the Copart-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 Copart has are in ``car["raw"]``. :func:`raw` returns them typed::
5
+
6
+ from copart_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 Any, TypedDict, cast
15
+
16
+ from apiauto import Car
17
+
18
+ __all__ = ["CopartRaw", "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 CopartRaw(TypedDict, total=False):
32
+ """Copart-only fields of a record (``car["raw"]``). Keys can be missing; read them with ``.get``."""
33
+
34
+ lot_number: str | None
35
+ """The lot number at the auction."""
36
+ status: int | None
37
+ sale_date: str | None
38
+ """Auction date and time, ISO 8601."""
39
+ bid: int | float | None
40
+ """The current bid, US dollars."""
41
+ buy_now: int | float | None
42
+ """Buy-now price, US dollars."""
43
+ final_bid: int | float | None
44
+ """The final bid of a sold lot, US dollars."""
45
+ damage_main: str | None
46
+ """Primary damage, a canonical value such as ``front`` or ``rear``."""
47
+ damage_second: str | None
48
+ title_doc: str | None
49
+ """Title document type, a canonical value such as ``clean`` or ``salvage``."""
50
+ keys_available: bool | None
51
+ airbags: Any
52
+ odometer_mi: int | None
53
+ """Odometer in miles as the auction shows it (``mileage_km`` is converted)."""
54
+ odometer_status: Any
55
+ condition: Any
56
+ grade_iaai: Any
57
+ estimate_repair_price: int | float | None
58
+ pre_accident_price: int | float | None
59
+ clean_wholesale_price: int | float | None
60
+ seller: str | None
61
+ seller_type: Any
62
+ location_branch: str | None
63
+ """The auction yard, for example ``Nashville (TN)``."""
64
+ latitude: float | None
65
+ longitude: float | None
66
+ video_url: str | None
67
+ drive: str | None
68
+ """``fwd``, ``rwd``, ``awd`` or ``4wd``."""
69
+ cylinders: int | None
70
+ source_values: dict[str, str | None]
71
+ """The auction's own spellings of make, model, fuel, damage and more."""
72
+ fx: FxQuote | None
73
+
74
+
75
+ def raw(car: Car) -> CopartRaw:
76
+ """The Copart-only fields of a record, typed as :class:`CopartRaw`."""
77
+ return cast(CopartRaw, car.get("raw") or {})
@@ -0,0 +1,185 @@
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 copart_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": "us", "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]) -> copart_api.Client:
41
+ http = httpx.Client(transport=httpx.MockTransport(recorder))
42
+ return copart_api.Client(KEY, http_client=http, max_retries=0)
43
+
44
+
45
+ def test_constants() -> None:
46
+ assert copart_api.MARKET == "us"
47
+ assert copart_api.SOURCE == "copart"
48
+ assert copart_api.SHARED_MARKET is True
49
+ assert copart_api.__version__ == "0.1.0"
50
+
51
+
52
+ def test_cars_presets_the_market() -> None:
53
+ rec = Recorder(page(["copart:1", "copart:2"], count=2))
54
+ with client(rec) as api:
55
+ result = api.cars(brand="Toyota", year_min=2020, limit=2)
56
+ assert [c["id"] for c in result["items"]] == ["copart:1", "copart:2"]
57
+ assert rec.requests[0].url.path == "/v1/cars"
58
+ assert rec.params() == {"market": "us", "brand": "Toyota", "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
+ ("68055056", "/v1/cars/copart:68055056"),
71
+ (68055056, "/v1/cars/copart:68055056"),
72
+ ("copart:68055056", "/v1/cars/copart:68055056"),
73
+ ],
74
+ )
75
+ def test_car_accepts_number_or_id(listing: str | int, path: str) -> None:
76
+ rec = Recorder(car("copart:68055056"))
77
+ with client(rec) as api:
78
+ assert api.car(listing)["id"] == "copart:68055056"
79
+ assert rec.requests[0].url.path == path
80
+
81
+
82
+ @pytest.mark.parametrize("bad", ["", " ", "other:123", "copart:"])
83
+ def test_car_id_rejects_foreign_ids(bad: str) -> None:
84
+ with pytest.raises(ValueError, match=r"\S"):
85
+ copart_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": "Toyota", "count": 5}], [{"name": "Camry", "count": 2}], markets)
97
+ with client(rec) as api:
98
+ assert api.brands()[0]["name"] == "Toyota"
99
+ assert rec.params(0) == {"market": "us"}
100
+ assert api.models("Toyota")[0]["count"] == 2
101
+ assert rec.params(1) == {"market": "us", "brand": "Toyota"}
102
+ assert api.status()["market"] == "us"
103
+
104
+
105
+ def test_raw_is_typed_view() -> None:
106
+ record: Any = {"id": "copart:68055056", "raw": {"source_values": {"brand": "x"}}}
107
+ assert copart_api.raw(record).get("source_values") == {"brand": "x"}
108
+ assert copart_api.raw({"id": "copart:68055056"}) == {} # type: ignore[typeddict-item]
109
+
110
+
111
+ def test_cars_keeps_only_this_auction() -> None:
112
+ rec = Recorder(page(["copart:1", "other:2", "copart:3"], next_cursor="c2", count=3))
113
+ with client(rec) as api:
114
+ result = api.cars(limit=3)
115
+ assert [c["id"] for c in result["items"]] == ["copart:1", "copart:3"]
116
+ assert result["next_cursor"] == "c2"
117
+ assert result["count"] is None
118
+
119
+
120
+ def test_iter_cars_collects_max_items_across_pages() -> None:
121
+ rec = Recorder(
122
+ page(["other:1", "copart:2"], next_cursor="c2"),
123
+ page(["other:3", "other:4"], next_cursor="c3"),
124
+ page(["copart:5", "copart:6"], next_cursor="c4"),
125
+ )
126
+ with client(rec) as api:
127
+ ids = [c["id"] for c in api.iter_cars(max_items=2, limit=2)]
128
+ assert ids == ["copart:2", "copart:5"]
129
+ assert len(rec.requests) == 3
130
+ assert all(r.url.params["market"] == "us" for r in rec.requests)
131
+
132
+
133
+ def test_iter_cars_zero_items_makes_no_request() -> None:
134
+ rec = Recorder()
135
+ with client(rec) as api:
136
+ assert list(api.iter_cars(max_items=0)) == []
137
+ assert rec.requests == []
138
+
139
+
140
+ def test_changes_keep_only_this_auction() -> None:
141
+ feed = {
142
+ "items": [
143
+ {"id": 1, "car_id": "copart:1", "type": "added"},
144
+ {"id": 2, "car_id": "other:2", "type": "added"},
145
+ ],
146
+ "next_cursor": None,
147
+ }
148
+ rec = Recorder(feed, feed)
149
+ with client(rec) as api:
150
+ assert [c["car_id"] for c in api.changes("2026-11-01T00:00:00Z")["items"]] == ["copart:1"]
151
+ assert [c["id"] for c in api.iter_changes("2026-11-01T00:00:00Z", max_items=5)] == [1]
152
+
153
+
154
+ def test_live_keeps_only_this_auction() -> None:
155
+ rec = Recorder([car("copart:1"), car("other:2")])
156
+ with client(rec) as api:
157
+ lots = api.live(make="Toyota", page=1)
158
+ assert [c["id"] for c in lots] == ["copart:1"]
159
+ assert rec.requests[0].url.path == "/v1/us/live"
160
+ assert rec.params() == {"make": "Toyota", "page": "1"}
161
+
162
+
163
+ def test_async_client() -> None:
164
+ rec = Recorder(page(["copart:1"]), car("copart:68055056"), page(["copart:1"]))
165
+
166
+ async def run() -> list[str]:
167
+ http = httpx.AsyncClient(transport=httpx.MockTransport(rec))
168
+ async with copart_api.AsyncClient(KEY, http_client=http, max_retries=0) as api:
169
+ first = await api.cars(limit=1)
170
+ one = await api.car("68055056")
171
+ more = [c["id"] async for c in api.iter_cars(max_items=1, limit=1)]
172
+ await http.aclose()
173
+ return [first["items"][0]["id"], one["id"], *more]
174
+
175
+ assert asyncio.run(run()) == ["copart:1", "copart:68055056", "copart:1"]
176
+ assert all(r.url.params.get("market") in (None, "us") for r in rec.requests)
177
+
178
+
179
+ def test_errors_are_the_apiauto_ones() -> None:
180
+ def handler(request: httpx.Request) -> httpx.Response:
181
+ body = {"error": {"code": "not_found", "message": "no such car"}}
182
+ return httpx.Response(404, content=json.dumps(body), headers={"content-type": "application/json"})
183
+
184
+ with client(handler) as api, pytest.raises(copart_api.NotFoundError):
185
+ 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 copart_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 copart_api.Client() as api:
16
+ assert api.status()["market"] == "us"
17
+ cars = list(api.iter_cars(max_items=3, limit=10))
18
+ assert cars, "the catalog returned no Copart cars"
19
+ assert all(car["source"] == "copart" for car in cars)
20
+ one = api.car(cars[0]["source_id"])
21
+ assert one["id"] == cars[0]["id"]
22
+ assert isinstance(copart_api.raw(one), dict)