@@ -50,34 +50,32 @@ def perform(self) -> Union[T, None]:
5050 """
5151 resp = self .make_request (url = f"{ self .api_url } { self .path } " )
5252
53- # delete calls do not return a body
54- if resp .text == "" and resp .status_code == 200 :
55- return None
56-
57- # this is a safety net, if we get here it means the JigsawStack API is having issues
58- # and most likely the gateway is returning htmls
59- if "application/json" not in resp .headers ["content-type" ] \
60- and "audio/wav" not in resp .headers ["content-type" ] \
61- and "image/png" not in resp .headers ["content-type" ]:
62- raise_for_code_and_type (
63- code = 500 ,
64- message = "Failed to parse JigsawStack API response. Please try again." ,
65- )
53+ # For binary responses or empty responses
54+ if resp .status_code == 200 :
55+ content_type = resp .headers .get ("content-type" , "" )
56+ if not resp .text or any (t in content_type for t in ["audio/" , "image/" , "application/octet-stream" ]):
57+ return cast (T , resp )
6658
67- # handle error in case there is a statusCode attr present
68- # and status != 200 and response is a json.
59+ # Handle errors and JSON responses
6960 if resp .status_code != 200 :
70- error = resp .json ()
71- raise_for_code_and_type (
72- code = resp .status_code ,
73- message = error .get ("message" ),
74- err = error .get ("error" ),
75- )
61+ try :
62+ error = resp .json ()
63+ raise_for_code_and_type (
64+ code = resp .status_code ,
65+ message = error .get ("message" ),
66+ err = error .get ("error" ),
67+ )
68+ except json .JSONDecodeError :
69+ raise_for_code_and_type (
70+ code = 500 ,
71+ message = "Failed to parse response. Invalid content type or encoding." ,
72+ )
7673
77- if "audio/wav" or "image/png" in resp .headers ["content-type" ]:
78- return cast (T , resp ) # we return the response object, instead of the json
79-
80- return cast (T , resp .json ())
74+ # For JSON responses
75+ try :
76+ return cast (T , resp .json ())
77+ except json .JSONDecodeError :
78+ return cast (T , resp )
8179
8280 def perform_file (self ) -> Union [T , None ]:
8381
0 commit comments