Read status, headers, and body data
Inspect API results
HTTPX · Class
HTTPX Response represents the result of an HTTP request. It provides status and protocol metadata, headers, URL information, body access, status validation, and synchronous or asynchronous streaming operations.
An HTTPX Response represents the server's result for a request. It exposes metadata such as status, URL, headers, and HTTP version, plus decoded or raw body access; asynchronous clients additionally provide awaitable reading, iteration, and closing operations.
class httpx.ResponseA Response instance representing an HTTP response.
status_code contains the numeric HTTP status as an integer.reason_phrase provides the textual HTTP reason phrase.http_version identifies the protocol version used for the response.import httpx
async def fetch() -> None:
async with httpx.AsyncClient() as client:
response = await client.get("https://example.com")
response.raise_for_status()
print(response.status_code)
print(response.json())Makes an asynchronous request, validates the status, then reads the status code and JSON body.
Inspect API results
Validate HTTP outcomes
Process large downloads
Build async network workflows
status_code gives the numeric HTTP status, while raise_for_status() raises an exception for unsuccessful responses. A successful response remains a Response object without automatically raising.
Follow-up: How can success be checked without raising? Use the is_success property, which represents a 2xx response.
Use content for bytes, text for decoded Unicode, and json() for JSON response data. The response also exposes dictionary-like headers and a URL object.
Follow-up: What happens with a streamed response? The body must be consumed with streaming APIs, and content and text are unavailable until it is read.
For asynchronous streaming, use aread(), aiter_bytes(), aiter_text(), aiter_lines(), or aiter_raw(). aclose() closes the response, although an AsyncClient.stream() block closes it automatically.
Follow-up: When would aiter_raw() be preferable? Use it when the unprocessed response bytes are required rather than content-decoded data.
RequestHeadersURLAsyncClientClient