Skip to content

Commit fd588ab

Browse files
committed
added support for arbitrary response types
1 parent 985616b commit fd588ab

6 files changed

Lines changed: 786 additions & 94 deletions

File tree

‎t3api_utils/api/operations.py‎

Lines changed: 42 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@
1616

1717
from t3api_utils.api.client import T3APIClient
1818
from t3api_utils.api.interfaces import MetrcCollectionResponse
19-
from t3api_utils.http.utils import T3HTTPError, arequest_json
19+
from t3api_utils.http.utils import ResponseType, T3HTTPError
20+
from t3api_utils.http import utils as _http_utils
2021

2122

2223
def send_api_request(
@@ -29,6 +30,7 @@ def send_api_request(
2930
files: Optional[Any] = None,
3031
headers: Optional[Dict[str, str]] = None,
3132
expected_status: Union[int, tuple[int, ...]] = 200,
33+
response_type: ResponseType = "json",
3234
) -> Any:
3335
"""Send a request to any T3 API endpoint (sync wrapper).
3436
@@ -48,9 +50,14 @@ def send_api_request(
4850
``{"file": ("name.png", data, "image/png")}``).
4951
headers: Additional headers (optional)
5052
expected_status: Expected HTTP status code(s) (default: 200)
53+
response_type: How to interpret the response body. ``"json"``
54+
(default) parses as JSON, ``"bytes"`` returns raw bytes,
55+
``"text"`` returns decoded text, ``"response"`` returns the
56+
full ``httpx.Response``.
5157
5258
Returns:
53-
Raw response data (could be dict, list, or any JSON-serializable type)
59+
Response data whose type depends on *response_type*:
60+
JSON-parsed ``Any``, ``bytes``, ``str``, or ``httpx.Response``.
5461
5562
Raises:
5663
ValueError: If both *json_body* and *files* are provided.
@@ -59,13 +66,20 @@ def send_api_request(
5966
if json_body is not None and files is not None:
6067
raise ValueError("json_body and files are mutually exclusive; provide one or neither.")
6168

62-
# For sync wrapper, we need to handle the case where the client might have been
63-
# created in a different event loop context. The safest approach is to create
64-
# a new client instance for this operation.
65-
66-
from t3api_utils.http.utils import request_json
69+
from t3api_utils.http.utils import (
70+
request_bytes,
71+
request_json,
72+
request_raw,
73+
request_text,
74+
)
75+
76+
_sync_dispatchers = {
77+
"json": request_json,
78+
"bytes": request_bytes,
79+
"text": request_text,
80+
"response": request_raw,
81+
}
6782

68-
# Use the sync version of request_json directly with the client's underlying config
6983
if not client.is_authenticated:
7084
raise T3HTTPError("Client is not authenticated. Call authenticate_with_credentials() first.")
7185

@@ -90,8 +104,10 @@ def send_api_request(
90104
if client._config.proxies:
91105
client_kwargs["proxies"] = client._config.proxies
92106

107+
dispatch_fn = _sync_dispatchers[response_type]
108+
93109
with httpx.Client(**client_kwargs) as sync_client:
94-
return request_json(
110+
return dispatch_fn(
95111
client=sync_client,
96112
method=method,
97113
url=path,
@@ -253,7 +269,7 @@ async def get_collection_async(
253269
params["filter"] = filter
254270

255271
try:
256-
response_data = await arequest_json(
272+
response_data = await _http_utils.arequest_json(
257273
aclient=client._client,
258274
method="GET",
259275
url=path,
@@ -278,6 +294,7 @@ async def send_api_request_async(
278294
files: Optional[Any] = None,
279295
headers: Optional[Dict[str, str]] = None,
280296
expected_status: Union[int, tuple[int, ...]] = 200,
297+
response_type: ResponseType = "json",
281298
) -> Any:
282299
"""Send a request to any T3 API endpoint using an async client.
283300
@@ -296,9 +313,14 @@ async def send_api_request_async(
296313
``files`` parameter.
297314
headers: Additional headers (optional)
298315
expected_status: Expected HTTP status code(s) (default: 200)
316+
response_type: How to interpret the response body. ``"json"``
317+
(default) parses as JSON, ``"bytes"`` returns raw bytes,
318+
``"text"`` returns decoded text, ``"response"`` returns the
319+
full ``httpx.Response``.
299320
300321
Returns:
301-
Raw response data (could be dict, list, or any JSON-serializable type)
322+
Response data whose type depends on *response_type*:
323+
JSON-parsed ``Any``, ``bytes``, ``str``, or ``httpx.Response``.
302324
303325
Raises:
304326
ValueError: If both *json_body* and *files* are provided.
@@ -310,8 +332,16 @@ async def send_api_request_async(
310332
if not client.is_authenticated:
311333
raise T3HTTPError("Client is not authenticated. Call authenticate_with_credentials() first.")
312334

335+
_async_dispatchers = {
336+
"json": _http_utils.arequest_json,
337+
"bytes": _http_utils.arequest_bytes,
338+
"text": _http_utils.arequest_text,
339+
"response": _http_utils.arequest_raw,
340+
}
341+
dispatch_fn = _async_dispatchers[response_type]
342+
313343
try:
314-
response_data = await arequest_json(
344+
return await dispatch_fn(
315345
aclient=client._client,
316346
method=method,
317347
url=path,
@@ -323,7 +353,5 @@ async def send_api_request_async(
323353
expected_status=expected_status,
324354
)
325355

326-
return response_data
327-
328356
except T3HTTPError as e:
329357
raise T3HTTPError(f"Failed to get data from {path}: {e}", response=e.response) from e

0 commit comments

Comments
 (0)