1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
//! Per-request fluent builder.
//!
//! Obtain a [`RequestBuilder`] from [`Client::get`](crate::Client::get) (or other verbs), chain
//! path/query/body options, then call [`RequestBuilder::send`] or [`RequestBuilder::send_json`].
use std::collections::HashMap;
use std::time::Duration;
use bytes::Bytes;
use http::{HeaderMap, Method};
use indexmap::IndexMap;
use crate::auth::Auth;
use crate::backend::HttpBody;
use crate::cancel::CancellationToken;
use crate::client::Client;
use crate::error::Error;
use crate::response::Response;
use crate::retry::RetryPolicy;
use crate::url_build::QueryValue;
use crate::Result;
#[cfg(feature = "json")]
use crate::json_parser::JsonParserFn;
/// Fluent builder for a single HTTP request.
///
/// By default [`send`](Self::send) returns [`Response`] even on non-2xx status. Use
/// [`throw_on_error`](Self::throw_on_error)(`true`) to get `Err` from `send`, or use
/// [`send_json`](Self::send_json) which checks status before deserializing.
pub struct RequestBuilder<'a> {
pub(crate) client: &'a Client,
pub(crate) method: Method,
pub(crate) path: String,
pub(crate) params: HashMap<String, String>,
pub(crate) query: IndexMap<String, QueryValue>,
pub(crate) headers: HeaderMap,
pub(crate) body: HttpBody,
#[cfg(feature = "multipart")]
pub(crate) multipart: Option<crate::multipart::Form>,
pub(crate) timeout: Option<Duration>,
pub(crate) retry: Option<RetryPolicy>,
pub(crate) auth: Option<Auth>,
pub(crate) cancellation: Option<CancellationToken>,
pub(crate) throw_on_error: bool,
#[cfg(feature = "json")]
pub(crate) json_parser: Option<JsonParserFn>,
#[cfg(feature = "validate")]
pub(crate) validate_response: bool,
}
impl<'a> RequestBuilder<'a> {
/// Sets a path template parameter (`:key` in the path).
pub fn param(mut self, key: impl Into<String>, value: impl ToString) -> Self {
self.params.insert(key.into(), value.to_string());
self
}
/// Merges path parameters from a map.
pub fn params(mut self, params: HashMap<String, String>) -> Self {
self.params.extend(params);
self
}
/// Merges path parameters from an iterator.
pub fn params_iter(
mut self,
params: impl IntoIterator<Item = (impl Into<String>, impl ToString)>,
) -> Self {
for (k, v) in params {
self.params.insert(k.into(), v.to_string());
}
self
}
/// Adds a query string parameter.
pub fn query(mut self, key: impl Into<String>, value: impl ToString) -> Self {
self.query
.insert(key.into(), QueryValue::Scalar(value.to_string()));
self
}
/// Sets multiple query parameters preserving insertion order.
pub fn queries(mut self, query: IndexMap<String, QueryValue>) -> Self {
for (k, v) in query {
self.query.insert(k, v);
}
self
}
/// Serializes `value` as JSON and uses it as a query parameter (feature `json`).
#[cfg(feature = "json")]
pub fn query_json<T: serde::Serialize>(
mut self,
key: impl Into<String>,
value: &T,
) -> Result<Self> {
self.query
.insert(key.into(), QueryValue::from_serializable(value)?);
Ok(self)
}
/// Adds a request header.
pub fn header(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> Result<Self> {
let name = http::HeaderName::from_bytes(key.as_ref().as_bytes())
.map_err(|e| Error::Other(format!("invalid header name: {e}")))?;
let value = http::HeaderValue::from_str(value.as_ref())
.map_err(|e| Error::Other(format!("invalid header value: {e}")))?;
self.headers.insert(name, value);
Ok(self)
}
/// Sets a JSON request body (feature `json`).
#[cfg(feature = "json")]
pub fn json<T: serde::Serialize>(mut self, body: &T) -> Result<Self> {
let bytes = serde_json::to_vec(body).map_err(|e| Error::Other(e.to_string()))?;
self.body = HttpBody::Bytes(Bytes::from(bytes));
if !self.headers.contains_key(http::header::CONTENT_TYPE) {
self.headers.insert(
http::header::CONTENT_TYPE,
http::HeaderValue::from_static("application/json"),
);
}
Ok(self)
}
/// Sets a raw request body.
pub fn body(mut self, body: impl Into<Bytes>) -> Self {
self.body = HttpBody::Bytes(body.into());
self
}
/// URL-encoded form body (`application/x-www-form-urlencoded`).
pub fn form<I, K, V>(mut self, fields: I) -> Self
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<str>,
V: AsRef<str>,
{
let mut serializer = url::form_urlencoded::Serializer::new(String::new());
for (k, v) in fields {
serializer.append_pair(k.as_ref(), v.as_ref());
}
self.body = HttpBody::Bytes(Bytes::from(serializer.finish()));
if !self.headers.contains_key(http::header::CONTENT_TYPE) {
self.headers.insert(
http::header::CONTENT_TYPE,
http::HeaderValue::from_static("application/x-www-form-urlencoded"),
);
}
self
}
/// Multipart form body (requires the `multipart` feature).
///
/// Automatic retry is not supported when multipart bodies are used.
#[cfg(feature = "multipart")]
pub fn multipart(mut self, form: crate::multipart::Form) -> Self {
self.multipart = Some(form);
self.body = HttpBody::Empty;
self
}
/// Overrides the client default timeout for this request.
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
/// Overrides the client default retry policy for this request.
pub fn retry(mut self, policy: RetryPolicy) -> Self {
self.retry = Some(policy);
self
}
/// Overrides authentication for this request.
pub fn auth(mut self, auth: Auth) -> Self {
self.auth = Some(auth);
self
}
/// Sets bearer authentication for this request.
pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
self.auth = Some(Auth::bearer(token));
self
}
/// Cancels the in-flight request and retry sleeps when this token is triggered.
///
/// # Examples
///
/// ```no_run
/// # use better_fetch::{CancellationToken, Client, Result};
/// # use std::time::Duration;
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
/// let client = Client::new("https://api.example.com")?;
/// let token = CancellationToken::new();
/// let token_clone = token.clone();
/// tokio::spawn(async move {
/// tokio::time::sleep(Duration::from_millis(10)).await;
/// token_clone.cancel();
/// });
/// let err = client
/// .get("/slow")
/// .cancellation_token(token)
/// .send()
/// .await
/// .unwrap_err();
/// assert!(err.is_cancelled());
/// # Ok(())
/// # }
/// ```
pub fn cancellation_token(mut self, token: CancellationToken) -> Self {
self.cancellation = Some(token);
self
}
/// When `true`, [`send`](Self::send) returns `Err` on non-2xx HTTP status (like upstream `throw: true`).
pub fn throw_on_error(mut self, throw: bool) -> Self {
self.throw_on_error = throw;
self
}
/// Overrides the client's JSON parser for this request only.
///
/// See [`crate::json_parser`] for fast path vs two-step parsing.
#[cfg(feature = "json")]
pub fn json_parser<F>(mut self, f: F) -> Self
where
F: Fn(&Bytes) -> std::result::Result<serde_json::Value, String> + Send + Sync + 'static,
{
self.json_parser = Some(crate::json_parser::json_parser(f));
self
}
/// Overrides the client's JSON parser for this request only.
#[cfg(feature = "json")]
pub fn json_parser_fn(mut self, parser: JsonParserFn) -> Self {
self.json_parser = Some(parser);
self
}
/// Executes the request and returns the [`Response`].
///
/// Non-2xx responses are returned as `Ok(Response)` unless [`throw_on_error`](Self::throw_on_error)
/// is `true`. Deserialize JSON with [`Response::json`](crate::Response::json) or use
/// [`send_json`](Self::send_json) for a one-step typed result.
///
/// # Examples
///
/// ```no_run
/// # use better_fetch::{Client, Result};
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
/// let client = Client::new("https://api.example.com")?;
/// let response = client.get("/users/1").send().await?;
/// if response.is_success() {
/// println!("status {}", response.status());
/// }
/// # Ok(())
/// # }
/// ```
pub async fn send(self) -> Result<Response> {
self.client.execute(self).await
}
/// Executes the request and deserializes JSON on success (feature `json`).
///
/// Fails with [`Error::Http`](crate::Error::Http) or [`Error::Deserialize`](crate::Error::Deserialize)
/// on non-2xx or invalid JSON.
///
/// # Examples
///
/// ```no_run
/// # use better_fetch::{Client, Result};
/// # use serde::Deserialize;
/// # #[derive(Deserialize)]
/// # struct User { id: u64 }
/// # #[tokio::main]
/// # async fn main() -> Result<()> {
/// let client = Client::new("https://api.example.com")?;
/// let user: User = client.get("/users/:id").param("id", 1).send_json().await?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "json")]
#[must_use = "send the request with `.await` and handle the result"]
pub async fn send_json<T: serde::de::DeserializeOwned>(self) -> Result<T> {
self.send().await?.json::<T>().await
}
/// When `false`, [`send_json_validated`](Self::send_json_validated) only deserializes (no garde).
#[cfg(feature = "validate")]
pub fn validate_response(mut self, validate: bool) -> Self {
self.validate_response = validate;
self
}
/// `send` + [`Response::json_validated`](crate::Response::json_validated) (feature `validate`).
#[cfg(feature = "validate")]
pub async fn send_json_validated<T>(self) -> Result<T>
where
T: serde::de::DeserializeOwned + garde::Validate,
T::Context: Default,
{
if !self.validate_response {
return self.send_json().await;
}
self.send().await?.json_validated().await
}
}