Last modified: Jan 30, 2025 By Alexander Williams

Python httpx.Response() Guide: HTTP Responses

When working with HTTP requests in Python, the httpx.Response() object is essential. It helps you handle server responses effectively. This guide will explain its key features and how to use it.

What is httpx.Response()?

The httpx.Response() object represents the response from an HTTP request. It contains data like status codes, headers, and content. This makes it easy to process server responses in your Python applications.

Key Methods of httpx.Response()

The httpx.Response() object provides several methods to access response data. Here are some of the most important ones:

1. status_code

The status_code property returns the HTTP status code of the response. For example, 200 means success, while 404 means not found.


import httpx

response = httpx.get('https://example.com')
print(response.status_code)  # Output: 200


200

2. text

The text property returns the response body as a string. This is useful for reading HTML or JSON content.


import httpx

response = httpx.get('https://example.com')
print(response.text)  # Output: HTML content of the page


<!doctype html>
<html>
<head>
    <title>Example Domain</title>
...

3. json()

The json() method parses the response body as JSON. It returns a Python dictionary or list.


import httpx

response = httpx.get('https://api.example.com/data')
data = response.json()
print(data)  # Output: Parsed JSON data


{'key': 'value'}

Handling Errors with httpx.Response()

When working with HTTP requests, errors can occur. The httpx.Response() object helps you handle these errors gracefully.

For example, you can check the status_code to determine if the request was successful. If not, you can raise an exception or log the error.


import httpx

response = httpx.get('https://example.com/nonexistent')
if response.status_code == 404:
    print("Page not found!")


Page not found!

Advanced Features

The httpx.Response() object also supports advanced features like streaming and timeouts. For example, you can use httpx.stream() to handle large responses efficiently.

If you need to set limits on your requests, check out our guide on Python httpx.Limits().

Conclusion

The httpx.Response() object is a powerful tool for handling HTTP responses in Python. It provides easy access to status codes, headers, and content. With its advanced features, you can handle errors and large responses effectively.

For more information on related topics, explore our guides on Python httpx.Timeout() and Python httpx.AsyncClient().