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 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 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::{ServiceBuilder, ServiceExt as _};
use tower_http::ServiceBuilderExt as _;
use tower_http_client::{ResponseExt as _, ServiceExt as _};
use tower_reqwest::{into_reqwest_body, HttpClientLayer};
use wiremock::{
    matchers::{method, path},
    Mock, MockServer, ResponseTemplate,
};

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

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    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>| into_reqwest_body(body))
        .layer(HttpClientLayer)
        .service(reqwest::Client::new())
        .map_err(anyhow::Error::msg)
        .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, String, 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::{ServiceBuilder, ServiceExt as _};
use tower_http::ServiceBuilderExt as _;
use tower_http_client::{ResponseExt as _, ServiceExt as _};
use tower_reqwest::{into_reqwest_body, HttpClientLayer};
use wiremock::{
    matchers::{method, path},
    Mock, MockServer, ResponseTemplate,
};

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

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    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>| into_reqwest_body(body))
        .layer(HttpClientLayer)
        .service(reqwest::Client::new())
        .map_err(anyhow::Error::msg)
        .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 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 build(self) -> ClientRequest<'a, S, Err, (), RespBody>

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

§Errors

If erroneous data was passed during the query building process.

Source§

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

Source

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

Sends the request to the target URI.

§Panics
  • if the ReqBody is not valid body.

Trait Implementations§

Source§

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

Source§

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

Formats the value using the given formatter. Read more

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> !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> 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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
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.
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
Source§

impl<T> ErasedDestructor for T
where T: 'static,