Skip to main content

Crate tez

Crate tez 

Source
Expand description

§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:

FeatureEffect
gzip (default)Transparently decodes gzip responses.
brotliAdds Brotli (br) response decoding.
deflateAdds deflate response decoding.
zstdAdds Zstandard response decoding.
cookiesAdds an optional in-memory cookie jar.
system-proxyAdds 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

TypeResponsibility
ClientHolds shared policy and sends requests through a shared connection pool.
RequestBuilderBuilds one detached Request and borrows its client only for .send().
RequestA standard http::Request<Body> that can be inspected, stored, or sent later.
ResponseFinal response metadata plus a one-shot streaming Body.
Multipart and PartBuild 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:

client.get("https://example.com/users").send().await?;
client.get("/users?page=2").send().await?;

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

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::AuthProvider::bearer(token))
        .build()
}

Use AuthProvider::basic when one request needs different credentials:

client
    .get("/account")
    .auth(tez::AuthProvider::basic(username, password))
    .send()
    .await?
    .discard()
    .await?;

Request authentication replaces a client default. Within one builder, a later call that replaces Authorization wins. Basic usernames cannot contain :; Basic credentials cannot contain ASCII control characters, and Bearer tokens must be nonempty RFC 6750 tokens. Invalid credentials are reported only by build or send, without including the credential text. Values generated by the authentication helpers are marked sensitive for standard header debug output.

Authentication defaults, like every client default header, are also sent 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:

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:

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:

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());

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:

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:

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?;

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:

use tez::BodyExt;

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

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 a response declared as text/event-stream, consume its server-sent events directly. Event::json decodes one event’s complete data field:

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

let mut events = response.events()?;
while let Some(event) = events.next().await? {
    let update: Update = event.json()?;
    println!("{}", update.message);
}

§Raw requests

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

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?;

§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 Basic or Bearer authentication with ClientBuilder::auth and AuthProvider. A request-level RequestBuilder::auth call or explicit Authorization header takes precedence.
  • 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_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:

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),
}

§Runtime and compatibility

Tez supports Rust 1.91 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.

Re-exports§

pub use auth::AuthProvider;

Modules§

auth
Authentication credentials for Tez clients and requests.
header
Standard HTTP types used throughout Tez’s public API. HTTP header types
proxy
Routing policies for HTTP(S) proxies.
redirect
Redirect behavior configured for a client.
retry
Retry behavior configured for a client.

Structs§

Body
An owned body for Tez requests and responses. An owned body for Tez requests and responses.
Bytes
An efficient immutable byte buffer for buffered HTTP data. A cheaply cloneable and sliceable chunk of contiguous memory.
Client
The reusable HTTP client and its configuration builder. A reusable asynchronous HTTP client.
ClientBuilder
The reusable HTTP client and its configuration builder. A builder for configuring a Client.
Error
Tez’s backend-neutral error type and specialized result alias. An error from building, sending, or consuming an HTTP message.
Event
A decoded server-sent event and its one-shot response stream. One decoded server-sent event.
EventStream
A decoded server-sent event and its one-shot response stream. A one-shot stream of server-sent events.
Frame
The standard streaming body trait and frame types implemented by Body. A frame of any kind related to an HTTP stream (body).
HeaderMap
Standard HTTP types used throughout Tez’s public API. A specialized multimap for header names and values.
HeaderName
Standard HTTP types used throughout Tez’s public API. Represents an HTTP header field name
HeaderValue
Standard HTTP types used throughout Tez’s public API. Represents an HTTP header field value.
HttpRequest
The standard HTTP request type for explicit request construction before it carries a Body. Represents an HTTP request.
Method
Standard HTTP types used throughout Tez’s public API. The Request Method (VERB)
Multipart
Owned multipart request bodies and their parts. An owned multipart/form-data request body.
Ndjson
An experimental incremental reader for newline-delimited JSON responses. An experimental, one-shot reader for newline-delimited JSON responses.
Part
Owned multipart request bodies and their parts. One field in a Multipart request body.
RequestBuilder
Fluent construction of one request sent through a Client. A fluent builder for one request.
Response
A final response with streaming body access and bounded consumers. A final HTTP response with a one-shot streaming Tez body.
SizeHint
The standard streaming body trait and frame types implemented by Body. A Body size hint
StatusCode
Standard HTTP types used throughout Tez’s public API. An HTTP status code (status-code in RFC 9110 et al.).
Uri
Standard HTTP types used throughout Tez’s public API. The URI component of a request.
Version
Standard HTTP types used throughout Tez’s public API. Represents a version of the HTTP spec.

Traits§

BodyExt
Extensions for reading frames from a standard streaming body. An extension trait for http_body::Body adding various combinators and adapters
HttpBody
The standard streaming body trait and frame types implemented by Body. Trait representing a streaming body of a Request or Response.

Type Aliases§

Request
A detached standard HTTP request carrying a Tez Body.
Result
Tez’s backend-neutral error type and specialized result alias. A specialized std::result::Result for Tez operations.