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
impl PendingRequest
Sourcepub fn new() -> PendingRequest
pub fn new() -> PendingRequest
A GET request without a URL, to configure as a template.
Sourcepub fn method(&self) -> &Method
pub fn method(&self) -> &Method
The request’s method, for inspecting it in a Client::before_sending hook.
Sourcepub fn url(&self) -> Result<Url, Error>
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");Sourcepub fn header_value(&self, name: &str) -> Option<&str>
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.
Sourcepub fn header_map(&self) -> &HeaderMap
pub fn header_map(&self) -> &HeaderMap
The configured headers, without the client’s default headers or the headers that the body generates.
Sourcepub fn body_bytes(&self) -> Option<Bytes>
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");Sourcepub fn get(&self, url: impl Into<String>) -> PendingRequest
pub fn get(&self, url: impl Into<String>) -> PendingRequest
Start a GET request to url with this request’s options.
Sourcepub fn head(&self, url: impl Into<String>) -> PendingRequest
pub fn head(&self, url: impl Into<String>) -> PendingRequest
Start a HEAD request to url with this request’s options.
Sourcepub fn post(&self, url: impl Into<String>) -> PendingRequest
pub fn post(&self, url: impl Into<String>) -> PendingRequest
Start a POST request to url with this request’s options.
Sourcepub fn put(&self, url: impl Into<String>) -> PendingRequest
pub fn put(&self, url: impl Into<String>) -> PendingRequest
Start a PUT request to url with this request’s options.
Sourcepub fn patch(&self, url: impl Into<String>) -> PendingRequest
pub fn patch(&self, url: impl Into<String>) -> PendingRequest
Start a PATCH request to url with this request’s options.
Sourcepub fn delete(&self, url: impl Into<String>) -> PendingRequest
pub fn delete(&self, url: impl Into<String>) -> PendingRequest
Start a DELETE request to url with this request’s options.
Sourcepub fn request(&self, method: Method, url: impl Into<String>) -> PendingRequest
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.
Sourcepub fn base_url(self, url: impl Into<String>) -> PendingRequest
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.
Sourcepub fn header(self, name: &str, value: impl AsRef<str>) -> PendingRequest
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?;Sourcepub fn headers<K, V>(
self,
headers: impl IntoIterator<Item = (K, V)>,
) -> PendingRequest
pub fn headers<K, V>( self, headers: impl IntoIterator<Item = (K, V)>, ) -> PendingRequest
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?;Sourcepub fn accept(self, content_type: impl AsRef<str>) -> PendingRequest
pub fn accept(self, content_type: impl AsRef<str>) -> PendingRequest
Ask for a response of this content type, by setting the Accept header.
Sourcepub fn accept_json(self) -> PendingRequest
pub fn accept_json(self) -> PendingRequest
Ask for a JSON response, by setting the Accept header to application/json.
Sourcepub fn token(self, token: impl AsRef<str>) -> PendingRequest
pub fn token(self, token: impl AsRef<str>) -> PendingRequest
Authenticate with a bearer token, which the request sends in the Authorization header.
Sourcepub fn basic_auth(
self,
username: impl AsRef<str>,
password: impl AsRef<str>,
) -> PendingRequest
pub fn basic_auth( self, username: impl AsRef<str>, password: impl AsRef<str>, ) -> PendingRequest
Authenticate with HTTP basic authentication.
Sourcepub fn user_agent(self, user_agent: impl AsRef<str>) -> PendingRequest
pub fn user_agent(self, user_agent: impl AsRef<str>) -> PendingRequest
Send this User-Agent header instead of the client’s.
Sourcepub fn query(self, query: impl Serialize) -> PendingRequest
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?;Sourcepub fn url_parameters(self, parameters: impl Serialize) -> PendingRequest
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?;Sourcepub fn json(self, body: impl Serialize) -> PendingRequest
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.
Sourcepub fn form(self, body: impl Serialize) -> PendingRequest
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.
Sourcepub fn body(
self,
body: impl Into<Bytes>,
content_type: impl AsRef<str>,
) -> PendingRequest
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?;Sourcepub fn body_file(
self,
path: impl AsRef<Path>,
content_type: impl AsRef<str>,
) -> PendingRequest
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?;Sourcepub fn attach(
self,
name: &str,
attachment: impl Into<Attachment>,
) -> PendingRequest
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?;Sourcepub fn timeout(
self,
timeout: impl Into<ZonedDateTimeArithmetic>,
) -> PendingRequest
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?;Sourcepub fn total_timeout(
self,
timeout: impl Into<ZonedDateTimeArithmetic>,
) -> PendingRequest
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?;Sourcepub fn configure_transport(
self,
configure: impl Fn(ClientBuilder) -> ClientBuilder + Send + Sync + 'static,
) -> PendingRequest
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?;Sourcepub fn retry(self, times: u32, backoff: impl Into<Backoff>) -> PendingRequest
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?;Sourcepub fn retry_when(
self,
when: impl Fn(&Error, u32) -> bool + Send + Sync + 'static,
) -> PendingRequest
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?;Sourcepub fn ensure_successful(self) -> PendingRequest
pub fn ensure_successful(self) -> PendingRequest
Return an Error::Status for a response outside 2xx, rather than the response.
Sourcepub fn send(
self,
) -> impl Future<Output = Result<Response, Error>> + Send + 'static
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.
Sourcepub fn stream(
self,
) -> impl Future<Output = Result<StreamedResponse, Error>> + Send + 'static
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
impl Clone for PendingRequest
Source§fn clone(&self) -> PendingRequest
fn clone(&self) -> PendingRequest
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for PendingRequest
impl Debug for PendingRequest
Source§impl Default for PendingRequest
impl Default for PendingRequest
Source§fn default() -> PendingRequest
fn default() -> PendingRequest
Source§impl IntoFuture for PendingRequest
impl IntoFuture for PendingRequest
Source§type IntoFuture = Pin<Box<dyn Future<Output = <PendingRequest as IntoFuture>::Output> + Send>>
type IntoFuture = Pin<Box<dyn Future<Output = <PendingRequest as IntoFuture>::Output> + Send>>
Source§fn into_future(self) -> <PendingRequest as IntoFuture>::IntoFuture
fn into_future(self) -> <PendingRequest as IntoFuture>::IntoFuture
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
impl Sync for PendingRequest
impl Unpin for PendingRequestwhere
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 PendingRequestwhere
*const ArcInner<Client> is !null: UnsafeUnpin,
PhantomData<ArcInner<Client>>: UnsafeUnpin,
*const u8 is !null: UnsafeUnpin,
PhantomData<Arc<dyn Fn(ClientBuilder) -> ClientBuilder + Sync + Send>>: UnsafeUnpin,
*const [u8] is !null: UnsafeUnpin,
PhantomData<[u8]>: UnsafeUnpin,
PhantomData<u8>: UnsafeUnpin,
PhantomData<String>: UnsafeUnpin,
PhantomData<(String, String)>: UnsafeUnpin,
*const [Pos] is !null: UnsafeUnpin,
PhantomData<[Pos]>: UnsafeUnpin,
PhantomData<Bucket<HeaderValue>>: UnsafeUnpin,
PhantomData<ExtraValue<HeaderValue>>: UnsafeUnpin,
*const u8: UnsafeUnpin,
Align8<*mut ()>: UnsafeUnpin,
&'static Vtable: UnsafeUnpin,
PhantomData<FilePart>: UnsafeUnpin,
*const ArcInner<dyn Fn(&Error, u32) -> bool + Sync + Send> is !null: UnsafeUnpin,
PhantomData<ArcInner<dyn Fn(&Error, u32) -> bool + Sync + Send>>: UnsafeUnpin,
*const ArcInner<dyn Error + Sync + Send> is !null: UnsafeUnpin,
PhantomData<ArcInner<dyn Error + Sync + Send>>: UnsafeUnpin,
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
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> ErasedDestructor for Twhere
T: 'static,
Source§impl<K> ForeignKey<K> for K
impl<K> ForeignKey<K> for K
Source§impl<T> FutureExt for T
impl<T> FutureExt for T
Source§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
Source§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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