dust

HTTP Client

Introduction

dust-framework provides an expressive HTTP client built on reqwest for making outgoing requests to external APIs and web services. It comes with sensible timeouts, configurable retries, and first-class error handling, and lets you fake outgoing responses in tests so your suite never touches the network.

All client functions and types live in the dust::http::client module.

Making requests

Start a request with get, post, put, patch, delete, or head, chain any options, and await it:

rust
use dust::http::client;let response = client::get("https://example.com/users").await?;

Awaiting sends the request and reads the entire response body. HTTP error statuses such as 404 or 500 still return Ok(response); ? fails only when the request could not be sent or timed out. To turn non-2xx statuses into errors automatically, see error handling.

You may send requests from handlers, console commands, queued jobs, and listeners. Inside tasks you spawn yourself, use dust::task::spawn rather than tokio::spawn so the task inherits your application's HTTP client context.

Responses

Response provides the following methods for inspecting the server's reply:

Method Returns
status() The StatusCode, which compares directly with integers (response.status() == 404).
successful() true for 2xx status codes.
redirect() true for 3xx status codes.
failed() true for 4xx or 5xx status codes.
client_error(), server_error() true for 4xx or 5xx status codes respectively.
header("x-name") The header value as Option<&str>.
headers() All response headers as &HeaderMap.
url() The final URL after following redirects.
bytes(), text() The response body as &Bytes or &str.
json::<T>() The body deserialized from JSON as Result<T, Error>.

Because the body is already buffered when the request resolves, json() and text() are synchronous. Decode JSON into your own struct or into serde_json::Value when you only need a few fields:

rust
use dust::http::client;use serde::Deserialize;#[derive(Deserialize)]pub struct GitHubUser {    pub login: String,    pub name: String,}let user: GitHubUser = client::get("https://api.github.com/users/taylorotwell")    .await?    .json()?;let raw: serde_json::Value = client::get("https://api.github.com/users/taylorotwell")    .await?    .json()?;let name = &raw["name"];

The client follows redirects automatically, so status(), headers(), and url() describe the final response rather than the first one. To stop following redirects, or to limit how many it follows, set a redirect policy through configure_transport.

Request data

Use json to send any Serialize value as a JSON request body:

rust
use dust::http::client;use serde_json::json;client::post("https://example.com/users")    .json(json!({ "name": "Steve", "role": "Network Administrator" }))    .await?;

Use query to append query string parameters from key-value pairs, a json! object, or a Serialize struct (omitting None fields automatically):

rust
use dust::http::client;use serde::Serialize;use serde_json::json;client::get("https://example.com/users")    .query([("name", "Taylor"), ("role", "admin")])    .await?;client::get("https://example.com/users")    .query(json!({ "name": "Taylor", "page": 2 }))    .await?;#[derive(Serialize)]struct Search {    q: String,    page: u32,    sort: Option<String>,}client::get("https://example.com/search")    .query(Search {        q: "dust".into(),        page: 2,        sort: None,    })    .await?;

Because Rust arrays require uniform element types, use json! or a Serialize struct when mixing value types, or chain multiple .query(..) calls.

Use form to send URL-encoded form bodies, body to send a raw body with an explicit content type, or body_file to stream a file directly from disk without buffering it in memory:

rust
client::post("https://example.com/users")    .form([("name", "Sara"), ("role", "Privacy Consultant")])    .await?;client::put("https://example.com/notes/1")    .body("Remember the milk.", "text/plain")    .await?;client::put("https://example.com/backups/latest")    .body_file("storage/app/backup.zip", "application/zip")    .await?;

Attaching files

Send multipart file uploads with attach, passing the form field name and an Attachment. Any form fields are included alongside the attached files:

rust
use dust::http::client::{self, Attachment};client::post("https://example.com/reports")    .attach("report", Attachment::from_path("storage/app/reports/q3.pdf"))    .form([("quarter", "Q3")])    .await?;

Attachment::from_path streams a file from disk, resolving relative paths against your application's base path. Attachment::from_data(bytes, "avatar.png") sends in-memory bytes under the given filename. Content types are inferred from the filename unless you override the filename or MIME type using named and mime:

rust
Attachment::from_path("storage/app/exports/1234.tmp")    .named("export.csv")    .mime("text/csv")

You can also forward an incoming UploadedFile directly from a handler:

rust
use dust::http::{UploadedFile, client};use dust::prelude::*;#[dust::input]#[validate(authenticated)]pub struct StorePhoto {    #[validate(required, image)]    photo: UploadedFile,}pub async fn store(Valid(form): Valid<StorePhoto>) -> dust::Result<Redirect> {    client::post("https://storage.example.com/photos")        .attach("photo", &form.photo)        .await?;    Ok(Redirect::back())}

Forward uploaded files inside the request handler itself rather than in a queued job or background task, because dust-framework cleans up temporary uploads once the request completes.

Headers

Add individual headers with header or multiple headers at once with headers. Setting a header replaces any earlier header of the same name:

rust
use dust::http::client;use serde_json::json;client::post("https://example.com/users")    .headers([("x-tenant", "acme"), ("x-locale", "en")])    .header("idempotency-key", "user-1234")    .json(json!({ "name": "Taylor" }))    .await?;

Set the Accept header using accept or the accept_json shorthand:

rust
client::get("https://example.com/users").accept_json().await?;client::get("https://example.com/reports/monthly")    .accept("text/csv")    .await?;

Authentication

You may authenticate outgoing requests using bearer tokens or HTTP basic authentication. To attach a bearer token to the request's Authorization header (Authorization: Bearer <token>), use the token method:

rust
use dust::http::client;let response = client::get("https://api.github.com/user")    .token("your-token")    .await?;

You may specify HTTP basic authentication credentials using the basic_auth method, which Base64-encodes the username and password into an Authorization: Basic header:

rust
use dust::http::client;let response = client::get("https://example.com/user")    .basic_auth("taylor@example.com", "secret")    .await?;

For APIs that expect a custom authentication scheme or an API key header, pass the header directly with header:

rust
use dust::http::client;let response = client::get("https://api.example.com/events")    .header("x-api-key", "your-api-key")    .await?;

In production applications, keep API keys and tokens out of your source code by storing them in a custom config section and injecting that section into your handler or service:

rust
// src/config/services.rsuse dust::config::Section;#[derive(Clone, Section)]pub struct GitHub {    #[env("GITHUB_TOKEN", required)]    pub token: String,}
rust
use dust::config::Section;use dust::http::client;use crate::config::services::GitHub;pub async fn show(github: Section<GitHub>) -> dust::Result<String> {    let response = client::get("https://api.github.com/user")        .token(&github.token)        .await?;    Ok(response.text().into_owned())}

dust-framework automatically marks Authorization, Proxy-Authorization, and Cookie header values as sensitive so they are redacted from debug output.

Base URLs and reusable requests

When calling the same API from multiple places, build a reusable PendingRequest template with client::base_url. Configure shared headers, tokens, and error handling once, then call get, post, and other verb methods with relative paths:

rust
use dust::config::Section;use dust::http::client::{self, PendingRequest};use dust::prelude::*;use serde_json::json;use crate::config::services::GitHub;fn github(config: &GitHub) -> PendingRequest {    client::base_url("https://api.github.com")        .token(&config.token)        .accept_json()        .ensure_successful()}pub async fn show(config: Section<GitHub>) -> dust::Result<Json<serde_json::Value>> {    let github = github(&config);    let user: serde_json::Value = github.get("/user").await?.json()?;    let repositories: serde_json::Value = github        .get("/user/repos")        .query([("per_page", 100)])        .await?        .json()?;    Ok(Json(json!({ "user": user, "repositories": repositories })))}

URL parameters

Avoid interpolating user input into URLs with format!, since values like ../admin can alter the target path. Instead, use {name} placeholders and pass values via url_parameters, which percent-encodes each parameter as a single path segment:

rust
use dust::http::client;client::get("https://api.github.com/repos/{owner}/{repo}")    .url_parameters([("owner", "dust"), ("repo", "framework")])    .await?;

url_parameters accepts pairs or a Serialize struct like query. Use {+name} to expand a parameter without path-segment encoding, such as a full base URL.

[!WARNING] url_parameters protects the path, not the host. If a host or full URL comes from user input, such as a webhook destination, validate it against an allowlist of schemes and domains before sending. Otherwise the client can be used to reach internal services that your application can see but the user cannot.

Timeouts

By default, requests wait up to 30 seconds for the full response and 10 seconds to establish a connection. Override the limit on a single request with timeout:

rust
use dust::http::client;use dust::prelude::*;client::get("https://example.com").timeout(3.seconds()).await?;

A timed-out request returns Error::Connection where error.is_timeout() is true. To change defaults application-wide, configure the client.

Retries

If you would like the HTTP client to automatically retry a request when a connection or non-2xx error occurs, use the retry method. Pass the maximum number of attempts along with either a fixed delay or a Backoff::exponential delay between attempts:

rust
use dust::http::client::{self, Backoff};use dust::prelude::*;use serde_json::json;client::post("https://example.com/webhooks")    .json(json!({ "event": "order.shipped" }))    .retry(3, 100.milliseconds())    .await?;client::get("https://example.com")    .retry(5, Backoff::exponential(100.milliseconds())) // 100ms, 200ms, 400ms, 800ms    .await?;

If every attempt fails, the client returns the final attempt's error.

When a 429 or 503 response includes a Retry-After header (either seconds or an HTTP date), dust-framework waits at least that long before retrying, provided the wait fits within the request's timeout or total_timeout. If the requested delay exceeds the remaining budget, the client stops retrying immediately and returns the error so you can handle it or re-queue the work.

Because each attempt uses its own timeout, multiple retries can exceed your handler's latency budget. Use total_timeout to cap the combined duration of all attempts and backoff delays:

rust
use dust::http::client::{self, Backoff};use dust::prelude::*;client::get("https://api.github.com/users/taylorotwell")    .timeout(2.seconds())    .retry(5, Backoff::exponential(200.milliseconds()))    .total_timeout(5.seconds())    .await?;

With total_timeout(5.seconds()), a 3-second Retry-After is honored when 3 seconds remain even though each individual attempt is capped at 2 seconds, while a 24-hour Retry-After fails immediately.

To retry only specific errors, pass a predicate to retry_when (attempts are 1-indexed):

rust
use dust::http::client::{self, Error};use dust::prelude::*;client::get("https://example.com")    .retry(3, 100.milliseconds())    .retry_when(|error, _attempt| matches!(error, Error::Connection(_)))    .await?;

[!WARNING] Retrying resends the same HTTP request. Only retry idempotent operations or requests protected by an idempotency key.

Error handling

By default, 4xx and 5xx responses return Ok(response). Call ensure_successful to convert any non-2xx status into Error::Status:

rust
use dust::http::client;let user: serde_json::Value = client::get("https://api.github.com/users/taylorotwell")    .ensure_successful()    .await?    .json()?;

You may also call response.ensure_successful()? after inspecting a response.

client::Error classifies failures into four variants:

Variant Cause
Error::Connection No response arrived (unreachable host, TLS failure, or timeout).
Error::Status Non-2xx status returned with ensure_successful or retry. Call error.response() to inspect it.
Error::Decode json() could not deserialize the body into the target type.
Error::Invalid Request could not be constructed (invalid URL or header).

Match on client::Error to handle specific failure cases:

rust
use dust::http::client::{self, Error};let request = client::get("https://api.github.com/users/taylorotwell")    .ensure_successful();match request.await {    Ok(response) => {        // ...    }    Err(Error::Connection(error)) if error.is_timeout() => {        // ...    }    Err(Error::Status(response)) if response.status() == 404 => {        // ...    }    Err(error) => return Err(error.into()),}

When converted via ? into dust::Error and returned from a handler, dust-framework reports the failure and responds with 500, logging the URL and beginning of the response body:

text
the HTTP request to https://api.example.com/users returned 404 Not Found: {"message":"Not found"}

Concurrent requests

When you need responses from multiple independent endpoints, send them concurrently with task::try_join! by calling .send() to obtain each request's future:

rust
use dust::http::client;use dust::task;let (repository, release) = task::try_join!(    client::get("https://api.github.com/repos/dust/framework").send(),    client::get("https://api.github.com/repos/dust/framework/releases/latest").send(),)?;

To bound concurrency across many requests, wrap them in a stream with .buffered(limit), which preserves input order:

rust
use dust::http::client;use dust::stream::{self, StreamExt};let responses: Vec<_> = stream::iter(["dust", "symfony", "rust-lang"])    .map(|org| {        client::get("https://api.github.com/orgs/{org}")            .url_parameters([("org", org)])            .send()    })    .buffered(5)    .collect()    .await;

Streaming responses

For large downloads or streaming APIs (such as AI chat completions), call stream() instead of awaiting the full body into memory. stream() resolves to a StreamedResponse as soon as response headers arrive.

Call chunks() to iterate over the response body one chunk of bytes at a time:

rust
use dust::http::client;use dust::stream::TryStreamExt;let mut chunks = client::get("https://example.com/exports/orders.csv")    .ensure_successful()    .stream()    .await?    .chunks();while let Some(chunk) = chunks.try_next().await? {    // Process each chunk of bytes...}

You can also pipe chunks() directly into file storage without buffering the download in memory:

rust
use dust::http::client;use dust::storage;let response = client::get("https://example.com/exports/orders.csv")    .ensure_successful()    .stream()    .await?;storage::disk("local")?    .write_stream("exports/orders.csv", response.chunks())    .await?;

StreamedResponse exposes the same status(), header(), and status helpers as Response. Consume its body once using chunks() for raw bytes, events() for server-sent events, or into_response() to buffer the remainder into a regular Response.

While streaming, the request timeout applies per chunk read rather than to the entire stream, so active long-lived streams do not time out.

Server-sent events

Many AI and realtime APIs stream responses as server-sent events. Calling events() yields each completed event, exposing data() and json().

For example, this handler proxies a streaming OpenAI completion to the browser as an EventStream response:

rust
use dust::config::Section;use dust::http::client;use dust::http::sse::EventStream;use dust::stream::TryStreamExt;use serde_json::json;use crate::config::services::OpenAi;pub async fn chat(openai: Section<OpenAi>) -> dust::Result<EventStream> {    let mut events = client::post("https://api.openai.com/v1/chat/completions")        .token(&openai.key)        .json(json!({            "model": "gpt-6.2-sol",            "stream": true,            "messages": [{ "role": "user", "content": "Write a haiku about Rust." }],        }))        .ensure_successful()        .stream()        .await?        .events();    Ok(EventStream::channel(async move |sender| {        while let Some(event) = events.try_next().await? {            if event.data() == "[DONE]" {                break;            }            let delta: serde_json::Value = event.json()?;            if let Some(content) = delta["choices"][0]["delta"]["content"].as_str() {                sender.send(content).await?;            }        }        Ok(())    }))}

Configuring the client

All top-level helpers in dust::http::client (client::get, client::post, client::base_url, and so on) dispatch requests through a single shared Client managed by your application. Sharing one Client lets requests across your application reuse pooled TCP and TLS connections, default timeouts, and request hooks.

Out of the box, the shared client uses the following defaults:

Setting Default
timeout 30 seconds
connect_timeout 10 seconds
user_agent dust-framework-Rust/<version>

To customize these defaults across your entire application, construct a Client and register it with app.instance inside .with_services in src/app.rs:

rust
use dust::http::client::Client;use dust::prelude::*;Application::configure()    .with_services(|app| {        app.instance(            Client::new()                .timeout(10.seconds())                .connect_timeout(5.seconds())                .user_agent("Acme/1.0")                .before_sending(|request| request.header("x-tenant", "acme"))                .after_response(|response| {                    tracing::debug!(status = %response.status(), "API response");                }),        );    })

Registering the client with app.instance (rather than a lazy singleton) ensures it is already available if other services send HTTP requests while your application boots.

Lifecycle hooks let you inspect or transform every outgoing request and response passing through a client. before_sending hooks run in the order they were registered before each request is dispatched, and after_response hooks observe every response that comes back, including each retry attempt and faked responses in tests.

If a before_sending hook should only apply to a specific API, inspect request.url() before modifying the request:

rust
use dust::http::client::Client;let client = Client::new().before_sending(|request| {    if request        .url()        .is_ok_and(|url| url.host_str() == Some("api.example.com"))    {        request.token("secret")    } else {        request    }});

Transport options

When you need to configure the underlying reqwest transport directly (such as adding custom CA certificates, configuring mutual TLS or an HTTP proxy, or changing the redirect policy), pass a closure to configure_transport. The closure receives reqwest's ClientBuilder and returns the configured builder.

Import reqwest types from dust::http::client::reqwest so your code always matches the version of reqwest bundled with dust-framework:

rust
use dust::http::client::{Client, reqwest};let client = Client::new().configure_transport(|transport| {    transport.redirect(reqwest::redirect::Policy::none())});

You may also call configure_transport on an individual request instead of the shared Client. Doing so creates an isolated connection pool for that request without affecting any other requests in your application.

Dedicated clients

Sometimes a single third-party integration needs its own User-Agent, stricter timeouts, custom TLS certificates, or a different redirect policy that you do not want applied to every outgoing request. In those cases, you can construct a dedicated Client and call get, post, base_url, and other request methods directly on it.

Because each Client maintains its own connection pool, avoid constructing a new one inside every request handler. Instead, wrap the dedicated Client in a service, register it once in src/app.rs, and inject it wherever it is needed:

rust
// src/services/reports.rsuse dust::http::client::Client;use dust::prelude::*;pub struct ReportsClient {    http: Client,}impl ReportsClient {    pub fn new() -> Self {        Self {            http: Client::new()                .timeout(60.seconds())                .user_agent("Acme Reports/1.0"),        }    }    pub async fn monthly(&self) -> dust::Result<String> {        let response = self            .http            .get("https://reports.example.com/monthly")            .ensure_successful()            .await?;        Ok(response.text().into_owned())    }}

Register the service in src/app.rs, then resolve it in a handler with Inject:

rust
// src/app.rsuse dust::prelude::*;use crate::services::reports::ReportsClient;Application::configure()    .with_services(|app| {        app.instance(ReportsClient::new());    })
rust
use dust::prelude::*;use crate::services::reports::ReportsClient;pub async fn show(reports: Inject<ReportsClient>) -> dust::Result<String> {    reports.monthly().await}

Even when requests are sent through a dedicated Client, client::fake() still intercepts them automatically in your tests.

Logging

The HTTP client emits a debug log entry on the dust::http::client target for every outgoing request, recording the method, URL, status, and duration_ms (or failure reason). Enable it with LOG_LEVEL=info,dust::http::client=debug. Credentials and query strings are automatically stripped from logged URLs and error messages so API keys are never leaked.

When distributed tracing is enabled, each attempt of a request creates a span of its own and sends its own W3C traceparent header, so a retried request shows one span per attempt.

Testing

Faking responses

Call client::fake() in your tests to intercept outgoing requests and return fake responses without touching the network. By default, every request receives an empty 200 response:

rust
use dust::http::client;use dust::testing::prelude::*;#[dust::test]async fn shows_a_github_profile(app: Application) {    let http = client::fake();    app.get("/profile").await.assert_ok();    http.assert_sent_count(1);}

Keep the returned fake handle alive while exercising your application; dropping it restores live network requests. Each test's fake is isolated to its application, so concurrent tests never interfere.

Pass URL patterns to .with(..) to return custom responses. Patterns match anywhere in the URL and support * wildcards, matching in registration order. Responses can be status codes, strings, JSON values, or client::response() builders:

rust
use serde_json::json;let http = client::fake()    .with(        "api.github.com/users/*",        json!({ "login": "taylorotwell", "name": "Taylor Otwell" }),    )    .with(        "api.stripe.com/*",        client::response()            .status(402)            .json(json!({ "error": "card_declined" })),    )    .with("example.com/health", 503)    .with("*", "Hello World");

Simulate network failures with client::failed_connection(), which returns Error::Connection:

rust
let http = client::fake().with("api.github.com/*", client::failed_connection());

Faked requests still execute client hooks and retry logic, without sleeping between retries.

[!NOTE] client::fake() intercepts requests sent through dust::http::client. Third-party SDKs that create their own internal HTTP client bypass this fake.

Response sequences

Return a sequence of different responses for the same URL pattern using client::sequence(), which is useful for testing retries:

rust
use dust::http::client;use serde_json::json;let http = client::fake().with(    "api.github.com/*",    client::sequence()        .push(client::failed_connection())        .push(503)        .push(json!({ "login": "taylorotwell" })),);

Once a sequence is exhausted, further requests fail with Error::Invalid unless you configure a fallback with when_empty. Like push, when_empty accepts any fake response value: a status code, string, JSON value, client::response() builder, client::failed_connection(), or a callback closure:

rust
let http = client::fake().with(    "api.github.com/*",    client::sequence().push("Hello World").when_empty(        client::response()            .status(404)            .json(json!({ "error": "not_found" })),    ),);

Fake callbacks

When the fake response depends on the incoming request, pass a closure to with. The closure receives a &Request and may return any fake response value (a status code, string, JSON value, or client::response() builder):

rust
use dust::http::client::{self, Request};let http = client::fake().with("api.example.com/*", |request: &Request| {    if request.has_header("authorization", "Bearer secret") {        200    } else {        401    }});

You can inspect any part of the outgoing request inside the callback using the same Request methods available in assertions.

Faking streamed responses

When code calls stream(), fake response bodies arrive line by line. For example, this test fakes an OpenAI server-sent events stream for the chat handler:

rust
use dust::http::client;use dust::testing::prelude::*;#[dust::test]async fn chat_replies_stream(app: Application) {    let http = client::fake().with(        "api.openai.com/*",        client::response()            .header("content-type", "text/event-stream")            .body(concat!(                "data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"}}]}\n\n",                "data: {\"choices\":[{\"delta\":{\"content\":\"lo!\"}}]}\n\n",                "data: [DONE]\n\n",            )),    );    app.get("/chat")        .await        .assert_ok()        .assert_see("data: Hel")        .assert_see("data: lo!");}

Inspecting requests

The fake records every outgoing request while active, including retries. Use assert_sent to verify that at least one recorded request matches a predicate:

rust
use dust::http::Method;http.assert_sent(|request| {    request.method() == Method::POST        && request.url() == "https://example.com/users"        && request.has_header("x-tenant", "acme")        && request.data()["name"] == "Taylor"});http.assert_not_sent(|request| request.url().contains("/posts"));http.assert_sent_count(5);http.assert_nothing_sent();

Request exposes the full outgoing request inside both assert_sent predicates and fake callbacks:

Method Description
method() The HTTP Method (GET, POST, etc.)
url() The full resolved URL, including base URL and query string
header(name) A header's text value as Option<&str>
has_header(name, value) Whether the header was sent with the given value
headers() All outgoing headers as a HeaderMap
body() The raw body bytes (&[u8])
data() Parsed JSON, form, or multipart text fields as serde_json::Value
json::<T>() Deserializes a JSON body into a typed struct
files() Attached multipart files (&[SentFile])
has_file(name, file_name) Whether a multipart file was attached with the given field and filename

For example, check multipart uploads with has_file:

rust
http.assert_sent(|request| request.has_file("report", "q3.pdf"));

For custom assertions, sent() returns all recorded requests and recorded() returns (Request, Response) pairs:

rust
let [(request, response)] = http.recorded().try_into().unwrap();assert_eq!(response.status(), 500);

Stray requests

Unmatched requests receive an empty 200 by default. Call prevent_stray_requests to fail any unexpected request with Error::Invalid:

rust
use serde_json::json;let http = client::fake()    .with("api.github.com/*", json!({ "login": "taylorotwell" }))    .prevent_stray_requests();

To allow specific live hosts (such as a local test server) while still blocking all other stray requests, use allow_stray_requests:

rust
use serde_json::json;let http = client::fake()    .with("api.github.com/*", json!({ "login": "taylorotwell" }))    .allow_stray_requests(["http://127.0.0.1:5000/*"]);