pub struct RequestBuilder { /* private fields */ }
Expand description
Request Builder
Provides an ergonomic way to chain the creation of a request.
This is generally accessed as the return value from surf::{method}()
,
however Request::builder
is also provided.
§Examples
use surf::http::{Method, mime::HTML, Url};
let mut request = surf::post("https://httpbin.org/post")
.body("<html>hi</html>")
.header("custom-header", "value")
.content_type(HTML)
.build();
assert_eq!(request.take_body().into_string().await.unwrap(), "<html>hi</html>");
assert_eq!(request.method(), Method::Post);
assert_eq!(request.url(), &Url::parse("https://httpbin.org/post")?);
assert_eq!(request["custom-header"], "value");
assert_eq!(request["content-type"], "text/html;charset=utf-8");
use surf::http::{Method, Url};
let url = Url::parse("https://httpbin.org/post")?;
let request = surf::Request::builder(Method::Post, url).build();
Implementations§
Source§impl RequestBuilder
impl RequestBuilder
Sourcepub fn new(method: Method, url: Url) -> Self
pub fn new(method: Method, url: Url) -> Self
Create a new instance.
This method is particularly useful when input URLs might be passed by third parties, and you don’t want to panic if they’re malformed. If URLs are statically encoded, it might be easier to use one of the shorthand methods instead.
§Examples
use surf::http::{Method, Url};
let url = Url::parse("https://httpbin.org/get")?;
let req = surf::RequestBuilder::new(Method::Get, url).build();
Sourcepub fn header(
self,
key: impl Into<HeaderName>,
value: impl ToHeaderValues,
) -> Self
pub fn header( self, key: impl Into<HeaderName>, value: impl ToHeaderValues, ) -> Self
Sets a header on the request.
§Examples
let req = surf::get("https://httpbin.org/get").header("header-name", "header-value").build();
assert_eq!(req["header-name"], "header-value");
Sourcepub fn content_type(self, content_type: impl Into<Mime>) -> Self
pub fn content_type(self, content_type: impl Into<Mime>) -> Self
Sets the Content-Type header on the request.
§Examples
let req = surf::post("https://httpbin.org/post").content_type(mime::HTML).build();
assert_eq!(req["content-type"], "text/html;charset=utf-8");
Sourcepub fn body(self, body: impl Into<Body>) -> Self
pub fn body(self, body: impl Into<Body>) -> Self
Sets the body of the request from any type with implements Into<Body>
, for example, any type with is AsyncRead
.
§Mime
The encoding is set to application/octet-stream
.
§Examples
use serde_json::json;
let mut req = surf::post("https://httpbin.org/post").body(json!({ "any": "Into<Body>"})).build();
assert_eq!(req.take_body().into_string().await.unwrap(), "{\"any\":\"Into<Body>\"}");
Sourcepub fn body_json(self, json: &impl Serialize) -> Result<Self>
pub fn body_json(self, json: &impl Serialize) -> Result<Self>
Pass JSON as the request body.
§Mime
The encoding is set to application/json
.
§Errors
This method will return an error if the provided data could not be serialized to JSON.
§Examples
#[derive(Deserialize, Serialize)]
struct Ip {
ip: String
}
let uri = "https://httpbin.org/post";
let data = &Ip { ip: "129.0.0.1".into() };
let res = surf::post(uri).body_json(data)?.await?;
assert_eq!(res.status(), 200);
Sourcepub fn body_string(self, string: String) -> Self
pub fn body_string(self, string: String) -> Self
Sourcepub fn body_bytes(self, bytes: impl AsRef<[u8]>) -> Self
pub fn body_bytes(self, bytes: impl AsRef<[u8]>) -> Self
Sourcepub async fn body_file(self, path: impl AsRef<Path>) -> Result<Self>
pub async fn body_file(self, path: impl AsRef<Path>) -> Result<Self>
Pass a file as the request body.
§Mime
The encoding is set based on the file extension using mime_guess
if the operation was
successful. If path
has no extension, or its extension has no known MIME type mapping,
then None
is returned.
§Errors
This method will return an error if the file couldn’t be read.
§Examples
let uri = "https://httpbin.org/post";
let res = surf::post(uri).body_file("./archive.tgz").await?.await?;
assert_eq!(res.status(), 200);
Sourcepub fn query(self, query: &impl Serialize) -> Result<Self, Error>
pub fn query(self, query: &impl Serialize) -> Result<Self, Error>
Set the URL querystring.
§Examples
#[derive(Serialize, Deserialize)]
struct Index {
page: u32
}
let query = Index { page: 2 };
let mut req = surf::get("https://httpbin.org/get").query(&query)?.build();
assert_eq!(req.url().query(), Some("page=2"));
assert_eq!(req.url().as_str(), "https://httpbin.org/get?page=2");
Sourcepub async fn recv_bytes(self) -> Result<Vec<u8>>
pub async fn recv_bytes(self) -> Result<Vec<u8>>
Submit the request and get the response body as bytes.
§Examples
let bytes = surf::get("https://httpbin.org/get").recv_bytes().await?;
assert!(bytes.len() > 0);
Sourcepub async fn recv_string(self) -> Result<String>
pub async fn recv_string(self) -> Result<String>
Submit the request and get the response body as a string.
§Examples
let string = surf::get("https://httpbin.org/get").recv_string().await?;
assert!(string.len() > 0);
Sourcepub async fn recv_json<T: DeserializeOwned>(self) -> Result<T>
pub async fn recv_json<T: DeserializeOwned>(self) -> Result<T>
Submit the request and decode the response body from json into a struct.
§Examples
#[derive(Deserialize, Serialize)]
struct Ip {
ip: String
}
let uri = "https://api.ipify.org?format=json";
let Ip { ip } = surf::get(uri).recv_json().await?;
assert!(ip.len() > 10);
Sourcepub async fn recv_form<T: DeserializeOwned>(self) -> Result<T>
pub async fn recv_form<T: DeserializeOwned>(self) -> Result<T>
Submit the request and decode the response body from form encoding into a struct.
§Errors
Any I/O error encountered while reading the body is immediately returned
as an Err
.
If the body cannot be interpreted as valid json for the target type T
,
an Err
is returned.
§Examples
#[derive(Deserialize, Serialize)]
struct Body {
apples: u32
}
let url = "https://api.example.com/v1/response";
let Body { apples } = surf::get(url).recv_form().await?;
Sourcepub fn middleware(self, middleware: impl Middleware) -> Self
pub fn middleware(self, middleware: impl Middleware) -> Self
Push middleware onto a per-request middleware stack.
Important: Setting per-request middleware incurs extra allocations.
Creating a Client
with middleware is recommended.
Client middleware is run before per-request middleware.
See the middleware submodule for more information on middleware.
§Examples
let res = surf::get("https://httpbin.org/get")
.middleware(surf::middleware::Redirect::default())
.await?;
Trait Implementations§
Source§impl Debug for RequestBuilder
impl Debug for RequestBuilder
Source§impl From<RequestBuilder> for Request
impl From<RequestBuilder> for Request
Source§fn from(builder: RequestBuilder) -> Request
fn from(builder: RequestBuilder) -> Request
Converts a surf::RequestBuilder
to a surf::Request
.
Source§impl Future for RequestBuilder
impl Future for RequestBuilder
Auto Trait Implementations§
impl Freeze for RequestBuilder
impl !RefUnwindSafe for RequestBuilder
impl Send for RequestBuilder
impl !Sync for RequestBuilder
impl Unpin for RequestBuilder
impl !UnwindSafe for RequestBuilder
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<F> FutureExt for F
impl<F> FutureExt for F
Source§fn catch_unwind(self) -> CatchUnwind<Self>where
Self: Sized + UnwindSafe,
fn catch_unwind(self) -> CatchUnwind<Self>where
Self: Sized + UnwindSafe,
Source§impl<F> FutureExt for F
impl<F> FutureExt for F
Source§fn catch_unwind(self) -> CatchUnwind<Self>where
Self: Sized + UnwindSafe,
fn catch_unwind(self) -> CatchUnwind<Self>where
Self: Sized + UnwindSafe,
Source§impl<T> FutureExt for T
impl<T> FutureExt for T
Source§fn delay(self, dur: Duration) -> DelayFuture<Self>where
Self: Sized,
fn delay(self, dur: Duration) -> DelayFuture<Self>where
Self: Sized,
Source§fn flatten(self) -> FlattenFuture<Self, <Self::Output as IntoFuture>::Future>
fn flatten(self) -> FlattenFuture<Self, <Self::Output as IntoFuture>::Future>
Source§fn race<F>(self, other: F) -> Race<Self, F>
fn race<F>(self, other: F) -> Race<Self, F>
Source§fn try_race<F, T, E>(self, other: F) -> TryRace<Self, F>
fn try_race<F, T, E>(self, other: F) -> TryRace<Self, F>
Source§fn join<F>(self, other: F) -> Join<Self, F>
fn join<F>(self, other: F) -> Join<Self, F>
Source§impl<T> FutureExt for T
impl<T> FutureExt for T
Source§fn map<U, F>(self, f: F) -> Map<Self, F>
fn map<U, F>(self, f: F) -> Map<Self, F>
Source§fn map_into<U>(self) -> MapInto<Self, U>
fn map_into<U>(self) -> MapInto<Self, U>
Source§fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
f
. Read moreSource§fn left_future<B>(self) -> Either<Self, B>
fn left_future<B>(self) -> Either<Self, B>
Source§fn right_future<A>(self) -> Either<A, Self>
fn right_future<A>(self) -> Either<A, Self>
Source§fn into_stream(self) -> IntoStream<Self>where
Self: Sized,
fn into_stream(self) -> IntoStream<Self>where
Self: Sized,
Source§fn flatten(self) -> Flatten<Self>
fn flatten(self) -> Flatten<Self>
Source§fn flatten_stream(self) -> FlattenStream<Self>
fn flatten_stream(self) -> FlattenStream<Self>
Source§fn fuse(self) -> Fuse<Self>where
Self: Sized,
fn fuse(self) -> Fuse<Self>where
Self: Sized,
poll
will never again be called once it has
completed. This method can be used to turn any Future
into a
FusedFuture
. Read moreSource§fn inspect<F>(self, f: F) -> Inspect<Self, F>
fn inspect<F>(self, f: F) -> Inspect<Self, F>
Source§fn catch_unwind(self) -> CatchUnwind<Self>where
Self: Sized + UnwindSafe,
fn catch_unwind(self) -> CatchUnwind<Self>where
Self: Sized + UnwindSafe,
Source§fn boxed<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>
fn boxed<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>
Source§fn boxed_local<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + 'a>>where
Self: Sized + 'a,
fn boxed_local<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + 'a>>where
Self: Sized + 'a,
Source§fn unit_error(self) -> UnitError<Self>where
Self: Sized,
fn unit_error(self) -> UnitError<Self>where
Self: Sized,
Future<Output = T>
into a
TryFuture<Ok = T, Error = ()
>.Source§fn never_error(self) -> NeverError<Self>where
Self: Sized,
fn never_error(self) -> NeverError<Self>where
Self: Sized,
Future<Output = T>
into a
TryFuture<Ok = T, Error = Never
>.