minreq

repository·master·Indexed 42 days ago

https://github.com/neonmoe/minreq

A simple, minimal-dependency HTTP client for Rust designed to be lightweight with a small impact on executable size. Version 3.0.0 targets Rust 1.63 and provides optional features for JSON (via serde), HTTP proxies, and multiple TLS backends including rustls, native-tls, and OpenSSL.

Tokens
5.3K
Snippets
19
Records
23
Agent score
54%

What's inside minreq

  1. Install minreq

    master

    To use minreq in your Rust project, add it to your Cargo.toml. It is a minimal-dependency HTTP client that supports various optional features for JSON, proxies, and TLS implementations.

    [dependencies]
    minreq = "3.0.0"
  2. Configure minreq optional features

    master

    You can enable specific capabilities in minreq by selecting the corresponding features in your Cargo.toml.

    JSON Support

    • json-using-serde: Enables parsing JSON responses.

    URL and Domain Handling

    • punycode: Enables support for Unicode domains.
    • urlencoding: Enables percent-encoding for query parameters.

    Proxy Support

    • proxy: Enables support for HTTP proxies.

    HTTPS/TLS Implementations

    Choose one of the following TLS backends:

    • https-rustls (aliased as https): Uses rustls.
    • https-rustls-probe: Uses rustls with probing.
    • https-native-tls: Uses the system's native TLS implementation.
    • https-openssl: Uses a vendored version of OpenSSL.
    • https-openssl-probe: Uses OpenSSL with probing.
    # Example: Enabling JSON and rustls
    minreq = {
        version = "3.0.0",
        features = ["json-using-serde", "https-rustls"]
    }
  3. Use streaming responses with ResponseLazy

    master

    If you use Request::send_lazy(), you receive a ResponseLazy object instead of a standard Response.

    ResponseLazy implements std::io::Read, allowing you to stream the response body as it arrives from the network. This is useful for handling large payloads without loading the entire body into memory at once.

    To use it, you can read from it into a buffer or use read_to_end to collect it into a Vec<u8>.

    use std::io::Read;
    
    // send_lazy() returns ResponseLazy
    let mut response = minreq::get("http://example.com").send_lazy()?;
    
    // Stream the body into a vector
    let mut buffer = Vec::new();
    response.read_to_end(&mut buffer)?;
  4. Configure request timeouts

    master

    By default, minreq requests have no timeout. You can set a timeout in two ways:

    1. Per-request: Use .with_timeout(n) where n is the number of seconds.
    2. Environment Variable: Set MINREQ_TIMEOUT to the desired number of seconds. This is useful for setting a global timeout for an entire application.

    If both are used, the .with_timeout() value takes precedence.

    // Per-request timeout
    minreq::get("http://example.com").with_timeout(8).send();
  5. Create an HTTP request using method aliases

    master

    You can create a new Request using convenient top-level functions that correspond to HTTP methods. These functions initialize a Request with the specified method and URL, but do not send it immediately.

    Available aliases:

    • get(url)
    • head(url)
    • post(url)
    • put(url)
    • delete(url)
    • connect(url)
    • options(url)
    • trace(url)
    • patch(url)
    let request = minreq::post("http://example.com");
  6. Enable optional features in minreq

    master

    By default, minreq has no features enabled to keep dependencies minimal. You must explicitly enable functionality like HTTPS, JSON support, or Proxy support in your Cargo.toml.

    Available features:

    • https or https-rustls: Enables HTTPS using rustls. Required for https:// URLs. Returns HttpsFeatureNotEnabled error if missing.
    • https-rustls-probe: Enables rustls and auto-detects root certificates.
    • https-native-tls: Enables HTTPS using native-tls.
    • https-openssl: Enables HTTPS using a statically linked OpenSSL.
    • https-openssl-probe: Enables https-openssl and auto-detects root certificates.
    • json-using-serde: Enables JSON serialization/deserialization via serde_json. Provides with_json() on Request and json() on Response.
    • punycode: Enables support for non-ASCII domains. Returns PunycodeFeatureNotEnabled error if missing.
    • proxy: Enables HTTP proxy support.
    • urlencoding: Enables percent-encoding for URLs and parameters added via with_param.
    [dependencies]
    minreq = { version = "3.0.0", features = ["punycode", "https", "json-using-serde"] }
  7. Check minreq Minimum Supported Rust Version (MSRV)

    master

    The current major version (v3) of minreq targets Rust 1.63 (based on Debian bookworm).

    Important Note: This MSRV policy applies to minreq with no optional features enabled. Enabling specific optional features may require a more recent Rust version. Always check the project's MSRV CI job if you are working in a constrained environment.

  8. Use an HTTP proxy

    master

    To route requests through a proxy, enable the proxy feature, create a Proxy instance, and pass it to the request using .with_proxy(proxy).

    Supported formats:

    • host:port
    • user:password@proxy:host

    Note: Only HTTP CONNECT proxies are supported.

    #[cfg(feature = "proxy")]
    {
        let proxy = minreq::Proxy::new("localhost:1080")?;
        let response = minreq::post("http://example.com")
            .with_proxy(proxy)
            .send()?;
        println!("{}", response.as_str()?);
    }
  9. Read response headers

    master

    Access headers sent by the server via the .header("key") method on the Response object. Note that header keys are case-insensitive and are stored as lowercase strings internally.

    let response = minreq::get("http://example.com").send()?;
    assert!(response.header("content-type").unwrap().starts_with("text/html"));
  10. Send a basic GET request

    master

    Use minreq::get(url) to initiate a GET request. Call .send()? to execute it and receive a Response object. You can access the response body as a string using .as_str()?, the status code via .status_code, and the reason phrase via .reason_phrase.

    let response = minreq::get("http://example.com").send()?;
    assert!(response.as_str()?.contains("</html>"));
    assert_eq!(200, response.status_code);
    assert_eq!("OK", response.reason_phrase);