Skip to main content

HttpClient

Struct HttpClient 

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

A runtime-agnostic HTTP client for sending HTTP requests.

HttpClient provides a high-level, fluent API for common HTTP operations over a configurable transport. It runs on the Tokio runtime by default, but any runtime and transport can be plugged in (see the custom module).

Tip: Cloning the client is cheap and results in instances that share the underlying connection pool and configuration.

§Examples

// Make a GET request
let response = client
    .get("https://example.com")
    .header(USER_AGENT, "MyApp/1.0")
    .fetch()
    .await?;

println!("Status: {}", response.status());

See crate-level documentation for more details on available configuration options and advanced usage scenarios.

Implementations§

Source§

impl HttpClient

Source

pub fn request( &self, method: impl TryInto<Method, Error: Into<Error>>, uri: impl TryInto<Uri, Error: Into<HttpError>>, ) -> HttpRequestBuilder<'_, Self>

Creates a request builder with the specified method and URI.

This is the most flexible way to build requests. For common HTTP methods like GET or POST, you can use the dedicated helper methods instead.

§Performance tip

While you can provide strings for the method and URI, using pre-created Method and Uri instances is more efficient as it avoids parsing overhead.

§Examples
use fetch::HttpClient;
// Using strings (convenient but with parsing overhead)
let response = client
    .request("GET", "https://example.com/api")
    .fetch()
    .await?;

// Using pre-parsed values (more efficient) and additional customization
// before fetching the response.
let method = http::Method::GET;
let uri = "https://example.com/api".parse::<http::Uri>()?;
let response = client
    .request(method, uri)
    .header(USER_AGENT, "MyApp/1.0")
    .fetch()
    .await?;
Source

pub fn get( &self, uri: impl TryInto<Uri, Error: Into<HttpError>>, ) -> HttpRequestBuilder<'_, Self>

Creates a GET request to the specified URI.

This is a convenient shortcut for request(Method::GET, uri).

§Performance tip

While you can provide a string for the URI, using a pre-created Uri instance is more efficient as it avoids parsing overhead.

§Examples
// Basic GET request
let response: HttpResponse = client.get("https://example.com").fetch().await?;

// GET with additional customization
let response: HttpResponse = client
    .get("https://api.example.com/users")
    .header("X-API-Key", "my-key")
    .fetch()
    .await?;

// Get response as text
let body: Response<String> = client.get("https://example.com").fetch_text().await?;
Source

pub fn post( &self, uri: impl TryInto<Uri, Error: Into<HttpError>>, ) -> HttpRequestBuilder<'_, Self>

Creates a POST request to the specified URI.

This is a convenient shortcut for request(Method::POST, uri).

§Performance tip

While you can provide a string for the URI, using a pre-created Uri instance is more efficient as it avoids parsing overhead.

§Examples

// Simple POST without a body
let response = client.post("https://api.example.com/users").fetch().await?;

// POST with text body and additional customization
let response = client
    .post("https://api.example.com/users")
    .header(USER_AGENT, "MyApp/1.0")
    .text("my-text")
    .fetch()
    .await?;
Source

pub fn delete( &self, uri: impl TryInto<Uri, Error: Into<HttpError>>, ) -> HttpRequestBuilder<'_, Self>

Creates a DELETE request to the specified URI.

This is a convenient shortcut for request(Method::DELETE, uri).

§Performance tip

While you can provide a string for the URI, using a pre-created Uri instance is more efficient as it avoids parsing overhead.

§Examples
// Delete a resource
let response = client
    .delete("https://api.example.com/users/123")
    .header("Authorization", "Bearer token")
    .fetch()
    .await?;
Source

pub fn head( &self, uri: impl TryInto<Uri, Error: Into<HttpError>>, ) -> HttpRequestBuilder<'_, Self>

Creates a HEAD request to the specified URI.

This is a convenient shortcut for request(Method::HEAD, uri). HEAD requests are similar to GET but return only headers without a body, useful for checking if a resource exists or has been modified.

§Performance tip

While you can provide a string for the URI, using a pre-created Uri instance is more efficient as it avoids parsing overhead.

§Examples
// Check if a resource exists without downloading it
let response = client
    .head("https://example.com/large-file.zip")
    .fetch()
    .await?;
Source

pub fn put( &self, uri: impl TryInto<Uri, Error: Into<HttpError>>, ) -> HttpRequestBuilder<'_, Self>

Creates a PUT request to the specified URI.

This is a convenient shortcut for request(Method::PUT, uri).

§Performance tip

While you can provide a string for the URI, using a pre-created Uri instance is more efficient as it avoids parsing overhead.

§Examples

// Simple PUT without a body
let response = client.put("https://api.example.com/users").fetch().await?;

// PUT with text body and additional customization
let response = client
    .put("https://api.example.com/users")
    .header(USER_AGENT, "MyApp/1.0")
    .text("my-text")
    .fetch()
    .await?;
Source

pub fn patch( &self, uri: impl TryInto<Uri, Error = UriError>, ) -> HttpRequestBuilder<'_, Self>

Creates a PATCH request to the specified URI.

This is a convenient shortcut for request(Method::PATCH, uri). PATCH requests are used for partial updates to resources, modifying only the specified fields rather than replacing the entire resource.

§Performance tip

While you can provide a string for the URI, using a pre-created Uri instance is more efficient as it avoids parsing overhead.

§Examples
// Partially update a resource with JSON payload
let response = client
    .patch("https://api.example.com/users/123")
    .header(USER_AGENT, "MyApp/1.0")
    .text("some content")
    .fetch()
    .await?;
Source

pub fn with_base_uri(&self, base_uri: BaseUri) -> Self

Returns a new HttpClient that uses the given base URI for all requests.

The new client shares this client’s pipeline and configuration; only the base URI differs. The original client is left unchanged.

Source§

impl HttpClient

Source

pub fn builder_fake( handler: impl Into<FakeHandler>, deps: impl Into<FakeDeps>, ) -> HttpClientBuilder

Creates a builder for a test-friendly HTTP client with a fake handler.

Unlike HttpClient::new_fake, this method returns a builder that can be further customized before constructing the client. Use this when you need more control over the client’s configuration in test scenarios.

§Examples
async fn example() -> Result<(), Box<dyn std::error::Error>> {
let client = HttpClient::builder_fake(StatusCode::NOT_FOUND, FakeDeps::default())
    .connect_timeout(Duration::from_millis(100))
    .insecure_allow_http()
    .build();

let response = client.get("http://test-url.local").fetch().await?;
assert_eq!(response.status(), StatusCode::NOT_FOUND);

Available only when compiled with the test-util feature.

Source

pub fn new_fake(handler: impl Into<FakeHandler>) -> Self

Creates a test-friendly HTTP client that uses mock responses.

This factory method provides a convenient way to create a client for testing without making real network requests. It automatically configures the builder with test-friendly defaults like allowing HTTP and using a minimal pipeline.

§Examples
// Create a client that always returns a specific status code
let client = HttpClient::new_fake(StatusCode::OK);

// Now you can use this client in tests without real network requests
let response = client.get("https://example.com").fetch().await?;
assert_eq!(response.status(), StatusCode::OK);

Available only when compiled with the test-util feature.

Source§

impl HttpClient

Source

pub fn builder_tokio(deps: impl Into<TokioDeps>) -> HttpClientBuilder

Creates a new HTTP client builder for the Tokio runtime.

This factory method provides a builder specifically configured for Tokio. Use this when working with Tokio-based applications.

Available only when compiled with the tokio feature and a TLS backend (rustls and/or native-tls).

Source

pub fn new_tokio() -> Self

Creates a new HTTP client for the Tokio runtime.

This method creates a fully configured HTTP client instance with the default configuration. Use builder_tokio if you want to customize the client (e.g. supply a custom TokioDeps) before creating it.

Available only when compiled with the tokio feature and a TLS backend (rustls and/or native-tls).

Trait Implementations§

Source§

impl AsRef<HttpBodyBuilder> for HttpClient

Source§

fn as_ref(&self) -> &HttpBodyBuilder

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for HttpClient

Source§

fn clone(&self) -> HttpClient

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 HttpClient

Source§

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

Formats the value using the given formatter. Read more
Source§

impl HasMemory for HttpClient

Source§

fn memory(&self) -> impl MemoryShared

Returns a sharing-compatible memory provider. Read more
Source§

impl Memory for HttpClient

Source§

fn reserve(&self, min_bytes: usize) -> BytesBuf

Reserves at least min_bytes bytes of memory capacity. Read more
Source§

impl Service<Request<HttpBody>> for HttpClient

Source§

type Out = Result<Response<HttpBody>, HttpError>

The output type returned by this service.
Source§

fn execute( &self, input: HttpRequest, ) -> impl Future<Output = Result<HttpResponse>> + Send

Processes the input and returns the output. Read more
Source§

impl ThreadAware for HttpClient

Source§

fn relocate(&mut self, source: Option<Affinity>, destination: Affinity)

Relocate this value in place to the destination affinity. 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<In, Out, T> DynamicServiceExt<In, Out> for T
where In: Send + 'static, Out: Send + 'static, T: Service<In, Out = Out> + 'static,

Source§

fn into_dynamic(self) -> DynamicService<In, Out>

Converts this service into a type-erased DynamicService.
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> HttpRequestBuilderExt for T

Source§

fn request_builder(&self) -> HttpRequestBuilder<'_, T>

Creates a new HTTP request builder associated with this handler.
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> MemoryShared for T
where T: Memory + Send + Sync + 'static,

Source§

impl<S> RequestHandler for S

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