Skip to content

rnet (Main Module)

The main rnet module contains core classes and types used throughout the library.

Core Classes

rnet.Client

A client for making HTTP requests.

cookie_jar instance-attribute

cookie_jar

Get the cookie jar used by this client (if enabled/configured).

Returns:

Type Description
Jar | None
  • The provided Jar if the client was constructed with cookie_provider=...
Jar | None
  • The auto-created Jar if the client was constructed with cookie_store=True

__init__

__init__(**kwargs)

Creates a new Client instance.

Examples:

import asyncio
import rnet

async def main():
    client = rnet.Client(
        user_agent="Mozilla/5.0",
        timeout=10,
    )
    response = await client.get('https://httpbin.io/get')
    print(await response.text())

asyncio.run(main())

request async

request(method, url, **kwargs)

Sends a request with the given method and URL.

Examples

import rnet
import asyncio
from rnet import Method

async def main():
    client = rnet.Client()
    response = await client.request(Method.GET, "https://httpbin.io/anything")
    print(await response.text())

asyncio.run(main())

websocket async

websocket(url, **kwargs)

Sends a WebSocket request.

Examples

import rnet
import asyncio

async def main():
    client = rnet.Client()
    ws = await client.websocket("wss://echo.websocket.org")
    await ws.send(rnet.Message.from_text("Hello, WebSocket!"))
    message = await ws.recv()
    print("Received:", message.data)
    await ws.close()

asyncio.run(main())

trace async

trace(url, **kwargs)

Sends a request with the given URL

Examples

import rnet
import asyncio
from rnet import Method

async def main():
    client = rnet.Client()
    response = await client.trace("https://httpbin.io/anything")
    print(await response.text())

asyncio.run(main())

options async

options(url, **kwargs)

Sends a request with the given URL

Examples

import rnet
import asyncio
from rnet import Method

async def main():
    client = rnet.Client()
    response = await client.options("https://httpbin.io/anything")
    print(await response.text())

asyncio.run(main())

patch async

patch(url, **kwargs)

Sends a request with the given URL

Examples

import rnet
import asyncio
from rnet import Method

async def main():
    client = rnet.Client()
    response = await client.patch("https://httpbin.io/anything", json={"key": "value"})
    print(await response.text())

asyncio.run(main())

delete async

delete(url, **kwargs)

Sends a request with the given URL

Examples

import rnet
import asyncio
from rnet import Method

async def main():
    client = rnet.Client()
    response = await client.delete("https://httpbin.io/anything")
    print(await response.text())

asyncio.run(main())

put async

put(url, **kwargs)

Sends a request with the given URL

Examples

import rnet
import asyncio
from rnet import Method

async def main():
    client = rnet.Client()
    response = await client.put("https://httpbin.io/anything", json={"key": "value"})
    print(await response.text())

asyncio.run(main())

post async

post(url, **kwargs)

Sends a request with the given URL

Examples

import rnet
import asyncio
from rnet import Method

async def main():
    client = rnet.Client()
    response = await client.post("https://httpbin.io/anything", json={"key": "value"})
    print(await response.text())

asyncio.run(main())

head async

head(url, **kwargs)

Sends a request with the given URL

Examples

import rnet
import asyncio
from rnet import Method

async def main():
    client = rnet.Client()
    response = await client.head("https://httpbin.io/anything")
    print(response.status)

asyncio.run(main())

get async

get(url, **kwargs)

Sends a request with the given URL

Examples

import rnet
import asyncio
from rnet import Method

async def main():
    client = rnet.Client()
    response = await client.get("https://httpbin.io/anything")
    print(await response.text())

asyncio.run(main())

rnet.Response

A response from a request.

Examples

import asyncio
import rnet

async def main():
    response = await rnet.get("https://www.rust-lang.org")
    print("Status Code: ", response.status)
    print("Version: ", response.version)
    print("Response URL: ", response.url)
    print("Headers: ", response.headers)
    print("Content-Length: ", response.content_length)
    print("Encoding: ", response.encoding)
    print("Remote Address: ", response.remote_addr)

    text_content = await response.text()
    print("Text: ", text_content)

if __name__ == "__main__":
    asyncio.run(main())

url instance-attribute

url

Get the URL of the response.

status instance-attribute

status

Get the status code of the response.

version instance-attribute

version

Get the HTTP version of the response.

headers instance-attribute

headers

Get the headers of the response.

cookies instance-attribute

cookies

Get the cookies of the response.

content_length instance-attribute

content_length

Get the content length of the response.

remote_addr instance-attribute

remote_addr

Get the remote address of the response.

local_addr instance-attribute

local_addr

Get the local address of the response.

history instance-attribute

history

Get the redirect history of the Response.

tls_info instance-attribute

tls_info

Get the TLS information of the response.

raise_for_status

raise_for_status()

Turn a response into an error if the server returned an error.

stream

stream()

Get the response into a Streamer of bytes from the body.

text async

text()

Get the text content of the response.

text_with_charset async

text_with_charset(encoding)

Get the full response text given a specific encoding.

json async

json()

Get the JSON content of the response.

bytes async

bytes()

Get the bytes content of the response.

close async

close()

Close the response connection.

HTTP Types

rnet.Method

Bases: Enum

An HTTP method.

rnet.Version

Bases: Enum

An HTTP version.

rnet.StatusCode

HTTP status code.

as_int

as_int()

Return the status code as an integer.

is_informational

is_informational()

Check if status is within 100-199.

is_success

is_success()

Check if status is within 200-299.

is_redirection

is_redirection()

Check if status is within 300-399.

is_client_error

is_client_error()

Check if status is within 400-499.

is_server_error

is_server_error()

Check if status is within 500-599.

__str__

__str__()

__richcmp__

__richcmp__(other, op)

Request Types

rnet.Request

Bases: TypedDict

emulation instance-attribute

emulation

The Emulation settings for the request.

proxy instance-attribute

proxy

The proxy to use for the request.

local_address instance-attribute

local_address

Bind to a local IP Address.

local_addresses instance-attribute

local_addresses

Bind to dual-stack local IP Addresses.

interface instance-attribute

interface

Bind to an interface by SO_BINDTODEVICE.

timeout instance-attribute

timeout

The timeout to use for the request.

read_timeout instance-attribute

read_timeout

The read timeout to use for the request.

version instance-attribute

version

The HTTP version to use for the request.

headers instance-attribute

headers

The headers to use for the request.

orig_headers instance-attribute

orig_headers

The original headers to use for the request.

default_headers instance-attribute

default_headers

The option enables default headers.

cookies instance-attribute

cookies

The cookies to use for the request.

redirect instance-attribute

redirect

The redirect policy.

cookie_provider instance-attribute

cookie_provider

Set cookie provider for the request.

gzip instance-attribute

gzip

Sets gzip as an accepted encoding.

brotli instance-attribute

brotli

Sets brotli as an accepted encoding.

deflate instance-attribute

deflate

Sets deflate as an accepted encoding.

zstd instance-attribute

zstd

Sets zstd as an accepted encoding.

auth instance-attribute

auth

The authentication to use for the request.

bearer_auth instance-attribute

bearer_auth

The bearer authentication to use for the request.

basic_auth instance-attribute

basic_auth

The basic authentication to use for the request.

query instance-attribute

query

The query parameters to use for the request.

form instance-attribute

form

The form parameters to use for the request.

json instance-attribute

json

The JSON body to use for the request.

body instance-attribute

body

The body to use for the request.

multipart instance-attribute

multipart

The multipart form to use for the request.

rnet.Multipart

A multipart form for a request.

__init__

__init__(*parts)

Creates a new multipart form.

rnet.Part

A part of a multipart form.

__init__

__init__(name, value, filename=None, mime=None, length=None, headers=None)

Creates a new part.

Arguments

  • name - The name of the part.
  • value - The value of the part, either text, bytes, a file path, or a async or sync stream.
  • filename - The filename of the part.
  • mime - The MIME type of the part.
  • length - The length of the part when value is a stream (e.g., for file uploads).
  • headers - The custom headers for the part.

WebSocket

rnet.WebSocket

A WebSocket response.

status instance-attribute

status

Get the status code of the response.

version instance-attribute

version

Get the HTTP version of the response.

headers instance-attribute

headers

Get the headers of the response.

cookies instance-attribute

cookies

Get the cookies of the response.

remote_addr instance-attribute

remote_addr

Get the remote address of the response.

protocol instance-attribute

protocol

Get the WebSocket protocol.

recv async

recv(timeout=None)

Receive a message from the WebSocket.

send async

send(message)

Send a message to the WebSocket.

send_all async

send_all(messages)

Send multiple messages to the WebSocket.

close async

close(code=None, reason=None)

Close the WebSocket connection.

rnet.WebSocketRequest

Bases: TypedDict

emulation instance-attribute

emulation

The Emulation settings for the request.

proxy instance-attribute

proxy

The proxy to use for the request.

local_address instance-attribute

local_address

Bind to a local IP Address.

local_addresses instance-attribute

local_addresses

Bind to dual-stack local IP Addresses.

interface instance-attribute

interface

Bind to an interface by SO_BINDTODEVICE.

headers instance-attribute

headers

The headers to use for the request.

orig_headers instance-attribute

orig_headers

The original headers to use for the request.

default_headers instance-attribute

default_headers

The option enables default headers.

cookies instance-attribute

cookies

The cookies to use for the request.

protocols instance-attribute

protocols

The protocols to use for the request.

force_http2 instance-attribute

force_http2

Whether to use HTTP/2 for the websocket.

auth instance-attribute

auth

The authentication to use for the request.

bearer_auth instance-attribute

bearer_auth

The bearer authentication to use for the request.

basic_auth instance-attribute

basic_auth

The basic authentication to use for the request.

query instance-attribute

query

The query parameters to use for the request.

read_buffer_size instance-attribute

read_buffer_size

Read buffer capacity. This buffer is eagerly allocated and used for receiving messages.

For high read load scenarios a larger buffer, e.g. 128 KiB, improves performance.

For scenarios where you expect a lot of connections and don't need high read load performance a smaller buffer, e.g. 4 KiB, would be appropriate to lower total memory usage.

The default value is 128 KiB.

write_buffer_size instance-attribute

write_buffer_size

The target minimum size of the write buffer to reach before writing the data to the underlying stream. The default value is 128 KiB.

If set to 0 each message will be eagerly written to the underlying stream. It is often more optimal to allow them to buffer a little, hence the default value.

Note: flush() will always fully write the buffer regardless.

max_write_buffer_size instance-attribute

max_write_buffer_size

The max size of the write buffer in bytes. Setting this can provide backpressure in the case the write buffer is filling up due to write errors. The default value is unlimited.

Note: The write buffer only builds up past write_buffer_size when writes to the underlying stream are failing. So the write buffer can not fill up if you are not observing write errors even if not flushing.

Note: Should always be at least write_buffer_size + 1 message and probably a little more depending on error handling strategy.

max_message_size instance-attribute

max_message_size

The maximum size of an incoming message. None means no size limit. The default value is 64 MiB which should be reasonably big for all normal use-cases but small enough to prevent memory eating by a malicious user.

max_frame_size instance-attribute

max_frame_size

The maximum size of a single incoming message frame. None means no size limit. The limit is for frame payload NOT including the frame header. The default value is 16 MiB which should be reasonably big for all normal use-cases but small enough to prevent memory eating by a malicious user.

accept_unmasked_frames instance-attribute

accept_unmasked_frames

When set to True, the server will accept and handle unmasked frames from the client. According to RFC 6455, the server must close the connection to the client in such cases, however it seems like there are some popular libraries that are sending unmasked frames, ignoring the RFC. By default this option is set to False, i.e. according to RFC6455.

rnet.Message

A WebSocket message.

data instance-attribute

data

Returns the data of the message as bytes.

text instance-attribute

text

Returns the text content of the message if it is a text message.

binary instance-attribute

binary

Returns the binary data of the message if it is a binary message.

ping instance-attribute

ping

Returns the ping data of the message if it is a ping message.

pong instance-attribute

pong

Returns the pong data of the message if it is a pong message.

close instance-attribute

close

Returns the close code and reason of the message if it is a close message.

text_from_json staticmethod

text_from_json(json)

Creates a new text message from the JSON representation.

Arguments

  • json - The JSON representation of the message.

binary_from_json staticmethod

binary_from_json(json)

Creates a new binary message from the JSON representation.

Arguments

  • json - The JSON representation of the message.

from_text staticmethod

from_text(text)

Creates a new text message.

Arguments

  • text - The text content of the message.

from_binary staticmethod

from_binary(data)

Creates a new binary message.

Arguments

  • data - The binary data of the message.

from_ping staticmethod

from_ping(data)

Creates a new ping message.

Arguments

  • data - The ping data of the message.

from_pong staticmethod

from_pong(data)

Creates a new pong message.

Arguments

  • data - The pong data of the message.

from_close staticmethod

from_close(code, reason=None)

Creates a new close message.

Arguments

  • code - The close code.
  • reason - An optional reason for closing.

json

json()

Returns the JSON representation of the message.

Streaming

rnet.Streamer

A stream response. An asynchronous iterator yielding data chunks (bytes) or HTTP trailers (HeaderMap) from the response stream. Used to stream response content and receive HTTP trailers if present. Implemented in the stream method of the Response class. Can be used in an asynchronous for loop in Python.

When streaming a response, each iteration yields either a bytes object (for body data) or a HeaderMap (for HTTP trailers, if the server sends them). This allows you to access HTTP/1.1 or HTTP/2 trailers in addition to the main body.

Examples

import asyncio
import rnet
from rnet import Method, Emulation, HeaderMap

async def main():
    resp = await rnet.get("https://example.com/stream-with-trailers")
    async with resp.stream() as streamer:
        async for chunk in streamer:
            if isinstance(chunk, bytes):
                print("Chunk: ", chunk)
            elif isinstance(chunk, HeaderMap):
                print("Trailers: ", chunk)
            await asyncio.sleep(0.1)

if __name__ == "__main__":
    asyncio.run(main())

Network Types

rnet.SocketAddr

A IP socket address.

ip

ip()

Returns the IP address of the socket address.

port

port()

Returns the port number of the socket address.

Configuration

rnet.ClientConfig

Bases: TypedDict

emulation instance-attribute

emulation

Emulation config.

user_agent instance-attribute

user_agent

Sets the User-Agent header to be used by this client.

headers instance-attribute

headers

Sets the default headers for every request.

orig_headers instance-attribute

orig_headers

Sets the original headers for every request.

referer instance-attribute

referer

Enable or disable automatic setting of the Referer header.

redirect instance-attribute

redirect

Set a redirect.Policy for this client.

cookie_store instance-attribute

cookie_store

Enable a persistent cookie store for the client.

cookie_provider instance-attribute

cookie_provider

Set the persistent cookie store for the client.

Cookies received in responses will be passed to this store, and additional requests will query this store for cookies.

By default, no cookie store is used.

timeout instance-attribute

timeout

Enables a request timeout.

The timeout is applied from when the request starts connecting until the response body has finished.

Default is no timeout.

connect_timeout instance-attribute

connect_timeout

Set a timeout for only the connect phase of a Client.

read_timeout instance-attribute

read_timeout

Set a timeout for only the read phase of a Client.

tcp_keepalive instance-attribute

tcp_keepalive

Set that all sockets have SO_KEEPALIVE set with the supplied duration.

Default is 15 seconds.

tcp_keepalive_interval instance-attribute

tcp_keepalive_interval

Set that all sockets have SO_KEEPALIVE set with the supplied interval.

Default is 15 seconds.

tcp_keepalive_retries instance-attribute

tcp_keepalive_retries

Set that all sockets have SO_KEEPALIVE set with the supplied retry count.

Default is 3 retries.

tcp_user_timeout instance-attribute

tcp_user_timeout

Set that all sockets have TCP_USER_TIMEOUT set with the supplied duration.

This option controls how long transmitted data may remain unacknowledged before the connection is force-closed.

Default is 30 seconds.

tcp_nodelay instance-attribute

tcp_nodelay

Set whether sockets have TCP_NODELAY enabled.

Default is True.

tcp_reuse_address instance-attribute

tcp_reuse_address

Enable SO_REUSEADDR.

pool_idle_timeout instance-attribute

pool_idle_timeout

Set an optional timeout for idle sockets being kept-alive.

pool_max_idle_per_host instance-attribute

pool_max_idle_per_host

Sets the maximum idle connection per host allowed in the pool.

pool_max_size instance-attribute

pool_max_size

Sets the maximum number of connections in the pool.

http1_only instance-attribute

http1_only

Only use HTTP/1.

http2_only instance-attribute

http2_only

Only use HTTP/2.

https_only instance-attribute

https_only

Restrict the Client to be used with HTTPS only requests.

http1_options instance-attribute

http1_options

Sets the HTTP/1 options for the client.

http2_options instance-attribute

http2_options

Sets the HTTP/2 options for the client.

verify instance-attribute

verify

Sets whether to verify TLS certificates.

verify_hostname instance-attribute

verify_hostname

Configures the use of hostname verification when connecting.

identity instance-attribute

identity

Represents a private key and X509 cert as a client certificate.

keylog instance-attribute

keylog

Key logging policy (environment or file).

tls_info instance-attribute

tls_info

Add TLS information as TlsInfo extension to responses.

min_tls_version instance-attribute

min_tls_version

Minimum TLS version.

max_tls_version instance-attribute

max_tls_version

Maximum TLS version.

tls_options instance-attribute

tls_options

Sets the TLS options.

no_proxy instance-attribute

no_proxy

Clear all proxies, so Client will use no proxy anymore.

This also disables the automatic usage of the "system" proxy.

proxies instance-attribute

proxies

Add a Proxy list to the client.

local_address instance-attribute

local_address

Bind to a local IP Address.

local_addresses instance-attribute

local_addresses

Bind to dual-stack local IP Addresses.

interface instance-attribute

interface

Bind connections only on the specified network interface.

This option is only available on the following operating systems:

  • Android
  • Fuchsia
  • Linux
  • macOS and macOS-like systems (iOS, tvOS, watchOS and visionOS)
  • Solaris and illumos

On Android, Linux, and Fuchsia, this uses the [SO_BINDTODEVICE][man-7-socket] socket option. On macOS and macOS-like systems, Solaris, and illumos, this instead uses the [IP_BOUND_IF and IPV6_BOUND_IF][man-7p-ip] socket options (as appropriate).

Note that connections will fail if the provided interface name is not a network interface that currently exists when a connection is established.

gzip instance-attribute

gzip

Enable auto gzip decompression by checking the Content-Encoding response header.

brotli instance-attribute

brotli

Enable auto brotli decompression by checking the Content-Encoding response header.

deflate instance-attribute

deflate

Enable auto deflate decompression by checking the Content-Encoding response header.

zstd instance-attribute

zstd

Enable auto zstd decompression by checking the Content-Encoding response header.