MCPcopy
hub / github.com/anthropics/anthropic-sdk-python / APIResponse

Class APIResponse

src/anthropic/_response.py:301–407  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

299
300
301class APIResponse(BaseAPIResponse[R]):
302 @property
303 def request_id(self) -> str | None:
304 return self.http_response.headers.get("request-id") # type: ignore[no-any-return]
305
306 @overload
307 def parse(self, *, to: type[_T]) -> _T: ...
308
309 @overload
310 def parse(self) -> R: ...
311
312 def parse(self, *, to: type[_T] | None = None) -> R | _T:
313 """Returns the rich python representation of this response's data.
314
315 For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
316
317 You can customise the type that the response is parsed into through
318 the `to` argument, e.g.
319
320 ```py
321 from anthropic import BaseModel
322
323
324 class MyModel(BaseModel):
325 foo: str
326
327
328 obj = response.parse(to=MyModel)
329 print(obj.foo)
330 ```
331
332 We support parsing:
333 - `BaseModel`
334 - `dict`
335 - `list`
336 - `Union`
337 - `str`
338 - `int`
339 - `float`
340 - `httpx.Response`
341 """
342 cache_key = to if to is not None else self._cast_to
343 cached = self._parsed_by_type.get(cache_key)
344 if cached is not None:
345 return cached # type: ignore[no-any-return]
346
347 if not self._is_sse_stream:
348 self.read()
349
350 parsed = self._parse(to=to)
351 if is_given(self._options.post_parser):
352 parsed = self._options.post_parser(parsed)
353
354 if isinstance(parsed, BaseModel):
355 add_request_id(parsed, self.request_id)
356
357 self._parsed_by_type[cache_key] = parsed
358 return cast(R, parsed)

Calls

no outgoing calls