11from __future__ import annotations
22
33import inspect
4+ import logging
45import datetime
56import functools
67from typing import TYPE_CHECKING , Any , Union , Generic , TypeVar , Callable , cast
78from typing_extensions import Awaitable , ParamSpec , get_args , override , get_origin
89
910import httpx
10- import pydantic
1111
1212from ._types import NoneType , UnknownResponse , BinaryResponseContent
1313from ._utils import is_given
14- from ._models import BaseModel
14+ from ._models import BaseModel , is_basemodel
1515from ._constants import RAW_RESPONSE_HEADER
1616from ._exceptions import APIResponseValidationError
1717
2323P = ParamSpec ("P" )
2424R = TypeVar ("R" )
2525
26+ log : logging .Logger = logging .getLogger (__name__ )
27+
2628
2729class APIResponse (Generic [R ]):
2830 _cast_to : type [R ]
@@ -174,6 +176,18 @@ def _parse(self) -> R:
174176 # in the response, e.g. application/json; charset=utf-8
175177 content_type , * _ = response .headers .get ("content-type" ).split (";" )
176178 if content_type != "application/json" :
179+ if is_basemodel (cast_to ):
180+ try :
181+ data = response .json ()
182+ except Exception as exc :
183+ log .debug ("Could not read JSON from response data due to %s - %s" , type (exc ), exc )
184+ else :
185+ return self ._client ._process_response_data (
186+ data = data ,
187+ cast_to = cast_to , # type: ignore
188+ response = response ,
189+ )
190+
177191 if self ._client ._strict_response_validation :
178192 raise APIResponseValidationError (
179193 response = response ,
@@ -188,14 +202,11 @@ def _parse(self) -> R:
188202
189203 data = response .json ()
190204
191- try :
192- return self ._client ._process_response_data (
193- data = data ,
194- cast_to = cast_to , # type: ignore
195- response = response ,
196- )
197- except pydantic .ValidationError as err :
198- raise APIResponseValidationError (response = response , body = data ) from err
205+ return self ._client ._process_response_data (
206+ data = data ,
207+ cast_to = cast_to , # type: ignore
208+ response = response ,
209+ )
199210
200211 @override
201212 def __repr__ (self ) -> str :
0 commit comments