Make an HTTP request to the registry. Returns parsed JSON or raises.
(method, path, body=None, token=None)
| 114 | # ── HTTP helpers ──────────────────────────────────────────────────── |
| 115 | |
| 116 | def api_request(method, path, body=None, token=None): |
| 117 | """Make an HTTP request to the registry. Returns parsed JSON or raises.""" |
| 118 | url = f"{get_registry_url()}{path}" |
| 119 | headers = {"Accept": "application/json", "User-Agent": f"lapsh/{__version__}"} |
| 120 | if token: |
| 121 | headers["Authorization"] = f"Bearer {token}" |
| 122 | |
| 123 | data = None |
| 124 | if body is not None: |
| 125 | headers["Content-Type"] = "application/json" |
| 126 | data = json.dumps(body).encode() |
| 127 | |
| 128 | req = urllib.request.Request(url, data=data, headers=headers, method=method) |
| 129 | try: |
| 130 | with urllib.request.urlopen(req) as resp: |
| 131 | return json.loads(resp.read().decode()) |
| 132 | except urllib.error.HTTPError as e: |
| 133 | body_text = e.read().decode() if e.fp else "" |
| 134 | try: |
| 135 | err = json.loads(body_text) |
| 136 | except (json.JSONDecodeError, ValueError): |
| 137 | err = {"error": body_text or f"HTTP {e.code}"} |
| 138 | msg = err.get("error", err.get("message", body_text)) |
| 139 | if e.code == 401: |
| 140 | raise SystemExit(f"Authentication failed: {msg}\n Run 'lapsh login' to re-authenticate.") |
| 141 | if e.code == 403: |
| 142 | raise SystemExit(f"Permission denied: {msg}") |
| 143 | raise SystemExit(f"Error: {msg}") |
| 144 | |
| 145 | |
| 146 | # ── SSE stream ────────────────────────────────────────────────────── |
no test coverage detected