-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathhttp_client.py
More file actions
256 lines (218 loc) · 7.57 KB
/
http_client.py
File metadata and controls
256 lines (218 loc) · 7.57 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
250
251
252
253
254
255
256
import asyncio
from types import TracebackType
from typing import Optional, Type, Union
# Self was added to typing in Python 3.11
from typing_extensions import Self
import httpx
from workos.utils._base_http_client import (
BaseHTTPClient,
HeadersType,
JsonType,
ParamsType,
ResponseJson,
)
from workos.utils.request_helper import REQUEST_METHOD_DELETE, REQUEST_METHOD_GET
class SyncHttpxClientWrapper(httpx.Client):
def __del__(self) -> None:
try:
self.close()
except Exception:
pass
class SyncHTTPClient(BaseHTTPClient[httpx.Client]):
"""Sync HTTP Client for a convenient way to access the WorkOS feature set."""
_client: httpx.Client
def __init__(
self,
*,
api_key: str,
base_url: str,
client_id: str,
version: str,
timeout: Optional[int] = None,
# If no custom transport is provided, let httpx use the default
# so we don't overwrite environment configurations like proxies
transport: Optional[httpx.BaseTransport] = None,
) -> None:
super().__init__(
api_key=api_key,
base_url=base_url,
client_id=client_id,
version=version,
timeout=timeout,
)
self._client = SyncHttpxClientWrapper(
base_url=base_url,
timeout=timeout,
follow_redirects=True,
transport=transport,
)
def is_closed(self) -> bool:
return self._client.is_closed
def close(self) -> None:
"""Close the underlying HTTPX client.
The client will *not* be usable after this.
"""
# If an error is thrown while constructing a client, self._client
# may not be present
if hasattr(self, "_client"):
self._client.close()
def __enter__(self) -> Self:
return self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
self.close()
def request(
self,
path: str,
method: Optional[str] = REQUEST_METHOD_GET,
params: ParamsType = None,
json: JsonType = None,
headers: HeadersType = None,
exclude_default_auth_headers: bool = False,
) -> ResponseJson:
"""Executes a request against the WorkOS API.
Args:
path (str): Path for the api request that'd be appended to the base API URL
Kwargs:
method (str): One of the supported methods as defined by the REQUEST_METHOD_X constants
params (ParamsType): Query params to be added to the request
json (JsonType): Body payload to be added to the request
Returns:
ResponseJson: Response from WorkOS
"""
prepared_request_parameters = self._prepare_request(
path=path,
method=method,
params=params,
json=json,
headers=headers,
exclude_default_auth_headers=exclude_default_auth_headers,
)
response = self._client.request(**prepared_request_parameters)
return self._handle_response(response)
def delete_with_body(
self,
path: str,
json: JsonType = None,
params: ParamsType = None,
headers: HeadersType = None,
exclude_default_auth_headers: bool = False,
) -> ResponseJson:
"""Executes a DELETE request with a JSON body against the WorkOS API."""
prepared_request_parameters = self._prepare_request(
path=path,
method=REQUEST_METHOD_DELETE,
json=json,
params=params,
headers=headers,
exclude_default_auth_headers=exclude_default_auth_headers,
force_include_body=True,
)
response = self._client.request(**prepared_request_parameters)
return self._handle_response(response)
class AsyncHttpxClientWrapper(httpx.AsyncClient):
def __del__(self) -> None:
try:
asyncio.get_running_loop().create_task(self.aclose())
except Exception:
pass
class AsyncHTTPClient(BaseHTTPClient[httpx.AsyncClient]):
"""Async HTTP Client for a convenient way to access the WorkOS feature set."""
_client: httpx.AsyncClient
_api_key: str
_client_id: str
def __init__(
self,
*,
base_url: str,
api_key: str,
client_id: str,
version: str,
timeout: Optional[int] = None,
# If no custom transport is provided, let httpx use the default
# so we don't overwrite environment configurations like proxies
transport: Optional[httpx.AsyncBaseTransport] = None,
) -> None:
super().__init__(
base_url=base_url,
api_key=api_key,
client_id=client_id,
version=version,
timeout=timeout,
)
self._client = AsyncHttpxClientWrapper(
base_url=base_url,
timeout=timeout,
follow_redirects=True,
transport=transport,
)
def is_closed(self) -> bool:
return self._client.is_closed
async def close(self) -> None:
"""Close the underlying HTTPX client.
The client will *not* be usable after this.
"""
await self._client.aclose()
async def __aenter__(self) -> Self:
return self
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
await self.close()
async def request(
self,
path: str,
method: Optional[str] = REQUEST_METHOD_GET,
params: ParamsType = None,
json: JsonType = None,
headers: HeadersType = None,
exclude_default_auth_headers: bool = False,
) -> ResponseJson:
"""Executes a request against the WorkOS API.
Args:
path (str): Path for the api request that'd be appended to the base API URL
Kwargs:
method (str): One of the supported methods as defined by the REQUEST_METHOD_X constants
params (ParamsType): Query params to be added to the request
json (JsonType): Body payload to be added to the request
Returns:
ResponseJson: Response from WorkOS
"""
prepared_request_parameters = self._prepare_request(
path=path,
method=method,
params=params,
json=json,
headers=headers,
exclude_default_auth_headers=exclude_default_auth_headers,
)
response = await self._client.request(**prepared_request_parameters)
return self._handle_response(response)
async def delete_with_body(
self,
path: str,
json: JsonType = None,
params: ParamsType = None,
headers: HeadersType = None,
exclude_default_auth_headers: bool = False,
) -> ResponseJson:
"""Executes a DELETE request with a JSON body against the WorkOS API."""
prepared_request_parameters = self._prepare_request(
path=path,
method=REQUEST_METHOD_DELETE,
json=json,
params=params,
headers=headers,
exclude_default_auth_headers=exclude_default_auth_headers,
force_include_body=True,
)
response = await self._client.request(**prepared_request_parameters)
return self._handle_response(response)
HTTPClient = Union[AsyncHTTPClient, SyncHTTPClient]