Skip to main content

PendingRequest

Struct PendingRequest 

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

An outgoing request that is still being configured.

Await the request, or call send, to send it. You may set its options in any order. A pending request without a URL is a template: call a verb on it, such as get, to start each request from the same options.

Invalid options, such as a header name with a space, don’t panic. Instead, sending the request returns Error::Invalid.

The request’s Debug output leaves out values that may hold secrets. It omits the Authorization, Proxy-Authorization, and Cookie headers, the credentials and query strings of its URLs, and the values of its query and URL parameters.

Implementations§

Source§

impl PendingRequest

Source

pub fn new() -> PendingRequest

A GET request without a URL, to configure as a template.

Source

pub fn method(&self) -> &Method

The request’s method, for inspecting it in a Client::before_sending hook.

Source

pub fn url(&self) -> Result<Url, Error>

The resolved URL, with the base URL, placeholders, and query parameters applied.

§Errors

Fails when the request has no URL, when the URL isn’t an absolute http or https URL, or when its placeholders can’t be filled.

use laravel::http::client;

let request = client::base_url("https://example.com/v1")
    .get("/users")
    .query([("page", 2)]);

assert_eq!(request.url()?.as_str(), "https://example.com/v1/users?page=2");
Source

pub fn header_value(&self, name: &str) -> Option<&str>

A configured header’s value, if the header is set and its value is text.

The client’s default headers and the headers that the body generates are added when the request is sent, so this method doesn’t see them.

Source

pub fn header_map(&self) -> &HeaderMap

The configured headers, without the client’s default headers or the headers that the body generates.

Source

pub fn body_bytes(&self) -> Option<Bytes>

The buffered body, for inspecting or signing a JSON, raw, or URL-encoded form body.

Returns empty bytes when the request has no body. Returns None for a file or multipart body, because those are streamed when the request is sent rather than buffered.

use laravel::http::{Method, client};

let request = client::post("https://example.com/users")
    .header("x-version", "v2")
    .form([("name", "Taylor Otwell")]);

assert_eq!(request.method(), Method::POST);
assert_eq!(request.header_value("x-version"), Some("v2"));
assert_eq!(request.header_map()["x-version"], "v2");
assert_eq!(request.body_bytes().unwrap(), "name=Taylor+Otwell");
Source

pub fn get(&self, url: impl Into<String>) -> PendingRequest

Start a GET request to url with this request’s options.

Source

pub fn head(&self, url: impl Into<String>) -> PendingRequest

Start a HEAD request to url with this request’s options.

Source

pub fn post(&self, url: impl Into<String>) -> PendingRequest

Start a POST request to url with this request’s options.

Source

pub fn put(&self, url: impl Into<String>) -> PendingRequest

Start a PUT request to url with this request’s options.

Source

pub fn patch(&self, url: impl Into<String>) -> PendingRequest

Start a PATCH request to url with this request’s options.

Source

pub fn delete(&self, url: impl Into<String>) -> PendingRequest

Start a DELETE request to url with this request’s options.

Source

pub fn request(&self, method: Method, url: impl Into<String>) -> PendingRequest

Start a request with any method to url with this request’s options.

The request uses a URL that starts with http:// or https:// as it is. Any other URL is relative to the base URL.

Source

pub fn base_url(self, url: impl Into<String>) -> PendingRequest

Resolve relative URLs against url.

For example, with a base URL of https://api.example.com/v1, a request to /users goes to https://api.example.com/v1/users.

Source

pub fn header(self, name: &str, value: impl AsRef<str>) -> PendingRequest

Add a header, replacing any with the same name.

laravel::http::client::get("https://example.com")
    .header("x-tenant", "acme")
    .await?;
Source

pub fn headers<K, V>( self, headers: impl IntoIterator<Item = (K, V)>, ) -> PendingRequest
where K: AsRef<str>, V: AsRef<str>,

Add several headers, replacing any with the same names.

laravel::http::client::get("https://example.com")
    .headers([("x-tenant", "acme"), ("x-request-id", "4f2a9c")])
    .await?;
Source

pub fn accept(self, content_type: impl AsRef<str>) -> PendingRequest

Ask for a response of this content type, by setting the Accept header.

Source

pub fn accept_json(self) -> PendingRequest

Ask for a JSON response, by setting the Accept header to application/json.

Source

pub fn token(self, token: impl AsRef<str>) -> PendingRequest

Authenticate with a bearer token, which the request sends in the Authorization header.

Source

pub fn basic_auth( self, username: impl AsRef<str>, password: impl AsRef<str>, ) -> PendingRequest

Authenticate with HTTP basic authentication.

Source

pub fn user_agent(self, user_agent: impl AsRef<str>) -> PendingRequest

Send this User-Agent header instead of the client’s.

Source

pub fn query(self, query: impl Serialize) -> PendingRequest

Add query parameters after any that the URL already has.

Pass pairs, a struct, or a map whose values are text, numbers, or booleans. The request leaves out None values. Each call adds to the earlier parameters, so you may pass pairs with different value types in separate calls. A list or an object nested inside a value fails the request with an Error::Invalid that names the key.

#[derive(serde::Serialize)]
struct Search {
    q: String,
    page: u32,
    sort: Option<String>,
}

laravel::http::client::get("https://example.com/users")
    .query([("name", "Taylor"), ("role", "admin")])
    .query([("page", 2)])
    .await?;

laravel::http::client::get("https://example.com/search")
    .query(Search { q: "rust".into(), page: 2, sort: None })
    .await?;
Source

pub fn url_parameters(self, parameters: impl Serialize) -> PendingRequest

Fill the URL’s {name} placeholders from pairs, a struct, or a map, as query accepts.

The request encodes each value as one path segment, so a value such as ../admin can’t change the path. A {+name} placeholder inserts its value as it is, such as a whole base URL. A placeholder without a value fails the request with Error::Invalid, and so does a segment value that’s empty, ., or ...

laravel::http::client::get("https://api.github.com/repos/{owner}/{repo}")
    .url_parameters([("owner", owner), ("repo", repo)])
    .await?;
Source

pub fn json(self, body: impl Serialize) -> PendingRequest

Send a JSON body, with a Content-Type of application/json.

A value that can’t be serialized as JSON fails the request with Error::Invalid.

Source

pub fn form(self, body: impl Serialize) -> PendingRequest

Send a form body, with a Content-Type of application/x-www-form-urlencoded.

Pass pairs, a struct, or a map, as query accepts. When the request has attachments, it sends the fields in a multipart form alongside the files.

Source

pub fn body( self, body: impl Into<Bytes>, content_type: impl AsRef<str>, ) -> PendingRequest

Send a raw body of the given content type.

laravel::http::client::put("https://example.com/photo")
    .body(photo, "image/jpeg")
    .await?;
Source

pub fn body_file( self, path: impl AsRef<Path>, content_type: impl AsRef<str>, ) -> PendingRequest

Send a file’s contents as the raw body.

The request streams the file from disk as it’s sent, rather than reading it into memory first. A relative path resolves against the application’s base path.

laravel::http::client::put("https://example.com/backups/latest")
    .body_file("storage/app/backup.zip", "application/zip")
    .await?;
Source

pub fn attach( self, name: &str, attachment: impl Into<Attachment>, ) -> PendingRequest

Attach a file under a form field, and send the request as a multipart form.

The request sends any form fields alongside the files. Pass an Attachment, or a file that the application received. To attach several files, call this method once for each file. You may use the same field name more than once to send several files under it.

use laravel::http::client::{self, Attachment};

client::post("https://example.com/photos")
    .attach("photo", Attachment::from_data(png, "taylor.png"))
    .attach("report", Attachment::from_path("storage/app/reports/q3.pdf"))
    .form([("caption", "At Laracon")])
    .await?;
Source

pub fn timeout( self, timeout: impl Into<ZonedDateTimeArithmetic>, ) -> PendingRequest

Wait this long for the whole response, including its body, such as 3.seconds().

This timeout replaces the client’s, which is 30 seconds by default. Zero means no limit.

use laravel::time::ToSpan;

laravel::http::client::get("https://example.com").timeout(3.seconds()).await?;
Source

pub fn total_timeout( self, timeout: impl Into<ZonedDateTimeArithmetic>, ) -> PendingRequest

Wait at most this long for the request and all its retries, including the waits between them, such as 5.seconds().

Each attempt waits for the shorter of its timeout and the time left. The request stops retrying when the next wait wouldn’t end in time. Zero, the default, means no limit.

use laravel::http::client::{self, Backoff};
use laravel::time::ToSpan;

client::get("https://example.com")
    .timeout(2.seconds())
    .retry(5, Backoff::exponential(200.milliseconds()))
    .total_timeout(5.seconds())
    .await?;
Source

pub fn configure_transport( self, configure: impl Fn(ClientBuilder) -> ClientBuilder + Send + Sync + 'static, ) -> PendingRequest

Configure a transport for this request only.

The callback runs after the client’s own configure_transport callbacks, and it doesn’t change the client or the request’s other options. Retries reuse the same transport, but each separate request builds its own. A request that a fake answers on every attempt doesn’t build a transport.

use laravel::http::client;

use client::reqwest::redirect::Policy;

let response = client::get("https://example.com")
    .token("secret")
    .configure_transport(|transport| transport.redirect(Policy::none()))
    .await?;
Source

pub fn retry(self, times: u32, backoff: impl Into<Backoff>) -> PendingRequest

Make up to times attempts, waiting backoff between them, while the request fails to connect or gets a status outside 2xx.

When every attempt fails, sending returns the last attempt’s Error, as though the request called ensure_successful. A times of zero makes one attempt. The request never retries when it’s invalid, or when a fake prevents stray requests and no pattern matches.

A 429 or 503 response may send a Retry-After header, in seconds or as an HTTP date. The header sets the shortest wait before the next attempt. If the header asks for longer than the request’s timeout, or for longer than the backoff when the request has no timeout, sending returns that response’s error without waiting. With a total_timeout, the request instead stops retrying when the next wait wouldn’t end before the total timeout.

use laravel::http::client::{self, Backoff};
use laravel::time::ToSpan;

client::get("https://example.com").retry(3, 100.milliseconds()).await?;
client::get("https://example.com")
    .retry(5, Backoff::exponential(100.milliseconds()))
    .await?;
Source

pub fn retry_when( self, when: impl Fn(&Error, u32) -> bool + Send + Sync + 'static, ) -> PendingRequest

Retry only when the callback returns true.

The callback receives the failed attempt’s error and the attempt’s number, starting at 1.

use laravel::http::client::{self, Error};
use laravel::time::ToSpan;

client::get("https://example.com")
    .retry(3, 100.milliseconds())
    .retry_when(|error, _attempt| matches!(error, Error::Connection(_)))
    .await?;
Source

pub fn ensure_successful(self) -> PendingRequest

Return an Error::Status for a response outside 2xx, rather than the response.

Source

pub fn send( self, ) -> impl Future<Output = Result<Response, Error>> + Send + 'static

Send the request and return its response.

The request uses the Client that started it, or the application’s client when a module helper started it. Awaiting the request does the same.

§Errors

Fails when the request is invalid or gets no response, after any retries. With ensure_successful or retry, it also fails for a response outside 2xx.

§Panics

Panics outside an application context. Also panics when a module helper started the request and the application’s Client isn’t registered as an instance.

Source

pub fn stream( self, ) -> impl Future<Output = Result<StreamedResponse, Error>> + Send + 'static

Send the request, and return a StreamedResponse as soon as the response begins, so you can read its body as it arrives.

Use this method for large downloads, and for APIs that send their answer in parts, such as server-sent events. Retries, ensure_successful, and fakes work as they do for send. When the request doesn’t enforce a successful status, the body stays unread for every status.

For a status error, the request reads up to 8 KiB of the body to explain the failure. If that read fails or times out, the error keeps the status, the headers, and the part of the body read so far.

§Errors

Fails as send does, before the body reaches the caller. A status error may hold only the start of the body rather than the whole body.

§Panics

Panics outside an application context. Also panics when a module helper started the request and the application’s Client isn’t registered as an instance.

Trait Implementations§

Source§

impl Clone for PendingRequest

Source§

fn clone(&self) -> PendingRequest

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 PendingRequest

Source§

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

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

impl Default for PendingRequest

Source§

fn default() -> PendingRequest

Returns the “default value” for a type. Read more
Source§

impl IntoFuture for PendingRequest

Source§

type Output = Result<Response, Error>

The output that the future will produce on completion.
Source§

type IntoFuture = Pin<Box<dyn Future<Output = <PendingRequest as IntoFuture>::Output> + Send>>

Which kind of future are we turning this into?
Source§

fn into_future(self) -> <PendingRequest as IntoFuture>::IntoFuture

Creates a future from a value. Read more

Auto Trait Implementations§

§

impl !Freeze for PendingRequest

§

impl !RefUnwindSafe for PendingRequest

§

impl !UnwindSafe for PendingRequest

§

impl Forget for PendingRequest

§

impl Move for PendingRequest

§

impl Send for PendingRequest
where Arc<Client>: Send, RawVecInner: Send, Arc<dyn Fn(ClientBuilder) -> ClientBuilder + Sync + Send>: Send, BoxRaw<[u8]>: Send, BoxRaw<[Pos]>: Send, Bytes: Send, Arc<dyn Fn(&Error, u32) -> bool + Sync + Send>: Send, Arc<dyn Error + Sync + Send>: Send,

§

impl Sync for PendingRequest
where Arc<Client>: Sync, RawVecInner: Sync, Arc<dyn Fn(ClientBuilder) -> ClientBuilder + Sync + Send>: Sync, BoxRaw<[u8]>: Sync, BoxRaw<[Pos]>: Sync, Bytes: Sync, Arc<dyn Fn(&Error, u32) -> bool + Sync + Send>: Sync, Arc<dyn Error + Sync + Send>: Sync,

§

impl Unpin for PendingRequest
where Arc<Client>: Unpin, *const u8 is !null: Unpin, Arc<dyn Fn(ClientBuilder) -> ClientBuilder + Sync + Send>: Unpin, Box<[u8]>: Unpin, Box<[Pos]>: Unpin, *const u8: Unpin, Align8<*mut ()>: Unpin, &'static Vtable: Unpin, Arc<dyn Fn(&Error, u32) -> bool + Sync + Send>: Unpin, Arc<dyn Error + Sync + Send>: Unpin,

§

impl UnsafeUnpin for PendingRequest

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> ErasedDestructor for T
where T: 'static,

Source§

impl<T> Fake for T

Source§

fn fake<U>(&self) -> U
where Self: FakeBase<U>,

Source§

fn fake_with_rng<U, R>(&self, rng: &mut R) -> U
where R: RngExt + ?Sized, Self: FakeBase<U>,

Source§

impl<T> FillValue<Option<T>> for T
where T: Send + 'static,

Source§

async fn fill(self) -> Result<Option<T>, Error>

Resolves the column’s value. Read more
Source§

impl<T> FillValue<T> for T
where T: Send + 'static,

Source§

async fn fill(self) -> Result<T, Error>

Resolves the column’s value. Read more
Source§

impl<K> ForeignKey<K> for K

Source§

fn key(&self) -> Option<&K>

Returns the key, or None when the field holds no key.
Source§

fn __from_key(key: K) -> K

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

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

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T, N> NotifiedBy<T> for N
where T: Notification<N>,

Source§

fn __routes(&self) -> Vec<Route>

Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + 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: Sized + 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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

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

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

fn try_from(value: U) -> Result<T, !>

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, V> UpdateValue<T> for V
where V: FillValue<T>,

Source§

fn __update<M, U>(self, column: Column<M, T>, update: U) -> U
where M: Model, U: Updates<M>, T: IntoExpr + Clone + Send + Sync + 'static,

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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