Skip to main content

ClientRequestBuilder

Struct ClientRequestBuilder 

Source
pub struct ClientRequestBuilder<'a, S, Err, RespBody> { /* private fields */ }
Expand description

An http::Request builder.

Generally, this builder copies the behavior of the http::request::Builder, but unlike it, this builder contains a reference to the client and is able to send a constructed request. Also, this builder borrows most useful methods from the reqwest one.

Implementations§

Source§

impl<'a, S, Err, RespBody> ClientRequestBuilder<'a, S, Err, RespBody>

Source

pub fn method<T>(self, method: T) -> Self
where Method: TryFrom<T>, <Method as TryFrom<T>>::Error: Into<Error>,

Sets the HTTP method for this request.

By default this is GET.

Source

pub fn uri<U: IntoUri>(self, uri: U) -> Self
where Uri: TryFrom<U::TryInto>, <Uri as TryFrom<U::TryInto>>::Error: Into<Error>,

Sets the URI for this request

By default this is /.

Source

pub fn version(self, version: Version) -> Self

Set the HTTP version for this request.

By default this is HTTP/1.1.

Source

pub fn header<K, V>(self, key: K, value: V) -> Self

Appends a header to this request.

This function will append the provided key/value as a header to the internal HeaderMap being constructed. Essentially this is equivalent to calling HeaderMap::append.

Source

pub fn headers_mut(&mut self) -> Option<&mut HeaderMap<HeaderValue>>

Returns a mutable reference to headers of this request builder.

If builder contains error returns None.

Source

pub fn extension<T>(self, extension: T) -> Self
where T: Clone + Any + Send + Sync + 'static,

Adds an extension to this builder.

Source

pub fn extensions_mut(&mut self) -> Option<&mut Extensions>

Returns a mutable reference to the extensions of this request builder.

If builder contains error returns None.

Source

pub fn typed_header<T>(self, header: T) -> Self
where T: Header,

Available on crate feature typed-header only.

Appends a typed header to this request.

This function will append the provided header as a header to the internal HeaderMap being constructed. Essentially this is equivalent to calling headers::HeaderMapExt::typed_insert.

Source

pub fn body<NewReqBody>( self, body: impl Into<NewReqBody>, ) -> Result<ClientRequest<'a, S, Err, NewReqBody, RespBody>, Error>

“Consumes” this builder, using the provided body to return a constructed ClientRequest.

§Errors

Same as the http::request::Builder::body

Source

pub fn without_body(self) -> ClientRequest<'a, S, Err, Bytes, RespBody>

Consumes this builder and returns a constructed request without a body.

§Errors

If erroneous data was passed during the query building process.

Source

pub fn json<T: Serialize + ?Sized>( self, value: &T, ) -> Result<ClientRequest<'a, S, Err, Bytes, RespBody>, SetBodyError<Error>>

Available on crate feature json only.

Sets a JSON body for this request.

Additionally this method adds a CONTENT_TYPE header for JSON body. If you decide to override the request body, keep this in mind.

§Errors

If the given value’s implementation of serde::Serialize decides to fail.

§Examples
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use tower::{BoxError, ServiceBuilder, ServiceExt as _};
use tower_http::ServiceBuilderExt as _;
use tower_http_client::{ResponseExt as _, ServiceExt as _};
use tower_reqwest::HttpClientLayer;
use wiremock::{
    Mock, MockServer, ResponseTemplate,
    matchers::{method, path},
};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
struct SomeInfo {
    name: String,
    age: u32,
}

#[tokio::main]
async fn main() -> Result<(), BoxError> {
    let (_mock_server, mock_server_uri) = create_mock_server().await;

    eprintln!("-> Creating an HTTP client with Tower layers...");
    let mut client = ServiceBuilder::new()
        // Set the request body type.
        .map_request_body(|body: http_body_util::Full<Bytes>| reqwest::Body::wrap(body))
        .layer(HttpClientLayer)
        .service(reqwest::Client::new())
        .map_err(BoxError::from)
        .boxed_clone();

    let response = client
        .post(format!("{mock_server_uri}/test"))
        .json(&SomeInfo {
            name: "John".to_string(),
            age: 30,
        })?
        .send()
        .await?;

    // Check that the request was successful.
    assert_eq!(response.status(), 200);
    assert_eq!(
        response.body_reader().json::<String>().await?,
        "I am John and 30 years old"
    );

    Ok(())
}

async fn create_mock_server() -> (MockServer, String) {
    let mock_server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/test"))
        .respond_with(move |request: &wiremock::Request| {
            let info: SomeInfo = serde_json::from_slice(request.body.as_ref()).unwrap();

            eprintln!("Received request with info {info:?}",);
            ResponseTemplate::new(200)
                .set_body_json(format!("I am {} and {} years old", info.name, info.age))
        })
        .mount(&mock_server)
        .await;
    let mock_server_uri = mock_server.uri();
    (mock_server, mock_server_uri)
}
Source

pub fn form<T: Serialize + ?Sized>( self, form: &T, ) -> Result<ClientRequest<'a, S, Err, Bytes, RespBody>, SetBodyError<Error>>

Available on crate feature form only.

Sets a form body for this request.

Additionally this method adds a CONTENT_TYPE header for form body. If you decide to override the request body, keep this in mind.

§Errors

If the given value’s implementation of serde::Serialize decides to fail.

§Examples
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use tower::{BoxError, ServiceBuilder, ServiceExt as _};
use tower_http::ServiceBuilderExt as _;
use tower_http_client::{ResponseExt as _, ServiceExt as _};
use tower_reqwest::HttpClientLayer;
use wiremock::{
    Mock, MockServer, ResponseTemplate,
    matchers::{method, path},
};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
struct SomeInfo {
    name: String,
    age: u32,
}

#[tokio::main]
async fn main() -> Result<(), BoxError> {
    let (_mock_server, mock_server_uri) = create_mock_server().await;

    eprintln!("-> Creating an HTTP client with Tower layers...");
    let mut client = ServiceBuilder::new()
        // Set the request body type.
        .map_request_body(|body: http_body_util::Full<Bytes>| reqwest::Body::wrap(body))
        .layer(HttpClientLayer)
        .service(reqwest::Client::new())
        .map_err(BoxError::from)
        .boxed_clone();

    let response = client
        .post(format!("{mock_server_uri}/test"))
        .form(&SomeInfo {
            name: "John".to_string(),
            age: 30,
        })?
        .send()
        .await?;

    // Check that the request was successful.
    assert_eq!(response.status(), 200);
    assert_eq!(
        response.body_reader().json::<String>().await?,
        "I am John and 30 years old"
    );

    Ok(())
}

async fn create_mock_server() -> (MockServer, String) {
    let mock_server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/test"))
        .respond_with(move |request: &wiremock::Request| {
            let info: SomeInfo = serde_urlencoded::from_bytes(request.body.as_ref()).unwrap();

            eprintln!("Received request with info {info:?}",);
            ResponseTemplate::new(200)
                .set_body_json(format!("I am {} and {} years old", info.name, info.age))
        })
        .mount(&mock_server)
        .await;
    let mock_server_uri = mock_server.uri();
    (mock_server, mock_server_uri)
}
Source

pub fn query<T: Serialize + ?Sized>(self, value: &T) -> Result<Self, Error>

Available on crate feature query only.

Sets the query string of the URL.

Serializes the given value into a query string using serde_urlencoded and replaces the existing query string of the URL entirely. Any previously set query parameters are discarded.

§Notes
  • Duplicate keys are preserved as-is: .query(&[("foo", "a"), ("foo", "b")]) produces "foo=a&foo=b".

  • This method does not support a single key-value tuple directly. Use a slice like .query(&[("key", "val")]) instead. Structs and maps that serialize into key-value pairs are also supported.

§Errors

Returns a serde_urlencoded::ser::Error if the provided value cannot be serialized into a query string.

Source§

impl<'a, S, Err, RespBody> ClientRequestBuilder<'a, S, Err, RespBody>

Source

pub fn send<ReqBody>( self, ) -> impl Future<Output = Result<Response<RespBody>, Err>> + use<'a, S, Err, RespBody, ReqBody>
where S: Service<Request<ReqBody>, Response = Response<RespBody>, Error = Err>, S::Future: Send + 'static, S::Error: 'static, ReqBody: From<Bytes>,

Sends the request to the target URI without a body.

This is a shorthand for self.without_body().send(). The service’s request body type must implement From<Bytes>.

§Panics
  • if erroneous data was passed during the query building process.

Trait Implementations§

Source§

impl<S, Err, RespBody> Debug for ClientRequestBuilder<'_, S, Err, RespBody>

Source§

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

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

impl<S, Err, RespBody> From<ClientRequestBuilder<'_, S, Err, RespBody>> for Builder

Source§

fn from(builder: ClientRequestBuilder<'_, S, Err, RespBody>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<'a, S, Err, RespBody> !Freeze for ClientRequestBuilder<'a, S, Err, RespBody>

§

impl<'a, S, Err, RespBody> !RefUnwindSafe for ClientRequestBuilder<'a, S, Err, RespBody>

§

impl<'a, S, Err, RespBody> Send for ClientRequestBuilder<'a, S, Err, RespBody>
where S: Send, Err: Send, RespBody: Send,

§

impl<'a, S, Err, RespBody> Sync for ClientRequestBuilder<'a, S, Err, RespBody>
where S: Sync, Err: Sync, RespBody: Sync,

§

impl<'a, S, Err, RespBody> Unpin for ClientRequestBuilder<'a, S, Err, RespBody>
where Err: Unpin, RespBody: Unpin,

§

impl<'a, S, Err, RespBody> UnsafeUnpin for ClientRequestBuilder<'a, S, Err, RespBody>

§

impl<'a, S, Err, RespBody> !UnwindSafe for ClientRequestBuilder<'a, S, Err, RespBody>

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> Same for T

Source§

type Output = T

Should always be Self
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.