printit-sdk 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Make It Universal LLC
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,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: printit-sdk
3
+ Version: 1.0.0
4
+ Summary: Official Python SDK for the Print It on-demand 3D manufacturing API
5
+ License: MIT
6
+ Project-URL: Homepage, https://printit.dev/developers
7
+ Project-URL: Documentation, https://printit.dev/docs
8
+ Keywords: 3d-printing,manufacturing,api,sdk
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: httpx>=0.27
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest; extra == "dev"
21
+ Requires-Dist: pytest-asyncio; extra == "dev"
22
+ Requires-Dist: respx; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # printit-sdk — Python client for the Print It API
26
+
27
+ ```bash
28
+ pip install printit-sdk
29
+ ```
30
+
31
+ Published by Make It Universal LLC, the company behind Print It. Get a key at
32
+ [printit.dev/developers](https://printit.dev/developers) — start with a **test** key
33
+ (`sk_pi_test_…`): real quotes, nothing charged, no workshop.
34
+
35
+ ## Quick start (test mode — nothing is charged)
36
+
37
+ ```python
38
+ from printit import PrintIt
39
+
40
+ client = PrintIt(api_key="sk_pi_test_...") # a test key: real quotes, no money, no workshop
41
+
42
+ ship_to = {"name": "Ada Lovelace", "street": "1 Main St", "city": "New York",
43
+ "region": "NY", "postal_code": "10001", "country_code": "US"}
44
+
45
+ # 1. Quote — the price, the contract and the delivery promise
46
+ quote = client.quote("bracket.stl", material="petg_pro", quantity=2, ship_to=ship_to)
47
+ # (an address is enough — pass delivery_lat/delivery_lon only if you have no address)
48
+ print(quote["pricing"]["total_display"], quote["shipping"]["basis"], quote["delivery_promise"])
49
+ print(quote["spec"]) # exactly what will be made
50
+
51
+ # 2. Route — pays from your wallet (live) and dispatches; the quoted address is used
52
+ client.order(quote["order_id"])
53
+
54
+ # 3. Test mode: walk it through production; your webhook gets every step
55
+ for _ in range(4):
56
+ print(client.advance(quote["order_id"])["status"]) # printing → … → delivered
57
+
58
+ # 4. Read it back
59
+ status = client.status(quote["order_id"])
60
+ print(status["status"], status["delivery"]["promised_by"], status["tracking"])
61
+ ```
62
+
63
+ Switch to a live key (`sk_pi_…`) and the same code charges your wallet and the job goes to
64
+ the network. `client.livemode` tells you which one you hold.
65
+
66
+ ## A parts list is one order
67
+
68
+ ```python
69
+ ids = [client.quote(f, material="petg_pro", ship_to=ship_to)["order_id"] for f in kit_files]
70
+ out = client.order_parts(ids) # one address, the fewest boxes, all or nothing
71
+ print(out["shipments_planned"], out["shipping_saved_usd_cents"])
72
+ ```
73
+
74
+ ## Cancel
75
+
76
+ ```python
77
+ client.cancel(order_id, reason="ordered_by_mistake") # before a workshop accepts it
78
+ ```
79
+
80
+ A quote is withdrawn; a paid order's price returns to your wallet at once. Safe to retry.
81
+
82
+ ## Async
83
+
84
+ ```python
85
+ async with PrintIt(api_key="sk_pi_...") as client:
86
+ quote = await client.quote_async("model.stl", delivery_lat=40.7, delivery_lon=-74.0)
87
+ await client.order_async(quote["order_id"], ship_to=ship_to)
88
+ ```
89
+
90
+ ## Idempotent retries
91
+
92
+ ```python
93
+ import uuid
94
+ idem = str(uuid.uuid4()) # generate once, reuse on every retry of the same call
95
+ client.order(order_id, idempotency_key=idem)
96
+ ```
97
+
98
+ ## Errors
99
+
100
+ ```python
101
+ from printit import PrintItError
102
+
103
+ try:
104
+ client.order(order_id)
105
+ except PrintItError as e:
106
+ if e.code == "insufficient_balance":
107
+ ... # top up the wallet
108
+ elif e.code == "requote_required":
109
+ ... # quote again with this ship_to
110
+ else:
111
+ print(e.status_code, e.detail)
112
+ ```
113
+
114
+ `PRINTIT_API_KEY` in the environment is read when no `api_key` is passed.
@@ -0,0 +1,90 @@
1
+ # printit-sdk — Python client for the Print It API
2
+
3
+ ```bash
4
+ pip install printit-sdk
5
+ ```
6
+
7
+ Published by Make It Universal LLC, the company behind Print It. Get a key at
8
+ [printit.dev/developers](https://printit.dev/developers) — start with a **test** key
9
+ (`sk_pi_test_…`): real quotes, nothing charged, no workshop.
10
+
11
+ ## Quick start (test mode — nothing is charged)
12
+
13
+ ```python
14
+ from printit import PrintIt
15
+
16
+ client = PrintIt(api_key="sk_pi_test_...") # a test key: real quotes, no money, no workshop
17
+
18
+ ship_to = {"name": "Ada Lovelace", "street": "1 Main St", "city": "New York",
19
+ "region": "NY", "postal_code": "10001", "country_code": "US"}
20
+
21
+ # 1. Quote — the price, the contract and the delivery promise
22
+ quote = client.quote("bracket.stl", material="petg_pro", quantity=2, ship_to=ship_to)
23
+ # (an address is enough — pass delivery_lat/delivery_lon only if you have no address)
24
+ print(quote["pricing"]["total_display"], quote["shipping"]["basis"], quote["delivery_promise"])
25
+ print(quote["spec"]) # exactly what will be made
26
+
27
+ # 2. Route — pays from your wallet (live) and dispatches; the quoted address is used
28
+ client.order(quote["order_id"])
29
+
30
+ # 3. Test mode: walk it through production; your webhook gets every step
31
+ for _ in range(4):
32
+ print(client.advance(quote["order_id"])["status"]) # printing → … → delivered
33
+
34
+ # 4. Read it back
35
+ status = client.status(quote["order_id"])
36
+ print(status["status"], status["delivery"]["promised_by"], status["tracking"])
37
+ ```
38
+
39
+ Switch to a live key (`sk_pi_…`) and the same code charges your wallet and the job goes to
40
+ the network. `client.livemode` tells you which one you hold.
41
+
42
+ ## A parts list is one order
43
+
44
+ ```python
45
+ ids = [client.quote(f, material="petg_pro", ship_to=ship_to)["order_id"] for f in kit_files]
46
+ out = client.order_parts(ids) # one address, the fewest boxes, all or nothing
47
+ print(out["shipments_planned"], out["shipping_saved_usd_cents"])
48
+ ```
49
+
50
+ ## Cancel
51
+
52
+ ```python
53
+ client.cancel(order_id, reason="ordered_by_mistake") # before a workshop accepts it
54
+ ```
55
+
56
+ A quote is withdrawn; a paid order's price returns to your wallet at once. Safe to retry.
57
+
58
+ ## Async
59
+
60
+ ```python
61
+ async with PrintIt(api_key="sk_pi_...") as client:
62
+ quote = await client.quote_async("model.stl", delivery_lat=40.7, delivery_lon=-74.0)
63
+ await client.order_async(quote["order_id"], ship_to=ship_to)
64
+ ```
65
+
66
+ ## Idempotent retries
67
+
68
+ ```python
69
+ import uuid
70
+ idem = str(uuid.uuid4()) # generate once, reuse on every retry of the same call
71
+ client.order(order_id, idempotency_key=idem)
72
+ ```
73
+
74
+ ## Errors
75
+
76
+ ```python
77
+ from printit import PrintItError
78
+
79
+ try:
80
+ client.order(order_id)
81
+ except PrintItError as e:
82
+ if e.code == "insufficient_balance":
83
+ ... # top up the wallet
84
+ elif e.code == "requote_required":
85
+ ... # quote again with this ship_to
86
+ else:
87
+ print(e.status_code, e.detail)
88
+ ```
89
+
90
+ `PRINTIT_API_KEY` in the environment is read when no `api_key` is passed.
@@ -0,0 +1,19 @@
1
+ """
2
+ Print It Python SDK
3
+ ===================
4
+ Not yet on PyPI — install from the repository (packages/sdk/python).
5
+
6
+ Quick start:
7
+ from printit import PrintIt
8
+
9
+ client = PrintIt(api_key="sk_pi_test_...") # test mode: nothing is charged
10
+ quote = client.quote("bracket.stl", delivery_lat=40.71, delivery_lon=-74.0, ship_to={...})
11
+ order = client.order(quote["order_id"])
12
+ status = client.status(order["order_id"])
13
+ """
14
+
15
+ from .client import PrintIt, PrintItError, QuoteResult, OrderResult, StatusResult
16
+ from .supply import PrintItSupply
17
+
18
+ __version__ = "1.0.0"
19
+ __all__ = ["PrintIt", "PrintItError", "PrintItSupply", "QuoteResult", "OrderResult", "StatusResult"]
@@ -0,0 +1,297 @@
1
+ """
2
+ PrintIt client — synchronous and async interfaces.
3
+
4
+ Sync:
5
+ client = PrintIt(api_key="sk_pi_test_...") # a TEST key: nothing is charged
6
+ quote = client.quote("model.stl", delivery_lat=40.71, delivery_lon=-74.0,
7
+ ship_to={"name": "Ada", "street": "1 Main St", "city": "New York",
8
+ "postal_code": "10001", "country_code": "US"})
9
+ client.order(quote["order_id"]) # the quoted address is used
10
+ client.advance(quote["order_id"]) # test mode: next production step
11
+
12
+ Async:
13
+ async with PrintIt(api_key="sk_pi_...") as client:
14
+ quote = await client.quote_async("model.stl", delivery_lat=40.71, delivery_lon=-74.0)
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ from pathlib import Path
21
+ from typing import Any, Optional
22
+
23
+ import httpx
24
+
25
+ from .types import OrderResult, QuoteResult, StatusResult
26
+
27
+ TEST_KEY_PREFIX = "sk_pi_test_"
28
+
29
+
30
+ class PrintItError(Exception):
31
+ """Raised for API errors with status >= 400. Branch on ``code`` (e.g.
32
+ ``insufficient_balance``, ``requote_required``, ``cancel_not_allowed``)."""
33
+
34
+ def __init__(self, status_code: int, detail: Any) -> None:
35
+ self.status_code = status_code
36
+ self.detail = detail
37
+ self.code = detail.get("error") if isinstance(detail, dict) else None
38
+ super().__init__(f"PrintIt API error {status_code}: {detail}")
39
+
40
+
41
+ _DEFAULT_BASE_URL = "https://api.printit.dev"
42
+
43
+
44
+ def _quote_form(*, delivery_lat, delivery_lon, material, color, quantity, infill_percent,
45
+ layer_height_mm, supports, wall_shells, is_urgent, currency, ship_to) -> dict:
46
+ data = {
47
+ "material": material,
48
+ "color": color,
49
+ "quantity": str(quantity),
50
+ "infill_percent": str(infill_percent),
51
+ "layer_height_mm": str(layer_height_mm),
52
+ "supports": supports,
53
+ "wall_shells": str(wall_shells),
54
+ "is_urgent": str(is_urgent).lower(),
55
+ "currency": currency,
56
+ }
57
+ if delivery_lat is not None and delivery_lon is not None:
58
+ data["delivery_lat"], data["delivery_lon"] = str(delivery_lat), str(delivery_lon)
59
+ elif not ship_to:
60
+ raise ValueError("Pass ship_to (the delivery address) or delivery_lat + delivery_lon.")
61
+ if ship_to:
62
+ data["ship_to"] = json.dumps(ship_to)
63
+ return data
64
+
65
+
66
+ class PrintIt:
67
+ """
68
+ Print It SDK client.
69
+
70
+ Parameters
71
+ ----------
72
+ api_key : str
73
+ ``sk_pi_test_…`` (test mode: real quotes, nothing charged, no workshop) or
74
+ ``sk_pi_…`` (live). Falls back to the PRINTIT_API_KEY env var.
75
+ base_url : str
76
+ Override for self-hosted instances. Defaults to https://api.printit.dev.
77
+ timeout : float
78
+ HTTP timeout in seconds (default 120 — uploads can be slow).
79
+ """
80
+
81
+ def __init__(
82
+ self,
83
+ api_key: Optional[str] = None,
84
+ base_url: str = _DEFAULT_BASE_URL,
85
+ timeout: float = 120.0,
86
+ ) -> None:
87
+ self._api_key = api_key or os.environ.get("PRINTIT_API_KEY", "")
88
+ if not self._api_key:
89
+ raise ValueError(
90
+ "api_key is required. Pass it directly or set the PRINTIT_API_KEY env var."
91
+ )
92
+ self._base_url = base_url.rstrip("/")
93
+ self._timeout = timeout
94
+ self._headers = {"X-PrintIt-Key": self._api_key}
95
+
96
+ @property
97
+ def livemode(self) -> bool:
98
+ """False for a test key — its orders never charge money or reach a workshop."""
99
+ return not self._api_key.startswith(TEST_KEY_PREFIX)
100
+
101
+ def _h(self, idempotency_key: Optional[str]) -> dict:
102
+ return {**self._headers, **({"X-Idempotency-Key": idempotency_key} if idempotency_key else {})}
103
+
104
+ def _url(self, path: str) -> str:
105
+ return f"{self._base_url}{path}"
106
+
107
+ # ── Sync API ──────────────────────────────────────────────────────────────
108
+
109
+ def quote(
110
+ self,
111
+ file_path: str | Path,
112
+ *,
113
+ delivery_lat: Optional[float] = None,
114
+ delivery_lon: Optional[float] = None,
115
+ material: str = "pla_standard",
116
+ color: str = "White",
117
+ quantity: int = 1,
118
+ infill_percent: int = 20,
119
+ layer_height_mm: float = 0.2,
120
+ supports: str = "standard",
121
+ wall_shells: int = 2,
122
+ is_urgent: bool = False,
123
+ currency: str = "USD",
124
+ ship_to: Optional[dict] = None,
125
+ idempotency_key: Optional[str] = None,
126
+ ) -> QuoteResult:
127
+ """Upload a 3D file and receive a binding quote. With ``ship_to`` the shipping line
128
+ is priced to that street (``shipping.basis == "exact"``), the coordinates are optional
129
+ (the address is placed for you) and ``order`` needs no address; without it, pass the
130
+ coordinates and shipping is an estimate."""
131
+ path = Path(file_path)
132
+ if not path.exists():
133
+ raise FileNotFoundError(f"File not found: {file_path}")
134
+ data = _quote_form(delivery_lat=delivery_lat, delivery_lon=delivery_lon, material=material,
135
+ color=color, quantity=quantity, infill_percent=infill_percent,
136
+ layer_height_mm=layer_height_mm, supports=supports,
137
+ wall_shells=wall_shells, is_urgent=is_urgent, currency=currency,
138
+ ship_to=ship_to)
139
+ with httpx.Client(timeout=self._timeout) as client, path.open("rb") as f:
140
+ response = client.post(self._url("/v1/quote"), headers=self._h(idempotency_key),
141
+ files={"file": (path.name, f, "application/octet-stream")},
142
+ data=data)
143
+ return _json(response)
144
+
145
+ def order(
146
+ self,
147
+ order_id: str,
148
+ *,
149
+ ship_to: Optional[dict] = None,
150
+ idempotency_key: Optional[str] = None,
151
+ ) -> OrderResult:
152
+ """Pay from your wallet and dispatch a quoted order (nothing is charged in test mode).
153
+
154
+ ``ship_to`` — ``{"name", "street", "city", "postal_code", "country_code", "region"?,
155
+ "phone"?, "instructions"?}``. Optional when the quote carried one (it may repeat it,
156
+ never move it — ``requote_required``); required otherwise."""
157
+ with httpx.Client(timeout=self._timeout) as client:
158
+ response = client.post(self._url(f"/v1/route/{order_id}"), headers=self._h(idempotency_key),
159
+ json={"ship_to": ship_to} if ship_to else {})
160
+ return _json(response)
161
+
162
+ def order_parts(self, order_ids: list[str], *, ship_to: Optional[dict] = None,
163
+ accept_new_totals: bool = False,
164
+ idempotency_key: Optional[str] = None) -> dict:
165
+ """Route a parts list (2–50 quoted parts) as ONE order: one address, the fewest boxes,
166
+ one charge per part — all or nothing. If packing them together would raise a part's
167
+ price, nothing is charged and ``PrintItError.code == "requote_required"`` carries the
168
+ new figures; pass ``accept_new_totals=True`` to route at them."""
169
+ body: dict = {"order_ids": list(order_ids)}
170
+ if ship_to:
171
+ body["ship_to"] = ship_to
172
+ if accept_new_totals:
173
+ body["accept_new_totals"] = True
174
+ with httpx.Client(timeout=self._timeout) as client:
175
+ response = client.post(self._url("/v1/route"), headers=self._h(idempotency_key), json=body)
176
+ return _json(response)
177
+
178
+ def status(self, order_id: str) -> StatusResult:
179
+ """One order: status, the contract, the promised delivery date and the courier."""
180
+ with httpx.Client(timeout=self._timeout) as client:
181
+ response = client.get(self._url(f"/v1/orders/{order_id}"), headers=self._headers)
182
+ return _json(response)
183
+
184
+ def cancel(self, order_id: str, *, reason: Optional[str] = None,
185
+ idempotency_key: Optional[str] = None) -> dict:
186
+ """Cancel before a workshop accepts it; a paid order's price returns to your wallet.
187
+ Safe to retry. A started order raises ``PrintItError`` with code ``cancel_not_allowed``."""
188
+ with httpx.Client(timeout=self._timeout) as client:
189
+ response = client.post(self._url(f"/v1/orders/{order_id}/cancel"),
190
+ headers=self._h(idempotency_key),
191
+ json={"reason": reason} if reason else {})
192
+ return _json(response)
193
+
194
+ def advance(self, order_id: str, to: Optional[str] = None) -> StatusResult:
195
+ """TEST MODE ONLY — move a test order to its next state (or ``to``), exactly as a
196
+ real one would travel; your webhook receives each step with ``livemode: false``."""
197
+ with httpx.Client(timeout=self._timeout) as client:
198
+ response = client.post(self._url(f"/v1/test/orders/{order_id}/advance"),
199
+ headers=self._headers, json={"to": to} if to else {})
200
+ return _json(response)
201
+
202
+ def materials(self, technology: Optional[str] = None) -> list[dict]:
203
+ """List available materials. Optionally filter by technology (FDM, SLA)."""
204
+ params = {"technology": technology.upper()} if technology else {}
205
+ with httpx.Client(timeout=self._timeout) as client:
206
+ response = client.get(self._url("/v1/materials"), headers=self._headers, params=params)
207
+ return _json(response)
208
+
209
+ def webhook_status(self, order_id: str) -> dict:
210
+ """Get outbound webhook delivery status for an order (DLQ inspection)."""
211
+ with httpx.Client(timeout=self._timeout) as client:
212
+ response = client.get(self._url(f"/v1/webhooks/status/{order_id}"), headers=self._headers)
213
+ return _json(response)
214
+
215
+ # ── Async API ─────────────────────────────────────────────────────────────
216
+
217
+ async def quote_async(
218
+ self,
219
+ file_path: str | Path,
220
+ *,
221
+ delivery_lat: Optional[float] = None,
222
+ delivery_lon: Optional[float] = None,
223
+ material: str = "pla_standard",
224
+ color: str = "White",
225
+ quantity: int = 1,
226
+ infill_percent: int = 20,
227
+ layer_height_mm: float = 0.2,
228
+ supports: str = "standard",
229
+ wall_shells: int = 2,
230
+ is_urgent: bool = False,
231
+ currency: str = "USD",
232
+ ship_to: Optional[dict] = None,
233
+ idempotency_key: Optional[str] = None,
234
+ ) -> QuoteResult:
235
+ path = Path(file_path)
236
+ if not path.exists():
237
+ raise FileNotFoundError(f"File not found: {file_path}")
238
+ data = _quote_form(delivery_lat=delivery_lat, delivery_lon=delivery_lon, material=material,
239
+ color=color, quantity=quantity, infill_percent=infill_percent,
240
+ layer_height_mm=layer_height_mm, supports=supports,
241
+ wall_shells=wall_shells, is_urgent=is_urgent, currency=currency,
242
+ ship_to=ship_to)
243
+ async with httpx.AsyncClient(timeout=self._timeout) as client:
244
+ with path.open("rb") as f:
245
+ response = await client.post(
246
+ self._url("/v1/quote"), headers=self._h(idempotency_key),
247
+ files={"file": (path.name, f, "application/octet-stream")}, data=data)
248
+ return _json(response)
249
+
250
+ async def order_async(
251
+ self,
252
+ order_id: str,
253
+ *,
254
+ ship_to: Optional[dict] = None,
255
+ idempotency_key: Optional[str] = None,
256
+ ) -> OrderResult:
257
+ """Async ``order`` — see ``order`` for ``ship_to``."""
258
+ async with httpx.AsyncClient(timeout=self._timeout) as client:
259
+ response = await client.post(self._url(f"/v1/route/{order_id}"),
260
+ headers=self._h(idempotency_key),
261
+ json={"ship_to": ship_to} if ship_to else {})
262
+ return _json(response)
263
+
264
+ async def status_async(self, order_id: str) -> StatusResult:
265
+ async with httpx.AsyncClient(timeout=self._timeout) as client:
266
+ response = await client.get(self._url(f"/v1/orders/{order_id}"), headers=self._headers)
267
+ return _json(response)
268
+
269
+ async def cancel_async(self, order_id: str, *, reason: Optional[str] = None,
270
+ idempotency_key: Optional[str] = None) -> dict:
271
+ async with httpx.AsyncClient(timeout=self._timeout) as client:
272
+ response = await client.post(self._url(f"/v1/orders/{order_id}/cancel"),
273
+ headers=self._h(idempotency_key),
274
+ json={"reason": reason} if reason else {})
275
+ return _json(response)
276
+
277
+ # ── Context manager ───────────────────────────────────────────────────────
278
+
279
+ async def __aenter__(self) -> "PrintIt":
280
+ return self
281
+
282
+ async def __aexit__(self, *_: Any) -> None:
283
+ pass
284
+
285
+
286
+ def _raise_for_status(response: httpx.Response) -> None:
287
+ if response.status_code >= 400:
288
+ try:
289
+ detail = response.json().get("detail", response.text)
290
+ except Exception:
291
+ detail = response.text
292
+ raise PrintItError(response.status_code, detail)
293
+
294
+
295
+ def _json(response: httpx.Response) -> Any:
296
+ _raise_for_status(response)
297
+ return response.json()
@@ -0,0 +1,81 @@
1
+ """
2
+ The Supply API — for a workshop's own software (a print farm's MES, a bureau's scheduler).
3
+
4
+ from printit import PrintItSupply
5
+
6
+ farm = PrintItSupply(api_key="sk_pi_supply_...") # minted by the maker at printit.dev/developers
7
+ for offer in farm.offers(): # the platform's order — keep it
8
+ if fits_my_queue(offer):
9
+ farm.claim(offer["order_id"]) # accepting is starting
10
+ break
11
+ farm.download(order_id, "part.stl")
12
+ farm.printed(order_id, actual_weight_grams=41.5)
13
+ farm.ship(order_id) # the platform picks the courier
14
+
15
+ A workshop key acts as the maker on these endpoints only: it never places orders and is never
16
+ a login. One job per claim — there is no bulk claim.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ from pathlib import Path
22
+ from typing import Any, Optional
23
+
24
+ import httpx
25
+
26
+ from .client import _DEFAULT_BASE_URL, _json
27
+
28
+ SUPPLY_KEY_PREFIX = "sk_pi_supply_"
29
+
30
+
31
+ class PrintItSupply:
32
+ def __init__(self, api_key: Optional[str] = None, base_url: str = _DEFAULT_BASE_URL,
33
+ timeout: float = 120.0) -> None:
34
+ self._api_key = api_key or os.environ.get("PRINTIT_SUPPLY_KEY", "")
35
+ if not self._api_key.startswith(SUPPLY_KEY_PREFIX):
36
+ raise ValueError("A workshop key (sk_pi_supply_…) is required — pass it or set PRINTIT_SUPPLY_KEY.")
37
+ self._base_url = base_url.rstrip("/")
38
+ self._timeout = timeout
39
+ self._headers = {"X-PrintIt-Key": self._api_key}
40
+
41
+ def _call(self, method: str, path: str, json: Optional[dict] = None) -> Any:
42
+ with httpx.Client(timeout=self._timeout) as client:
43
+ response = client.request(method, f"{self._base_url}/v1/supply{path}",
44
+ headers=self._headers, json=json)
45
+ return _json(response)
46
+
47
+ def offers(self) -> Any:
48
+ """Jobs offered to this workshop, ranked by the platform."""
49
+ return self._call("GET", "/offers")
50
+
51
+ def offer(self, order_id: str) -> Any:
52
+ """One job: the buyer's paid spec, the part's size, the deadlines."""
53
+ return self._call("GET", f"/offers/{order_id}")
54
+
55
+ def claim(self, order_id: str) -> Any:
56
+ """Claim one job. Raises PrintItError 409 if another workshop took it first."""
57
+ return self._call("POST", f"/offers/{order_id}/claim")
58
+
59
+ def jobs(self) -> Any:
60
+ """This workshop's jobs in progress."""
61
+ return self._call("GET", "/jobs")
62
+
63
+ def download(self, order_id: str, dest: str | Path) -> Path:
64
+ """Save the part's file to `dest`."""
65
+ with httpx.Client(timeout=self._timeout) as client:
66
+ response = client.get(f"{self._base_url}/v1/supply/jobs/{order_id}/file", headers=self._headers)
67
+ if response.status_code >= 400:
68
+ _json(response) # raises PrintItError with the API's detail
69
+ path = Path(dest)
70
+ path.write_bytes(response.content)
71
+ return path
72
+
73
+ def printed(self, order_id: str, *, actual_weight_grams: Optional[float] = None) -> Any:
74
+ """Report the part printed and packed."""
75
+ body = {"actual_weight_grams": actual_weight_grams} if actual_weight_grams is not None else {}
76
+ return self._call("POST", f"/jobs/{order_id}/printed", json=body)
77
+
78
+ def ship(self, order_id: str, *, shipping_option_id: Optional[str] = None) -> Any:
79
+ """Book the courier (None = the platform's recommended option)."""
80
+ body = {"shipping_option_id": shipping_option_id} if shipping_option_id else {}
81
+ return self._call("POST", f"/jobs/{order_id}/ship", json=body)
@@ -0,0 +1,53 @@
1
+ """The shapes the Print It API answers with (TypedDicts — keys as the API sends them)."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Optional, TypedDict
5
+
6
+
7
+ class QuoteResult(TypedDict, total=False):
8
+ order_id: str
9
+ livemode: bool
10
+ status: str
11
+ geometry: dict
12
+ dfm: list
13
+ spec: dict # the contract: exactly what will be made
14
+ estimate: dict
15
+ pricing: dict # {currency, total_usd_cents, total_usd, total_display, markup_pct}
16
+ shipping: dict # {basis: "exact" | "estimate", ship_to}
17
+ delivery_promise: Optional[dict] # {days, hours, basis} or None (no honest promise)
18
+ coverage: dict
19
+ next_step: str
20
+ expires_at: str
21
+
22
+
23
+ class OrderResult(TypedDict, total=False):
24
+ order_id: str
25
+ livemode: bool
26
+ status: str
27
+ coverage_type: str
28
+ charged_usd_cents: int
29
+ next_step: str
30
+ billing: str
31
+ dispatch_tier: str
32
+
33
+
34
+ class StatusResult(TypedDict, total=False):
35
+ # No maker identity by design: /v1 is an order-solicitation API — Print It is
36
+ # accountable for the part, and naming the shop that printed it is how a
37
+ # customer learns to reorder around us. See the file-upload-engine
38
+ # `app/api/routers/v1.py` module header.
39
+ order_id: str
40
+ livemode: bool
41
+ status: str
42
+ message: str
43
+ accepted: bool
44
+ cancellable: bool
45
+ spec: dict
46
+ delivery: dict # {promised_by, promise}
47
+ courier: Optional[dict]
48
+ tracking: Optional[dict]
49
+ total_usd_cents: int
50
+ total_usd: float
51
+ currency: str
52
+ created_at: str
53
+ updated_at: str
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: printit-sdk
3
+ Version: 1.0.0
4
+ Summary: Official Python SDK for the Print It on-demand 3D manufacturing API
5
+ License: MIT
6
+ Project-URL: Homepage, https://printit.dev/developers
7
+ Project-URL: Documentation, https://printit.dev/docs
8
+ Keywords: 3d-printing,manufacturing,api,sdk
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: httpx>=0.27
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest; extra == "dev"
21
+ Requires-Dist: pytest-asyncio; extra == "dev"
22
+ Requires-Dist: respx; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # printit-sdk — Python client for the Print It API
26
+
27
+ ```bash
28
+ pip install printit-sdk
29
+ ```
30
+
31
+ Published by Make It Universal LLC, the company behind Print It. Get a key at
32
+ [printit.dev/developers](https://printit.dev/developers) — start with a **test** key
33
+ (`sk_pi_test_…`): real quotes, nothing charged, no workshop.
34
+
35
+ ## Quick start (test mode — nothing is charged)
36
+
37
+ ```python
38
+ from printit import PrintIt
39
+
40
+ client = PrintIt(api_key="sk_pi_test_...") # a test key: real quotes, no money, no workshop
41
+
42
+ ship_to = {"name": "Ada Lovelace", "street": "1 Main St", "city": "New York",
43
+ "region": "NY", "postal_code": "10001", "country_code": "US"}
44
+
45
+ # 1. Quote — the price, the contract and the delivery promise
46
+ quote = client.quote("bracket.stl", material="petg_pro", quantity=2, ship_to=ship_to)
47
+ # (an address is enough — pass delivery_lat/delivery_lon only if you have no address)
48
+ print(quote["pricing"]["total_display"], quote["shipping"]["basis"], quote["delivery_promise"])
49
+ print(quote["spec"]) # exactly what will be made
50
+
51
+ # 2. Route — pays from your wallet (live) and dispatches; the quoted address is used
52
+ client.order(quote["order_id"])
53
+
54
+ # 3. Test mode: walk it through production; your webhook gets every step
55
+ for _ in range(4):
56
+ print(client.advance(quote["order_id"])["status"]) # printing → … → delivered
57
+
58
+ # 4. Read it back
59
+ status = client.status(quote["order_id"])
60
+ print(status["status"], status["delivery"]["promised_by"], status["tracking"])
61
+ ```
62
+
63
+ Switch to a live key (`sk_pi_…`) and the same code charges your wallet and the job goes to
64
+ the network. `client.livemode` tells you which one you hold.
65
+
66
+ ## A parts list is one order
67
+
68
+ ```python
69
+ ids = [client.quote(f, material="petg_pro", ship_to=ship_to)["order_id"] for f in kit_files]
70
+ out = client.order_parts(ids) # one address, the fewest boxes, all or nothing
71
+ print(out["shipments_planned"], out["shipping_saved_usd_cents"])
72
+ ```
73
+
74
+ ## Cancel
75
+
76
+ ```python
77
+ client.cancel(order_id, reason="ordered_by_mistake") # before a workshop accepts it
78
+ ```
79
+
80
+ A quote is withdrawn; a paid order's price returns to your wallet at once. Safe to retry.
81
+
82
+ ## Async
83
+
84
+ ```python
85
+ async with PrintIt(api_key="sk_pi_...") as client:
86
+ quote = await client.quote_async("model.stl", delivery_lat=40.7, delivery_lon=-74.0)
87
+ await client.order_async(quote["order_id"], ship_to=ship_to)
88
+ ```
89
+
90
+ ## Idempotent retries
91
+
92
+ ```python
93
+ import uuid
94
+ idem = str(uuid.uuid4()) # generate once, reuse on every retry of the same call
95
+ client.order(order_id, idempotency_key=idem)
96
+ ```
97
+
98
+ ## Errors
99
+
100
+ ```python
101
+ from printit import PrintItError
102
+
103
+ try:
104
+ client.order(order_id)
105
+ except PrintItError as e:
106
+ if e.code == "insufficient_balance":
107
+ ... # top up the wallet
108
+ elif e.code == "requote_required":
109
+ ... # quote again with this ship_to
110
+ else:
111
+ print(e.status_code, e.detail)
112
+ ```
113
+
114
+ `PRINTIT_API_KEY` in the environment is read when no `api_key` is passed.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ printit/__init__.py
5
+ printit/client.py
6
+ printit/supply.py
7
+ printit/types.py
8
+ printit_sdk.egg-info/PKG-INFO
9
+ printit_sdk.egg-info/SOURCES.txt
10
+ printit_sdk.egg-info/dependency_links.txt
11
+ printit_sdk.egg-info/requires.txt
12
+ printit_sdk.egg-info/top_level.txt
13
+ tests/test_client.py
14
+ tests/test_supply.py
@@ -0,0 +1,6 @@
1
+ httpx>=0.27
2
+
3
+ [dev]
4
+ pytest
5
+ pytest-asyncio
6
+ respx
@@ -0,0 +1 @@
1
+ printit
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "printit-sdk"
7
+ version = "1.0.0"
8
+ description = "Official Python SDK for the Print It on-demand 3D manufacturing API"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.10"
12
+ keywords = ["3d-printing", "manufacturing", "api", "sdk"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Intended Audience :: Developers",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ ]
21
+ dependencies = [
22
+ "httpx>=0.27",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ dev = ["pytest", "pytest-asyncio", "respx"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://printit.dev/developers"
30
+ Documentation = "https://printit.dev/docs"
31
+
32
+ [tool.setuptools.packages.find]
33
+ where = ["."]
34
+ include = ["printit*"]
35
+
36
+ [tool.pytest.ini_options]
37
+ asyncio_mode = "auto"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,334 @@
1
+ """
2
+ printit-sdk — unit tests
3
+ Run: pytest tests/ -v
4
+ Requires: pytest, pytest-asyncio, respx (installed via pip install printit-sdk[dev])
5
+ """
6
+ import uuid
7
+ import pytest
8
+ import respx
9
+ import httpx
10
+ from pathlib import Path
11
+
12
+ from printit import PrintIt, PrintItError
13
+
14
+
15
+ # ── Fixtures ──────────────────────────────────────────────────────────────────
16
+
17
+ API_KEY = "sk_pi_test_key"
18
+ BASE = "https://api.printit.dev"
19
+
20
+
21
+ @pytest.fixture
22
+ def client():
23
+ return PrintIt(api_key=API_KEY)
24
+
25
+
26
+ @pytest.fixture
27
+ def stl_file(tmp_path: Path) -> Path:
28
+ p = tmp_path / "model.stl"
29
+ p.write_bytes(b"solid test\nendsolid test\n") # minimal valid STL text
30
+ return p
31
+
32
+
33
+ # ── Constructor ───────────────────────────────────────────────────────────────
34
+
35
+ def test_raises_without_api_key(monkeypatch):
36
+ monkeypatch.delenv("PRINTIT_API_KEY", raising=False)
37
+ with pytest.raises(ValueError, match="api_key is required"):
38
+ PrintIt()
39
+
40
+
41
+ def test_reads_api_key_from_env(monkeypatch):
42
+ monkeypatch.setenv("PRINTIT_API_KEY", "sk_pi_env_key")
43
+ c = PrintIt()
44
+ assert c._api_key == "sk_pi_env_key"
45
+
46
+
47
+ def test_custom_base_url():
48
+ c = PrintIt(api_key=API_KEY, base_url="https://self-hosted.example.com/")
49
+ assert c._base_url == "https://self-hosted.example.com" # trailing slash stripped
50
+
51
+
52
+ # ── quote() ───────────────────────────────────────────────────────────────────
53
+
54
+ QUOTE_RESPONSE = {
55
+ "order_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
56
+ "status": "quoted",
57
+ "geometry": {"volume_cm3": 42.5, "shadow_area_cm2": 18.3, "height_mm": 45.0, "is_oversized": False},
58
+ "estimate": {"weight_g": 51.0, "material": "pla_standard", "quantity": 1, "infill_percent": 20},
59
+ "pricing": {"total_amount": 8.50, "currency": "USD"},
60
+ "coverage": {"coverage_type": "local"},
61
+ "next_step": "POST /v1/route/...",
62
+ "expires_at": "2026-01-01T12:15:00",
63
+ }
64
+
65
+
66
+ @respx.mock
67
+ def test_quote_success(client: PrintIt, stl_file: Path):
68
+ respx.post(f"{BASE}/v1/quote").mock(return_value=httpx.Response(200, json=QUOTE_RESPONSE))
69
+ result = client.quote(stl_file, delivery_lat=-33.45, delivery_lon=-70.64)
70
+ assert result["order_id"] == QUOTE_RESPONSE["order_id"]
71
+ assert result["status"] == "quoted"
72
+
73
+
74
+ @respx.mock
75
+ def test_quote_raises_on_4xx(client: PrintIt, stl_file: Path):
76
+ respx.post(f"{BASE}/v1/quote").mock(return_value=httpx.Response(422, json={"detail": "no_coverage"}))
77
+ with pytest.raises(PrintItError) as exc_info:
78
+ client.quote(stl_file, delivery_lat=0.0, delivery_lon=0.0)
79
+ assert exc_info.value.status_code == 422
80
+ assert "no_coverage" in str(exc_info.value.detail)
81
+
82
+
83
+ def test_quote_raises_file_not_found(client: PrintIt):
84
+ with pytest.raises(FileNotFoundError):
85
+ client.quote("/nonexistent/model.stl", delivery_lat=0.0, delivery_lon=0.0)
86
+
87
+
88
+ @respx.mock
89
+ def test_quote_sends_idempotency_key(client: PrintIt, stl_file: Path):
90
+ idem_key = str(uuid.uuid4())
91
+ route = respx.post(f"{BASE}/v1/quote").mock(return_value=httpx.Response(200, json=QUOTE_RESPONSE))
92
+ client.quote(stl_file, delivery_lat=-33.45, delivery_lon=-70.64, idempotency_key=idem_key)
93
+ assert route.called
94
+ assert route.calls[0].request.headers.get("X-Idempotency-Key") == idem_key
95
+
96
+
97
+ # ── order() ───────────────────────────────────────────────────────────────────
98
+
99
+ ORDER_RESPONSE = {
100
+ "order_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
101
+ "status": "paid",
102
+ "coverage_type": "local",
103
+ "next_step": "Poll GET /v1/status/...",
104
+ "billing": "Charged from your Print It wallet balance.",
105
+ "dispatch_tier": "free",
106
+ }
107
+
108
+
109
+ @respx.mock
110
+ def test_order_success(client: PrintIt):
111
+ order_id = ORDER_RESPONSE["order_id"]
112
+ respx.post(f"{BASE}/v1/route/{order_id}").mock(return_value=httpx.Response(200, json=ORDER_RESPONSE))
113
+ result = client.order(order_id)
114
+ assert result["order_id"] == order_id
115
+ assert result["status"] == "paid"
116
+ # /v1 is an order-solicitation API: no response may name the maker.
117
+ assert "assigned_maker" not in result
118
+ assert result["coverage_type"] == "local"
119
+
120
+
121
+ @respx.mock
122
+ def test_order_raises_on_404(client: PrintIt):
123
+ respx.post(f"{BASE}/v1/route/bad-id").mock(return_value=httpx.Response(404, json={"detail": "order_not_found"}))
124
+ with pytest.raises(PrintItError) as exc_info:
125
+ client.order("bad-id")
126
+ assert exc_info.value.status_code == 404
127
+
128
+
129
+ @respx.mock
130
+ def test_order_sends_the_delivery_address(client: PrintIt):
131
+ """/v1/route refuses (and charges nothing) without `ship_to` — the SDK must carry it."""
132
+ import json
133
+ order_id = ORDER_RESPONSE["order_id"]
134
+ route = respx.post(f"{BASE}/v1/route/{order_id}").mock(return_value=httpx.Response(200, json=ORDER_RESPONSE))
135
+ ship_to = {"name": "Ada Buyer", "street": "1 Main St", "city": "New York", "country_code": "US"}
136
+ client.order(order_id, ship_to=ship_to)
137
+ assert json.loads(route.calls.last.request.content) == {"ship_to": ship_to}
138
+
139
+
140
+ @respx.mock
141
+ def test_order_sends_idempotency_key(client: PrintIt):
142
+ idem_key = str(uuid.uuid4())
143
+ order_id = ORDER_RESPONSE["order_id"]
144
+ route = respx.post(f"{BASE}/v1/route/{order_id}").mock(return_value=httpx.Response(200, json=ORDER_RESPONSE))
145
+ client.order(order_id, idempotency_key=idem_key)
146
+ assert route.calls[0].request.headers.get("X-Idempotency-Key") == idem_key
147
+
148
+
149
+ # ── status() ──────────────────────────────────────────────────────────────────
150
+
151
+ STATUS_RESPONSE = {
152
+ "order_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
153
+ "status": "printing",
154
+ "message": "Your part is being printed.",
155
+ "accepted": True,
156
+ "tracking": {},
157
+ "total_usd_cents": 8500,
158
+ "currency": "USD",
159
+ "updated_at": "2026-01-01T12:00:00",
160
+ }
161
+
162
+
163
+ @respx.mock
164
+ def test_status_success(client: PrintIt):
165
+ order_id = STATUS_RESPONSE["order_id"]
166
+ respx.get(f"{BASE}/v1/orders/{order_id}").mock(return_value=httpx.Response(200, json=STATUS_RESPONSE))
167
+ result = client.status(order_id)
168
+ assert result["status"] == "printing"
169
+ # B2B orders are USD-canonical — /v1/status always reports USD.
170
+ assert result["currency"] == "USD"
171
+ # /v1 is an order-solicitation API: the maker is never named.
172
+ assert "assigned_maker" not in result
173
+ assert result["accepted"] is True
174
+
175
+
176
+ # ── materials() ───────────────────────────────────────────────────────────────
177
+
178
+ MATERIALS_RESPONSE = [
179
+ {"id": "pla_standard", "name": "PLA Standard", "technology": "FDM", "price_usd_per_g": 0.025, "best_for": "Prototypes"},
180
+ {"id": "resin_standard", "name": "Resin Standard", "technology": "SLA", "price_usd_per_g": 0.045, "best_for": "Detail"},
181
+ ]
182
+
183
+
184
+ @respx.mock
185
+ def test_materials_no_filter(client: PrintIt):
186
+ respx.get(f"{BASE}/v1/materials").mock(return_value=httpx.Response(200, json=MATERIALS_RESPONSE))
187
+ result = client.materials()
188
+ assert len(result) == 2
189
+ assert result[0]["id"] == "pla_standard"
190
+
191
+
192
+ @respx.mock
193
+ def test_materials_technology_filter(client: PrintIt):
194
+ fdm_only = [MATERIALS_RESPONSE[0]]
195
+ respx.get(f"{BASE}/v1/materials").mock(return_value=httpx.Response(200, json=fdm_only))
196
+ result = client.materials(technology="FDM")
197
+ assert len(result) == 1
198
+ assert result[0]["technology"] == "FDM"
199
+
200
+
201
+ # ── webhook_status() ──────────────────────────────────────────────────────────
202
+
203
+ WEBHOOK_RESPONSE = [
204
+ {
205
+ "id": "evt-1", "event_type": "order.delivered", "status": "delivered",
206
+ "attempt_count": 1, "last_attempt_at": None, "last_error": None,
207
+ "delivered_at": "2026-01-01T12:00:00", "next_retry_at": None,
208
+ }
209
+ ]
210
+
211
+
212
+ @respx.mock
213
+ def test_webhook_status(client: PrintIt):
214
+ order_id = "order-123"
215
+ respx.get(f"{BASE}/v1/webhooks/status/{order_id}").mock(return_value=httpx.Response(200, json=WEBHOOK_RESPONSE))
216
+ result = client.webhook_status(order_id)
217
+ assert len(result) == 1
218
+ assert result[0]["event_type"] == "order.delivered"
219
+
220
+
221
+ # ── async variants ────────────────────────────────────────────────────────────
222
+
223
+ @pytest.mark.asyncio
224
+ @respx.mock
225
+ async def test_order_async(client: PrintIt):
226
+ order_id = ORDER_RESPONSE["order_id"]
227
+ respx.post(f"{BASE}/v1/route/{order_id}").mock(return_value=httpx.Response(200, json=ORDER_RESPONSE))
228
+ result = await client.order_async(order_id)
229
+ assert result["status"] == "paid"
230
+
231
+
232
+ @pytest.mark.asyncio
233
+ @respx.mock
234
+ async def test_status_async(client: PrintIt):
235
+ order_id = STATUS_RESPONSE["order_id"]
236
+ respx.get(f"{BASE}/v1/orders/{order_id}").mock(return_value=httpx.Response(200, json=STATUS_RESPONSE))
237
+ result = await client.status_async(order_id)
238
+ assert result["status"] == "printing"
239
+
240
+
241
+ # ── PrintItError ──────────────────────────────────────────────────────────────
242
+
243
+ def test_print_it_error_attrs():
244
+ err = PrintItError(status_code=422, detail={"error": "no_coverage"})
245
+ assert err.status_code == 422
246
+ assert err.detail == {"error": "no_coverage"}
247
+ assert "422" in str(err)
248
+ assert isinstance(err, Exception)
249
+
250
+
251
+ # ── 2026-11-20: the contract, cancel, test mode ──────────────────────────────
252
+
253
+ @respx.mock
254
+ def test_quote_sends_the_address_and_every_spec_term(client: PrintIt, stl_file: Path):
255
+ import json as _json
256
+ route = respx.post(f"{BASE}/v1/quote").mock(return_value=httpx.Response(200, json=QUOTE_RESPONSE))
257
+ ship_to = {"name": "Ada", "street": "1 Main St", "city": "New York",
258
+ "postal_code": "10001", "country_code": "US"}
259
+ client.quote(stl_file, delivery_lat=40.7, delivery_lon=-74.0, layer_height_mm=0.12,
260
+ supports="tree", wall_shells=4, ship_to=ship_to)
261
+ body = route.calls.last.request.content.decode()
262
+ for field, value in (("layer_height_mm", "0.12"), ("supports", "tree"), ("wall_shells", "4")):
263
+ assert f'name="{field}"\r\n\r\n{value}' in body
264
+ assert _json.dumps(ship_to) in body
265
+
266
+
267
+ @respx.mock
268
+ def test_quote_without_an_address_sends_none(client: PrintIt, stl_file: Path):
269
+ route = respx.post(f"{BASE}/v1/quote").mock(return_value=httpx.Response(200, json=QUOTE_RESPONSE))
270
+ client.quote(stl_file, delivery_lat=40.7, delivery_lon=-74.0)
271
+ assert 'name="ship_to"' not in route.calls.last.request.content.decode()
272
+
273
+
274
+ @respx.mock
275
+ def test_cancel_posts_the_reason_and_the_idempotency_key(client: PrintIt):
276
+ order_id = str(uuid.uuid4())
277
+ route = respx.post(f"{BASE}/v1/orders/{order_id}/cancel").mock(return_value=httpx.Response(
278
+ 200, json={"order_id": order_id, "status": "cancelled", "livemode": True,
279
+ "refund": {"to": "wallet", "amount_usd_cents": 1265}}))
280
+ out = client.cancel(order_id, reason="price", idempotency_key="k-1")
281
+ assert out["refund"]["amount_usd_cents"] == 1265
282
+ assert route.calls.last.request.headers["X-Idempotency-Key"] == "k-1"
283
+ assert b'"reason"' in route.calls.last.request.content
284
+
285
+
286
+ @respx.mock
287
+ def test_errors_carry_the_machine_code(client: PrintIt):
288
+ order_id = str(uuid.uuid4())
289
+ respx.post(f"{BASE}/v1/orders/{order_id}/cancel").mock(return_value=httpx.Response(
290
+ 409, json={"detail": {"error": "cancel_not_allowed", "message": "started"}}))
291
+ with pytest.raises(PrintItError) as exc:
292
+ client.cancel(order_id)
293
+ assert exc.value.code == "cancel_not_allowed" and exc.value.status_code == 409
294
+
295
+
296
+ @respx.mock
297
+ def test_advance_moves_a_test_order(client: PrintIt):
298
+ order_id = str(uuid.uuid4())
299
+ route = respx.post(f"{BASE}/v1/test/orders/{order_id}/advance").mock(
300
+ return_value=httpx.Response(200, json={"order_id": order_id, "status": "printing", "livemode": False}))
301
+ assert client.advance(order_id)["status"] == "printing"
302
+ assert route.calls.last.request.content == b"{}"
303
+ client.advance(order_id, to="delivered")
304
+ assert b'"delivered"' in route.calls.last.request.content
305
+
306
+
307
+ def test_livemode_follows_the_key():
308
+ assert PrintIt(api_key="sk_pi_test_abc").livemode is False
309
+ assert PrintIt(api_key="sk_pi_0123abcd").livemode is True
310
+
311
+
312
+ @respx.mock
313
+ def test_an_address_alone_is_enough_to_quote(client: PrintIt, stl_file: Path):
314
+ route = respx.post(f"{BASE}/v1/quote").mock(return_value=httpx.Response(200, json=QUOTE_RESPONSE))
315
+ client.quote(stl_file, ship_to={"name": "Ada", "street": "1 Main St", "city": "New York",
316
+ "postal_code": "10001", "country_code": "US"})
317
+ body = route.calls.last.request.content.decode()
318
+ assert 'name="delivery_lat"' not in body and 'name="ship_to"' in body
319
+
320
+
321
+ def test_a_quote_needs_an_address_or_a_point(client: PrintIt, stl_file: Path):
322
+ with pytest.raises(ValueError, match="ship_to"):
323
+ client.quote(stl_file)
324
+
325
+
326
+ @respx.mock
327
+ def test_order_parts_routes_a_kit_in_one_call(client: PrintIt):
328
+ route = respx.post(f"{BASE}/v1/route").mock(return_value=httpx.Response(
329
+ 200, json={"status": "paid", "order_ids": ["a", "b"], "shipments_planned": 1}))
330
+ out = client.order_parts(["a", "b"], accept_new_totals=True, idempotency_key="k")
331
+ assert out["shipments_planned"] == 1
332
+ import json as _json
333
+ assert _json.loads(route.calls.last.request.content) == {"order_ids": ["a", "b"], "accept_new_totals": True}
334
+ assert route.calls.last.request.headers["X-Idempotency-Key"] == "k"
@@ -0,0 +1,42 @@
1
+ """printit.PrintItSupply — the workshop client."""
2
+ import httpx
3
+ import pytest
4
+ import respx
5
+
6
+ from printit import PrintItError, PrintItSupply
7
+
8
+ KEY = "sk_pi_supply_" + "a" * 64
9
+ BASE = "https://api.printit.dev/v1/supply"
10
+
11
+
12
+ def test_it_refuses_a_key_that_is_not_a_workshop_key():
13
+ with pytest.raises(ValueError, match="sk_pi_supply_"):
14
+ PrintItSupply(api_key="sk_pi_test_abc")
15
+
16
+
17
+ @respx.mock
18
+ def test_offers_claim_printed_ship_reach_their_endpoints():
19
+ farm = PrintItSupply(api_key=KEY)
20
+ respx.get(f"{BASE}/offers").mock(return_value=httpx.Response(200, json=[{"order_id": "o1"}]))
21
+ claim = respx.post(f"{BASE}/offers/o1/claim").mock(return_value=httpx.Response(200, json={"status": "printing"}))
22
+ printed = respx.post(f"{BASE}/jobs/o1/printed").mock(return_value=httpx.Response(200, json={}))
23
+ ship = respx.post(f"{BASE}/jobs/o1/ship").mock(return_value=httpx.Response(200, json={"dispatch_ok": True}))
24
+ assert farm.offers() == [{"order_id": "o1"}]
25
+ assert farm.claim("o1") == {"status": "printing"}
26
+ farm.printed("o1", actual_weight_grams=41.5)
27
+ farm.ship("o1")
28
+ assert claim.calls.last.request.headers["X-PrintIt-Key"] == KEY
29
+ assert printed.calls.last.request.content == b'{"actual_weight_grams":41.5}'
30
+ assert ship.calls.last.request.content == b"{}"
31
+
32
+
33
+ @respx.mock
34
+ def test_a_lost_race_is_a_409_with_its_code(tmp_path):
35
+ farm = PrintItSupply(api_key=KEY)
36
+ respx.post(f"{BASE}/offers/o2/claim").mock(return_value=httpx.Response(
37
+ 409, json={"detail": {"error": "already_taken", "message": "Another workshop took it."}}))
38
+ with pytest.raises(PrintItError) as exc:
39
+ farm.claim("o2")
40
+ assert exc.value.status_code == 409 and exc.value.code == "already_taken"
41
+ respx.get(f"{BASE}/jobs/o3/file").mock(return_value=httpx.Response(200, content=b"solid x"))
42
+ assert farm.download("o3", tmp_path / "x.stl").read_bytes() == b"solid x"