-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.py
More file actions
249 lines (210 loc) · 8.01 KB
/
Copy pathhttp.py
File metadata and controls
249 lines (210 loc) · 8.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
"""
HTTP client for Stack0 API
Handles authentication, request/response formatting, and error handling
"""
from __future__ import annotations
from typing import Any
import httpx
from .._exceptions import (
APIError,
AuthenticationError,
NetworkError,
NotFoundError,
PermissionError,
RateLimitError,
ValidationError,
)
DEFAULT_BASE_URL = "https://api.stack0.dev/v1"
DEFAULT_TIMEOUT = 30.0
class HTTPClient:
"""Synchronous HTTP client for Stack0 API"""
def __init__(
self,
api_key: str,
base_url: str = DEFAULT_BASE_URL,
timeout: float = DEFAULT_TIMEOUT,
) -> None:
self.api_key = api_key
self.base_url = base_url.rstrip("/")
self._client = httpx.Client(
base_url=self.base_url,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
timeout=timeout,
)
def _handle_response(self, response: httpx.Response) -> Any:
"""Handle API response and raise appropriate exceptions"""
if response.is_success:
if response.status_code == 204:
return None
try:
return response.json()
except Exception:
return None
# Handle error responses
try:
error_body = response.json()
except Exception:
error_body = {"message": response.text or response.reason_phrase}
message = error_body.get("message", f"HTTP {response.status_code}")
code = error_body.get("code")
status_code = response.status_code
if status_code == 401:
raise AuthenticationError(message, status_code, code, error_body)
elif status_code == 403:
raise PermissionError(message, status_code, code, error_body)
elif status_code == 404:
raise NotFoundError(message, status_code, code, error_body)
elif status_code == 429:
retry_after = response.headers.get("Retry-After")
raise RateLimitError(
message,
status_code,
code,
error_body,
int(retry_after) if retry_after else None,
)
elif status_code == 400:
raise ValidationError(message, status_code, code, error_body)
else:
raise APIError(message, status_code, code, error_body)
def _make_request(
self,
method: str,
path: str,
body: dict[str, Any] | None = None,
) -> Any:
"""Make an HTTP request"""
try:
if body is not None:
response = self._client.request(method, path, json=body)
else:
response = self._client.request(method, path)
return self._handle_response(response)
except httpx.TimeoutException as e:
raise NetworkError(f"Request timed out: {e}") from e
except httpx.RequestError as e:
raise NetworkError(f"Network error: {e}") from e
def get(self, path: str) -> Any:
"""Make a GET request"""
return self._make_request("GET", path)
def post(self, path: str, body: dict[str, Any] | None = None) -> Any:
"""Make a POST request"""
return self._make_request("POST", path, body or {})
def put(self, path: str, body: dict[str, Any]) -> Any:
"""Make a PUT request"""
return self._make_request("PUT", path, body)
def patch(self, path: str, body: dict[str, Any]) -> Any:
"""Make a PATCH request"""
return self._make_request("PATCH", path, body)
def delete(self, path: str) -> Any:
"""Make a DELETE request"""
return self._make_request("DELETE", path)
def delete_with_body(self, path: str, body: dict[str, Any]) -> Any:
"""Make a DELETE request with a body"""
return self._make_request("DELETE", path, body)
def close(self) -> None:
"""Close the HTTP client"""
self._client.close()
def __enter__(self) -> "HTTPClient":
return self
def __exit__(self, *args: Any) -> None:
self.close()
class AsyncHTTPClient:
"""Asynchronous HTTP client for Stack0 API"""
def __init__(
self,
api_key: str,
base_url: str = DEFAULT_BASE_URL,
timeout: float = DEFAULT_TIMEOUT,
) -> None:
self.api_key = api_key
self.base_url = base_url.rstrip("/")
self._client = httpx.AsyncClient(
base_url=self.base_url,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
timeout=timeout,
)
async def _handle_response(self, response: httpx.Response) -> Any:
"""Handle API response and raise appropriate exceptions"""
if response.is_success:
if response.status_code == 204:
return None
try:
return response.json()
except Exception:
return None
# Handle error responses
try:
error_body = response.json()
except Exception:
error_body = {"message": response.text or response.reason_phrase}
message = error_body.get("message", f"HTTP {response.status_code}")
code = error_body.get("code")
status_code = response.status_code
if status_code == 401:
raise AuthenticationError(message, status_code, code, error_body)
elif status_code == 403:
raise PermissionError(message, status_code, code, error_body)
elif status_code == 404:
raise NotFoundError(message, status_code, code, error_body)
elif status_code == 429:
retry_after = response.headers.get("Retry-After")
raise RateLimitError(
message,
status_code,
code,
error_body,
int(retry_after) if retry_after else None,
)
elif status_code == 400:
raise ValidationError(message, status_code, code, error_body)
else:
raise APIError(message, status_code, code, error_body)
async def _make_request(
self,
method: str,
path: str,
body: dict[str, Any] | None = None,
) -> Any:
"""Make an HTTP request"""
try:
if body is not None:
response = await self._client.request(method, path, json=body)
else:
response = await self._client.request(method, path)
return await self._handle_response(response)
except httpx.TimeoutException as e:
raise NetworkError(f"Request timed out: {e}") from e
except httpx.RequestError as e:
raise NetworkError(f"Network error: {e}") from e
async def get(self, path: str) -> Any:
"""Make a GET request"""
return await self._make_request("GET", path)
async def post(self, path: str, body: dict[str, Any] | None = None) -> Any:
"""Make a POST request"""
return await self._make_request("POST", path, body or {})
async def put(self, path: str, body: dict[str, Any]) -> Any:
"""Make a PUT request"""
return await self._make_request("PUT", path, body)
async def patch(self, path: str, body: dict[str, Any]) -> Any:
"""Make a PATCH request"""
return await self._make_request("PATCH", path, body)
async def delete(self, path: str) -> Any:
"""Make a DELETE request"""
return await self._make_request("DELETE", path)
async def delete_with_body(self, path: str, body: dict[str, Any]) -> Any:
"""Make a DELETE request with a body"""
return await self._make_request("DELETE", path, body)
async def close(self) -> None:
"""Close the HTTP client"""
await self._client.aclose()
async def __aenter__(self) -> "AsyncHTTPClient":
return self
async def __aexit__(self, *args: Any) -> None:
await self.close()