Treq is a high-level HTTP client library for Python, inspired by the popular `requests` library but built upon Twisted's asynchronous networking framework. It simplifies making HTTP requests within Twisted applications by providing a familiar, easy-to-use API for various HTTP methods, JSON handling, and cookie management. The library is actively maintained, currently at version 25.5.0, with a regular release cadence to support new Python and Twisted versions.
pip install treqVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to perform a basic GET request using `treq` and print the response status, headers, and body. It uses `twisted.internet.task.react` to manage the Twisted reactor, ensuring the asynchronous operation runs correctly and the application exits gracefully.
Use either `json` for JSON payloads or `files`/`data` for form-encoded or multipart data, but not both simultaneously.
Upgrade to Python 3.8+ and ensure your Twisted installation is up-to-date (22.10.0 or newer for treq 25.5.0). Consult the treq changelog for specific version compatibility.
Upgrade to treq 22.1.0 or newer to ensure correct cookie handling and prevent unintended information disclosure.
Upgrade to treq 20.4.0 or newer. Ensure all string inputs are properly encoded if dealing with older versions, or explicitly use `hyperlink` objects for robust URL construction.
Choose only one method for sending the request body: either `json={...}` for a JSON payload, or `data={...}` for form-encoded data, or `files={...}` for multipart file uploads. Do not combine them.Ensure your application runs within the Twisted reactor. Use `twisted.internet.task.react(your_main_function)` to properly start and stop the reactor for your asynchronous code.
Upgrade treq to version 20.4.0 or newer. If stuck on an older version, manually encode URL components using `urllib.parse.quote` or `hyperlink` before passing them to treq.
Ensure you are awaiting the content retrieval methods (e.g., `body = await response.text()`) and only `decode()` raw `bytes` objects obtained from `await response.content()`.