Python¶
Tested with Python 3.10+ and requests 2.31+.
Minimal client¶
```python
cnw.py¶
import os from typing import Any, Mapping import requests
ENDPOINT = os.environ.get("CNW_ENDPOINT", "https://api.cutweaver.io") API_KEY = os.environ.get("CNW_API_KEY")
class CnwError(Exception): def init(self, code: str, message: str, status: int) -> None: super().init(message) self.code = code self.status = status
def solve(payload: Mapping[str, Any], timeout: float = 10.0) -> dict: headers = {"Content-Type": "application/json"} if API_KEY: headers["X-API-Key"] = API_KEY
res = requests.post(f"{ENDPOINT}/v1/solve", json=payload, headers=headers, timeout=timeout)
data = res.json()
if not data.get("ok"):
err = data.get("error", {})
raise CnwError(err.get("code", "unknown"), err.get("message", "Unknown error"), res.status_code)
return data["result"]
```
Usage¶
```python from cnw import solve
result = solve({ "sheets": [{"width": 3210, "height": 2250}], "pieces": [ {"width": 800, "height": 600, "quantity": 4}, {"width": 1200, "height": 900, "quantity": 2}, ], "params": {"kerf": 4}, "strategy": "greedy", })
print(f"Utilization: {result['metrics']['totalUtilization'] * 100:.1f}%") for sheet in result["sheets"]: print(f"Sheet {sheet['index']}: {len(sheet['placements'])} pieces") ```
Retry with backoff¶
```python import time from cnw import solve, CnwError
def solve_with_retry(payload, max_attempts: int = 3): for attempt in range(1, max_attempts + 1): try: return solve(payload) except CnwError as e: if e.status != 429 and e.status < 500: raise if attempt == max_attempts: raise time.sleep(2 ** attempt * 0.5) ```