tez 0.0.2

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation

tez

tez is a lightweight, ergonomic, and fast high-level HTTP client for Rust.

The name comes from the Hindi word तेज़ (tez): fast.

It keeps everyday HTTP work direct and readable while retaining the standard Rust HTTP types for the cases that need more control.

Quick start

Add Tez and a Tokio runtime:

[dependencies]
tez = "0.1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
serde = { version = "1", features = ["derive"] } # for `.json(...)` below

Cargo features

Tez keeps response codecs and stateful behavior explicit:

Feature Effect
gzip (default) Transparently decodes gzip responses.
brotli Adds Brotli (br) response decoding.
deflate Adds deflate response decoding.
zstd Adds Zstandard response decoding.
cookies Adds an optional in-memory cookie jar.
system-proxy Adds optional system proxy discovery.

Gzip is the sole default feature. HTTP/2 remains part of every Tez client.

Command-line client

The optional cli feature builds Tez's human-friendly tez command. From this repository, run it with:

cargo run -p tez --features cli -- example.com

Its HTTPie-style request syntax and terminal behavior are documented in CLI.md.

Create one client for each shared policy, then reuse it:

#[derive(serde::Serialize)]
struct NewUser {
    name: String,
}

#[tokio::main]
async fn main() -> tez::Result<()> {
    let client = tez::Client::builder()
        .base_url("https://api.example.com/v1")
        .timeout(std::time::Duration::from_secs(30))
        .build()?;

    let response = client
        .post("/users")
        .json(&NewUser {
            name: "Ada".into(),
        })
        .send()
        .await?;

    if response.status().is_success() {
        println!("{}", response.text().await?);
    }

    Ok(())
}

Core model

Type Responsibility
[Client] Holds shared policy and sends requests through a shared connection pool.
[RequestBuilder] Builds one detached [Request] and borrows its client only for .send().
[Request] A standard http::Request<Body> that can be inspected, stored, or sent later.
[Response] Final response metadata plus a one-shot streaming [Body].
[Multipart] and [Part] Build an owned multipart request body from buffered or streaming fields.

Calling [RequestBuilder::build] performs no I/O. It returns the owned request, ready to inspect, store, or send later through a compatible client.

Request targets

A request target is either a complete HTTP(S) URL or a root-leading path. A path needs a client base URL:

# async fn run(client: tez::Client) -> tez::Result<()> {
client.get("https://example.com/users").send().await?;
client.get("/users?page=2").send().await?;
# Ok(())
# }

A base URL acts as a path prefix. With https://example.com/api, /users becomes https://example.com/api/users. Ambiguous relative targets such as users are rejected.

Tez checks the normalized path remains inside that prefix. For example, /../admin cannot escape an /api base URL.

Authentication

Tez includes header-based API key, Basic, and Bearer authentication. Custom implementations can refresh credentials asynchronously and apply every header their protocol owns after the request URL and ordinary headers are resolved.

Provider clients commonly use one credential for every request. Configure it once on the client so callers do not need to assemble Authorization headers:

fn provider_client(token: &str) -> tez::Result<tez::Client> {
    tez::Client::builder()
        .base_url("https://api.example.com/v1")
        .auth(tez::auth::BearerAuth::new(token)?)
        .build()
}

Use [auth::BasicAuth] when one request needs different credentials:

# async fn run(
#     client: &tez::Client,
#     username: &str,
#     password: &str,
# ) -> tez::Result<()> {
client
    .get("/account")
    .auth(tez::auth::BasicAuth::new(username, password)?)
    .send()
    .await?
    .discard()
    .await?;
# Ok(())
# }

Request authentication replaces a client default. Authentication runs once before the first network attempt, so each implementation has final ownership of the headers it applies. Basic usernames cannot contain :; Basic credentials cannot contain ASCII control characters, and Bearer tokens must be nonempty RFC 6750 tokens. Their constructors reject invalid credentials without including the credential text. Values generated by the authentication helpers are marked sensitive for standard header debug output.

Client authentication also applies to complete URLs on another origin. Use a separate client for each trust domain.

Proxies

Clients connect directly by default. Route both HTTP and HTTPS requests through one explicit HTTP(S) proxy origin when needed:

fn proxied_client() -> tez::Result<tez::Client> {
    tez::Client::builder()
        .proxy(tez::proxy::Policy::all("http://proxy.example:8080"))
        .build()
}

An explicit proxy URL may contain credentials, but cannot contain a path, query, or fragment. It applies to every Tez HTTP(S) request and ignores process proxy settings, including NO_PROXY.

Enable the system-proxy Cargo feature to opt into conventional environment and supported operating-system discovery:

# #[cfg(feature = "system-proxy")]
fn workstation_client() -> tez::Result<tez::Client> {
    tez::Client::builder()
        .proxy(tez::proxy::Policy::system())
        .build()
}

Policy::system reads HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, NO_PROXY, their lowercase forms, and supported operating-system settings when the client is built. The resulting client does not observe later changes. Use Policy::direct to express the default explicitly when application configuration selects a policy. A later ClientBuilder::proxy call replaces the earlier policy.

Tez does not expose explicit SOCKS configuration or per-destination routing callbacks.

Cookies

Enable the cookies Cargo feature, then opt one client into in-memory cookie handling:

# #[cfg(feature = "cookies")]
fn session_client() -> tez::Result<tez::Client> {
    tez::Client::builder().cookies().build()
}

Cookies are disabled by default. ClientBuilder::cookies gives one client an in-memory cookie jar. It accepts response cookies and sends them on later matching requests using their domain, path, secure, and expiry rules. Client clones share the same private jar.

An explicit request Cookie header is sent unchanged instead of cookies from the jar for that request. Response cookies are still remembered. Do not set Cookie as a client default: client defaults also apply to explicit URLs on other origins.

The jar exists only in memory and is discarded with the client. Tez does not expose cookie or jar types, persistent session files, custom storage, or direct jar mutation.

TLS trust

HTTPS uses rustls with platform certificate verification by default. For a private certificate authority, configure an isolated trust bundle:

fn private_client(ca: &[u8], identity: &[u8]) -> tez::Result<tez::Client> {
    tez::Client::builder()
        .trust_pem(ca)
        .identity_pem(identity)
        .https_only()
        .build()
}

[ClientBuilder::trust_pem] replaces platform roots instead of merging with them. The PEM bundle must contain at least one X.509 certificate. [ClientBuilder::identity_pem] accepts a combined PEM certificate chain and unencrypted private key for mutual TLS. Repeating either method replaces its previous value.

Use one client per trust domain. A client with private roots cannot also trust the platform roots, which keeps an internal service's trust boundary explicit. [ClientBuilder::https_only] rejects an HTTP base URL at build time, rejects other HTTP request targets before connecting, and reports an HTTPS-to-HTTP redirect as a redirect error when it is being followed. An HTTP proxy origin remains valid because the request itself still uses HTTPS through the proxy tunnel.

Tez always selects rustls; dependency feature unification cannot silently switch its TLS backend. It does not expose an insecure certificate verifier, native-backend selection, or low-level TLS version and cipher configuration.

Build and send requests

Use the fluent builder for an ordinary request. It owns the detached request as you assemble it and borrows the client only so .send() can delegate to [Client::send]:

# async fn run(client: tez::Client) -> tez::Result<()> {
let response = client
    .post("/widgets")
    .header("x-request-id", "request-42")
    .query(&[("notify", true)])
    .form(&[("name", "tez")])
    .send()
    .await?;

let bytes = response.bytes().await?;
assert!(!bytes.is_empty());
# Ok(())
# }

Every final HTTP status produces a [Response]. Use response.status() to decide what success means for the operation.

Request bodies

Choose the body helper that describes what you are sending:

  • [RequestBuilder::body] accepts a [Body], bytes, text, or a byte vector and does not set a Content-Type.
  • [RequestBuilder::text], [RequestBuilder::json], and [RequestBuilder::form] replace the body and set their usual Content-Type unless you already supplied one.
  • [RequestBuilder::multipart] accepts an owned [Multipart] and sets its boundary-bearing Content-Type.
  • [Body::wrap] takes an owned standard [HttpBody] for streaming data and trailers. A wrapped body is one-shot.

The builder retains its first construction error. This keeps fluent code linear: call build or send once, then handle a single [Error].

Build multipart bodies from text, bytes, or a Tez body:

# async fn run(client: tez::Client, image: Vec<u8>) -> tez::Result<()> {
let upload = tez::Multipart::new()
    .text("description", "profile photo")
    .part(
        "photo",
        tez::Part::bytes(image)
            .file_name("profile.png")
            .media_type("image/png"),
    );

client
    .post("/photos")
    .multipart(upload)
    .send()
    .await?
    .discard()
    .await?;
# Ok(())
# }

Multipart forms made only from buffered parts are buffered. Tez sends an exact Content-Length and can replay them across a same-origin 307 or 308. Adding a wrapped streaming [Part::body] makes the form one-shot and streaming instead: it has no known total length, and a body-preserving redirect is returned without being followed. Tez generates the multipart boundary and its matching Content-Type. An earlier content type is replaced; a later explicit Content-Type is a request error because it could no longer describe the encoded body. [Part::body] includes data frames from its Tez body; HTTP trailers are not encoded as part data.

Response bodies

[Response::bytes], [Response::text], and [Response::json] each collect at most 16 MiB of body data exposed by the response, after automatic decompression when enabled. text validates UTF-8; json deserializes JSON without requiring a response Content-Type. These helpers consume the body. For large downloads or trailers, consume its frames directly:

# async fn run(response: tez::Response) -> tez::Result<()> {
use tez::BodyExt;

let mut body = response.stream();
while let Some(frame) = body.frame().await {
    let frame = frame?;
    if let Some(data) = frame.data_ref() {
        println!("received {} bytes", data.len());
    }
}
# Ok(())
# }

When the content is not needed, call [Response::discard] to drain it and make connection reuse possible.

[Response::content_length] reports the decoded body length when the transport knows it. It is not the literal Content-Length header, and compressed or streaming responses commonly return None. [Response::remote_addr] reports the final transport peer when available; when a proxy is in use, that address may belong to the proxy. Both values are captured with the response headers and remain stable while the one-shot body is consumed.

For structured streaming responses, call [Response::stream], frame the body into logical events, and deserialize each event as it arrives. events() infers ordinary JSON, NDJSON, JSON Lines, or server-sent event framing from the response Content-Type:

#[derive(serde::Deserialize)]
struct Update {
    message: String,
}

# async fn run(response: tez::Response) -> tez::Result<()> {
let mut events = response.stream().events().json::<Update>();
while let Some(update) = events.next().await? {
    println!("{}", update.message);
}
# Ok(())
# }

JSON documents produce one event at end-of-body. NDJSON and JSON Lines produce one event per completed record. Server-sent events produce one event per SSE dispatch, and the typed adapter treats the conventional [DONE] data marker as the end of the stream.

Keep the events undecoded when SSE metadata or non-JSON data matters:

# async fn run(response: tez::Response) -> tez::Result<()> {
let mut events = response.stream().events();
while let Some(event) = events.next().await? {
    println!("{:?}: {}", event.event(), event.data());
}
# Ok(())
# }

Raw requests

For explicit HTTP interoperability, build a standard request and send it through the same client pipeline:

# async fn run(client: tez::Client) -> tez::Result<()> {
let request = tez::HttpRequest::builder()
    .method(tez::Method::PUT)
    .uri("https://api.example.com/archive")
    .body(tez::Body::from("payload"))?;

let response = client.send(request).await?;
# Ok(())
# }

Defaults and limits

Clients are immutable and cheap to clone. Clones share one connection pool.

  • The default timeout is one 30-second deadline covering connection, upload, redirects, response headers, and body reads.
  • Override the deadline for one operation with [RequestBuilder::timeout]. Pass None to remove the deadline for that request; passing None to [ClientBuilder::timeout] makes the default unbounded.
  • Requests send User-Agent: tez/<version> by default. Set [ClientBuilder::user_agent] to replace it or [ClientBuilder::no_user_agent] to omit it; an explicit request header still takes precedence.
  • Configure shared authentication with [ClientBuilder::auth] and [auth::Authentication]. A request-level [RequestBuilder::auth] call replaces the client authentication; the selected implementation has final ownership of the headers it applies.
  • Configure one client default with [ClientBuilder::default_header] or replace the complete set with [ClientBuilder::default_headers]. Request headers override matching client defaults.
  • With the cookies Cargo feature, ClientBuilder::cookies enables one in-memory cookie jar shared by client clones. Cookie memory is disabled by default.
  • Default headers apply to every explicit request sent through the client, including a complete URL on another origin. Use separate clients for separate trust domains.
  • Clients connect directly by default. Set [ClientBuilder::proxy] to one [proxy::Policy]: [proxy::Policy::all] routes every HTTP(S) request through one explicit proxy, and feature-gated Policy::system opts into environment and supported operating-system discovery.
  • HTTPS uses rustls with platform certificate verification. Replace platform roots with an isolated PEM bundle using [ClientBuilder::trust_pem], configure mutual TLS with [ClientBuilder::identity_pem], and reject plaintext request targets with [ClientBuilder::https_only].
  • Tez returns redirect responses by default. Set [ClientBuilder::redirects] to [redirect::Policy::SameOrigin] to follow up to ten redirects within the original scheme, host, and effective port. A cross-origin redirect, or one that would replay a one-shot streaming body, remains a 3xx response. The eleventh same-origin redirect and an HTTPS-only downgrade are redirect errors. Tez never generates Referer.
  • Tez does not schedule retries by default. Set [ClientBuilder::retry] to [retry::Policy::Idempotent] to make at most three total attempts for idempotent methods with absent or buffered bodies. It retries connection failures before response headers and selected transient responses; streaming bodies and non-idempotent methods are never replayed. Every wait and attempt consumes the same total deadline; a wait that cannot fit in the remaining time returns a timeout immediately. Valid Retry-After values for 429 and 503 are honored for up to one minute; otherwise, Tez uses a short random delay before each retry.
  • HTTP/2 is enabled; gzip response decompression is the default Cargo feature.

Response compression

Tez advertises and automatically decodes only the response codecs selected through Tez Cargo features. Gzip is the sole default; Brotli, deflate, and Zstandard are opt-in.

Call [ClientBuilder::disable_compression] to disable advertising and decoding for every codec compiled into Tez. An explicit Accept-Encoding request header is still sent unchanged, while the response body and its Content-Encoding and Content-Length headers remain encoded. With compression enabled, an explicit Accept-Encoding controls request negotiation only: Tez still decodes responses that use a codec compiled into Tez. Tez does not automatically compress request bodies.

Tez owns HTTP transfer framing. A manually supplied Content-Length must match a body whose length is known exactly. Streaming bodies use the standard [HttpBody] contract through [Body::wrap]; Tez chooses the appropriate framing for them.

Tez exposes one total deadline at a time, not separate connect or read limits. Requests inherit the client deadline unless they override or disable it. An unbounded request has no total deadline and continues until completion, failure, or cancellation. The same total deadline covers safe transport recovery and configured retry waits.

Errors

[Error] is backend-neutral and supports stable questions such as is_request, is_authentication, is_connect, is_timeout, is_redirect, is_runtime, is_body, is_body_too_large, and is_decode.

Errors never expose a transport-specific error or caller-provided URL, header, or body data. Match only the category your application can act on:

# async fn run(client: tez::Client) -> tez::Result<()> {
match client.get("https://example.com/health").send().await {
    Ok(response) if response.status().is_success() => response.discard().await?,
    Ok(response) => {
        eprintln!("service returned {}", response.status());
        response.discard().await?;
    }
    Err(error) if error.is_timeout() => eprintln!("service was too slow"),
    Err(error) => return Err(error),
}
# Ok(())
# }

Runtime and compatibility

Tez supports Rust 1.94.1 and later. It is a native asynchronous client: sending a request or reading a body requires a Tokio runtime with I/O and time support. A missing runtime is reported through [Error::is_runtime] without exposing the runtime in Tez's stable error contract.

Deliberate 0.1 boundaries

Tez 0.1 intentionally has no service-specific retry rules or callbacks, persistent or custom cookie storage, insecure or low-level TLS controls, blocking execution, WebAssembly, protocol upgrades, or HTTP/3. That leaves room to design those capabilities later without making transport types part of the public contract.