Treq

25.5.0 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

from twisted.internet.task import react
import treq
import os

async def fetch_and_print(reactor):
    # Using httpbin.org for a simple test endpoint
    response = await treq.get("https://httpbin.org/get", reactor=reactor)
    print(f"Status: {response.code} {response.phrase.decode()}")
    print("Headers:")
    for k, v in response.headers.getAllRawHeaders():
        print(f"  {k.decode()}: {', '.join(map(bytes.decode, v))}")
    body = await response.text()
    print("Body:")
    print(body)

if __name__ == '__main__':
    react(fetch_and_print)

view raw JSON →