Skip to main content

HttpClientBuilder

Struct HttpClientBuilder 

Source
pub struct HttpClientBuilder { /* private fields */ }
Expand description

Builder for creating and configuring an HTTP client.

This builder follows the builder pattern, allowing you to customize various aspects of the HttpClient before creating it. Each configuration method returns self for method chaining.

By default, the builder is configured to use a standard pipeline that includes resilience features and observability (logging, metrics). This behavior can be modified with methods like minimal_pipeline or custom_pipeline.

§Construction

The builder instance is created using the HttpClient::builder_tokio method, or the free-standing custom::create_builder function for a custom transport.

Implementations§

Source§

impl HttpClientBuilder

Source

pub fn name(self, name: impl Into<Cow<'static, str>>) -> Self

Sets the name for the HTTP client.

The name is used in logging and metrics to identify the HTTP client instance. The name should follow the snake_case convention. By default, the client is named “http_client”.

Source

pub fn insecure_allow_http(self) -> Self

Allows insecure HTTP connections.

By default, the client only permits HTTPS connections. This method enables both HTTP and HTTPS requests. Use this for testing or internal networks only.

§Security

HTTP connections are unencrypted and can be intercepted. Use with caution!

Source

pub const fn connect_timeout(self, timeout: Duration) -> Self

Sets the connection timeout duration.

This sets how long to wait for a connection to be established before giving up. If not specified, a default value of 30 seconds will be used.

Source

pub fn connection_keep_alive(self, mode: ConnectionKeepAlive) -> Self

Configures how HTTP connections are kept alive.

Keep-alive maintains open or idle connections, reducing latency for subsequent requests by avoiding the overhead of establishing new TCP connections.

By default, this value is set to ConnectionKeepAlive::disabled.

Source

pub const fn response_body_options(self, options: HttpBodyOptions) -> Self

Sets the body options applied to every response produced by this client.

HttpBodyOptions controls body-level policies such as the buffer limit (maximum memory used when buffering via HttpBody::into_buffered) and the idle timeout between body frames.

By default, HttpBodyOptions::default() is used.

§Example
let options = HttpBodyOptions::default()
    .buffer_limit(4 * 1024 * 1024)
    .timeout(Duration::from_secs(30));

let client = builder.response_body_options(options).build();
Source

pub fn minimal_pipeline(self) -> Self

Enables the minimal pipeline mode for the client.

In this mode, the client uses only the Dispatch handler directly without any middleware, giving you complete control but without features like logging or metrics. This is useful when you need a streamlined client with minimal overhead.

Source

pub fn custom_pipeline<F, R>(self, factory: F) -> Self
where F: Fn(Dispatch, PipelineContext) -> R + Send + Sync + 'static, R: RequestHandler + 'static,

Configures the client to use a custom request pipeline instead of the default standard pipeline.

By default, the HTTP client uses a standard pipeline that includes common middleware for handling requests and responses. This method allows you to replace that pipeline with your own implementation, giving you complete control over request processing.

The factory function receives:

  • A Dispatch handler that handles the actual HTTP communication.
  • A PipelineContext with additional context information.

In your callback, you can provide your own stack of middleware with the dispatch handler at the bottom. Each middleware can add functionality like logging, authentication, caching, or custom request/response transformations. The middleware forms a chain where each one can process the request before passing it to the next handler in the chain.

§Examples
fn configure_builder(mut builder: HttpClientBuilder) -> HttpClientBuilder {
    builder.custom_pipeline(move |dispatch, ctx| {
        let stack = (
            Logging::layer(ctx.clock(), ctx.redaction_engine()),
            HttpRetry::layer("my_retry", ctx.resilience_context())
                .http_configure_defaults()
                .max_retry_attempts(1),
            dispatch,
        );
        stack.into_service()
    })
}
Source

pub fn tls_options(self, tls_options: TlsOptions) -> Self

Sets TLS options for this client.

Use TlsOptions::builder_rustls() for the rustls backend, or TlsOptions::builder_native_tls() for the platform native TLS backend. The rustls backend also supports mutual TLS (mTLS) via the builder’s client_identity method.

§Example
let client = builder
    .tls_options(TlsOptions::builder_rustls().build())
    .build();
Source

pub fn supported_http_versions(self, versions: &[Version]) -> Self

Sets the supported HTTP versions for the client.

The default is HTTP/1.1 and HTTP/2. This method allows you to change which HTTP protocol versions the client will use when connecting to servers.

Source

pub fn meter_provider(self, meter_provider: &dyn MeterProvider) -> Self

Sets a custom OpenTelemetry meter provider for the client.

The given MeterProvider is used to collect this client’s metrics. By default, the client uses the global meter provider; use this method to override it for this client instance.

§Performance

For thread-isolated runtimes, prefer a per-thread meter provider to avoid the lock contention that a global meter provider can cause.

Source

pub fn standard_pipeline<F>(self, configure: F) -> Self

Configures the standard pipeline with custom settings.

This method allows you to customize the standard pipeline (which includes resilience features and observability) by providing a configuration function that receives the current pipeline and returns a modified version.

See StandardRequestPipeline for more details on the defaults.

§Multiple Calls

Multiple consecutive calls to this method are additive - each call receives the pipeline configured by the previous call. However, if you switch to a different pipeline type (e.g., minimal_pipeline) and then call this method again, it will receive a fresh default StandardRequestPipeline rather than the previously configured one.

§Example
let client = builder
    .standard_pipeline(|pipeline, _context| {
        // Change the attempt timeout to 5 seconds
        pipeline.attempt_timeout(|timeout| timeout.timeout(Duration::from_secs(5)))
    })
    .build();
Source

pub fn base_uri(self, base_uri: impl Into<BaseUri>) -> Self

Sets the base URI for the client.

This setting overrides any endpoint set in the Uri you pass to the request methods, leading to three possible scenarios:

  • HttpClientBuilder::base_uri is set: the BaseUri on the request’s Uri is ignored and the client uses the provided BaseUri instead.
  • HttpClientBuilder::base_uri is not set, but the request Uri has a BaseUri: the client uses the BaseUri from the request’s Uri.
  • No endpoint is set on either side: the request fails with a validation HttpError.
let client = HttpClient::builder_fake(FakeHandler::default(), FakeDeps::default())
    .base_uri(BaseUri::from_static("https://example.com"))
    .build();

let response = client.get("/foo/bar").fetch().await?;
Source

pub fn router(self, router: Router) -> Self

Configures the Router used to resolve the destination BaseUri for each request.

A router can expose multiple alternative endpoints (e.g. a primary and one or more fallback endpoints). When the configured router has alternatives, the standard pipeline automatically enables retry/hedging on connection-unavailable errors so subsequent attempts can target a different endpoint.

This setting and HttpClientBuilder::base_uri are mutually exclusive shortcuts for the same underlying configuration; whichever is called last wins. Calling base_uri(uri) is equivalent to router(Router::fixed(uri)).

§Examples
let client = HttpClient::builder_fake(FakeHandler::default(), FakeDeps::default())
    .router(Router::fallback(
        BaseUri::from_static("https://primary.example.com/"),
        BaseUri::from_static("https://secondary.example.com/"),
    ))
    .build();
Source

pub fn http2_options(self, options: Http2Options) -> Self

Configures HTTP/2 options for the client.

This method allows you to customize HTTP/2-specific settings for connections created by the client. These settings only apply when the client negotiates HTTP/2 connections.

§Examples
let client = builder
    .http2_options(Http2Options::default().initial_max_send_streams(100))
    .build();
Source

pub fn connection_pool_options(self, options: ConnectionPoolOptions) -> Self

Configures connection pool options for the client.

This method allows you to configure how the client manages its connection pool. The connection pool reuses existing connections to reduce the overhead and latency of establishing new connections for each request.

§Examples
let client = builder
    .connection_pool_options(
        ConnectionPoolOptions::default()
            .max_connections(50)
            .connection_idle_timeout(Duration::from_secs(300)),
    )
    .build();
Source

pub fn redaction_engine(self, redaction_engine: &RedactionEngine) -> Self

Sets the redaction engine for the client.

The RedactionEngine is used to redact sensitive information from requests and responses. This is particularly useful for logging and telemetry, where you want to avoid exposing sensitive data such as authentication tokens, personal information, or other confidential information.

Source

pub fn build(self) -> HttpClient

Builds the configured HttpClient.

This finalizes all configuration and returns a ready-to-use client that reflects every setting applied to this builder.

Trait Implementations§

Source§

impl Clone for HttpClientBuilder

Source§

fn clone(&self) -> HttpClientBuilder

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for HttpClientBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more