http-request 23.3.0

http-request is a lightweight, efficient library for building, sending, and handling HTTP/HTTPS requests in Rust applications. It provides a simple and intuitive API, allowing developers to easily interact with web services, whether they use the "HTTP" or "HTTPS" protocol. The library supports various HTTP methods, custom headers, request bodies, timeout, automatic handling of redirects (including detecting redirect loops), and enhanced response body decoding (both automatic and manual), enabling fast and secure communication. Whether working with secure "HTTPS" connections or standard "HTTP" requests, the library is optimized for performance, minimal resource usage, and easy integration into Rust projects.
Documentation
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use super::*;

/// Default construction for [`HttpClientBuilder`].
impl Default for HttpClientBuilder {
    /// Creates an [`HttpClientBuilder`] with persistent keep-alive pooling enabled by default.
    ///
    /// # Returns
    ///
    /// - `Self` - Default client builder with `keep_alive = true`.
    #[inline]
    fn default() -> Self {
        let mut config: RequestConfig = RequestConfig::default();
        config.set_keep_alive(true);
        Self {
            base_url: None,
            default_headers: HashMap::new(),
            config,
            root_cert: None,
        }
    }
}

/// Inherent implementation of [`HttpClientBuilder`].
impl HttpClientBuilder {
    /// Creates a new [`HttpClientBuilder`] with keep-alive enabled by default.
    ///
    /// # Returns
    ///
    /// - `Self` - Fresh client builder.
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Configures a base URL prepended to relative paths passed to [`HttpClient`] request methods.
    ///
    /// # Arguments
    ///
    /// - `T` - Base URL such as `"https://api.example.com"` or `"http://127.0.0.1:8080/v1"`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn base_url<T>(mut self, url: T) -> Self
    where
        T: Into<String>,
    {
        let Self { base_url, .. } = &mut self;
        *base_url = Some(url.into());
        self
    }

    /// Adds a default header automatically included on every request created by this client.
    ///
    /// # Arguments
    ///
    /// - `K` - Header name (normalized to lowercase).
    /// - `V` - Header value.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn default_header<K, V>(mut self, key: K, value: V) -> Self
    where
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let Self {
            default_headers, ..
        } = &mut self;
        default_headers.insert(key.as_ref().to_ascii_lowercase(), value.as_ref().to_owned());
        self
    }

    /// Configures a default `Authorization: Bearer <token>` header for every request.
    ///
    /// # Arguments
    ///
    /// - `T` - Bearer token string.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn bearer_auth<T>(self, token: T) -> Self
    where
        T: AsRef<str>,
    {
        let value: String = format!("{BEARER_PREFIX}{}", token.as_ref());
        self.default_header(HEADER_AUTHORIZATION, value)
    }

    /// Configures a default `Authorization: Basic <credentials>` header for every request.
    ///
    /// # Arguments
    ///
    /// - `U` - Username string.
    /// - `P` - Password string.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn basic_auth<U, P>(self, username: U, password: P) -> Self
    where
        U: AsRef<str>,
        P: AsRef<str>,
    {
        let raw: String = format!("{}:{}", username.as_ref(), password.as_ref());
        let encoded: String = crate::utils::base64_encode(raw.as_bytes());
        let value: String = format!("{BASIC_PREFIX}{encoded}");
        self.default_header(HEADER_AUTHORIZATION, value)
    }

    /// Sets the default request timeout in milliseconds.
    ///
    /// # Arguments
    ///
    /// - `u64` - Timeout in milliseconds (`0` disables timeout).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn timeout(mut self, ms: u64) -> Self {
        let Self { config, .. } = &mut self;
        config.set_timeout(ms);
        self
    }

    /// Sets the default TCP connect timeout in milliseconds (`0` inherits `timeout`).
    ///
    /// # Arguments
    ///
    /// - `u64` - Connect timeout in milliseconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn connect_timeout(mut self, ms: u64) -> Self {
        let Self { config, .. } = &mut self;
        config.set_connect_timeout(ms);
        self
    }

    /// Sets the default bounded retry count for idempotent transient failures.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum retry attempts (`0` disables retries).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn retry(mut self, max_retries: usize) -> Self {
        let Self { config, .. } = &mut self;
        config.set_max_retries(max_retries);
        self
    }

    /// Enables or disables persistent HTTP keep-alive connection pooling.
    ///
    /// # Arguments
    ///
    /// - `bool` - `true` to pool persistent connections (default), `false` to close after each request.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn keep_alive(mut self, enabled: bool) -> Self {
        let Self { config, .. } = &mut self;
        config.set_keep_alive(enabled);
        self
    }

    /// Forces HTTP/1.1 for all requests built by this client.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn http1_1_only(mut self) -> Self {
        let Self { config, .. } = &mut self;
        config.set_http_version(HttpVersion::Http1_1);
        self
    }

    /// Forces HTTP/2 for all requests built by this client.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn http2_only(mut self) -> Self {
        let Self { config, .. } = &mut self;
        config.set_http_version(HttpVersion::Http2);
        self
    }

    /// Enables automatic 3xx redirect following with up to `max_redirects` hops.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum number of redirects to follow.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn redirect(mut self, max_redirects: usize) -> Self {
        let Self { config, .. } = &mut self;
        config.set_redirect(true);
        config.set_max_redirect_times(max_redirects);
        self
    }

    /// Disables automatic 3xx redirect following.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn no_redirect(mut self) -> Self {
        let Self { config, .. } = &mut self;
        config.set_redirect(false);
        self
    }

    /// Enables or disables automatic response body decompression (`gzip`/`deflate`/`br`).
    ///
    /// # Arguments
    ///
    /// - `bool` - `true` to automatically decode compressed response bodies.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn decode(mut self, enabled: bool) -> Self {
        let Self { config, .. } = &mut self;
        config.set_decode(enabled);
        self
    }

    /// Configures a proxy for all requests built by this client.
    ///
    /// # Arguments
    ///
    /// - `Proxy` - Proxy configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated client builder.
    pub fn proxy(mut self, proxy: Proxy) -> Self {
        let Self { config, .. } = &mut self;
        config.set_proxy(Some(proxy));
        self
    }

    /// Adds one or more PEM-encoded custom root CA certificates shared across all requests from this client.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Raw PEM-encoded X.509 certificate bytes.
    ///
    /// # Returns
    ///
    /// - `Result<Self, RequestError>` - Updated builder or an error on invalid PEM input.
    pub fn root_cert_pem(mut self, pem_bytes: &[u8]) -> Result<Self, RequestError> {
        let Self { root_cert, .. } = &mut self;
        let store: &mut RootCertStore = root_cert.get_or_insert_with(|| RootCertStore {
            roots: TLS_SERVER_ROOTS.to_vec(),
        });
        let _: usize = add_pem_certs_to_store(store, pem_bytes)?;
        Ok(self)
    }

    /// Finalizes the builder into a reusable, cheaply cloneable [`HttpClient`].
    ///
    /// # Returns
    ///
    /// - `HttpClient` - Constructed client instance.
    pub fn build(self) -> HttpClient {
        let Self {
            base_url,
            default_headers,
            config,
            root_cert,
        } = self;
        HttpClient {
            inner: Arc::new(HttpClientInner {
                base_url,
                default_headers,
                config,
                root_cert,
            }),
        }
    }
}

/// Default construction for [`HttpClient`].
impl Default for HttpClient {
    /// Creates a default [`HttpClient`] with persistent keep-alive pooling enabled.
    ///
    /// # Returns
    ///
    /// - `Self` - Default reusable HTTP client.
    #[inline]
    fn default() -> Self {
        HttpClientBuilder::new().build()
    }
}

/// Inherent implementation of [`HttpClient`].
impl HttpClient {
    /// Creates a new reusable [`HttpClient`] with persistent keep-alive pooling enabled by default.
    ///
    /// # Returns
    ///
    /// - `Self` - Fresh reusable HTTP client.
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns a [`HttpClientBuilder`] for customizing base URL, default headers, timeouts, TLS roots, and retries.
    ///
    /// # Returns
    ///
    /// - `HttpClientBuilder` - Fluent client builder.
    #[inline]
    pub fn builder() -> HttpClientBuilder {
        HttpClientBuilder::new()
    }

    /// Resolves `path_or_url` against the configured `base_url` when `path_or_url` is relative.
    ///
    /// # Arguments
    ///
    /// - `&str` - Absolute URL or relative path/query string.
    ///
    /// # Returns
    ///
    /// - `String` - Resolved request URL.
    fn resolve_target(&self, path_or_url: &str) -> String {
        let Self { inner } = self;
        if path_or_url.contains(SCHEME_SEPARATOR) {
            return path_or_url.to_owned();
        }
        let Some(ref base) = inner.base_url else {
            return path_or_url.to_owned();
        };
        let base_trimmed: &str = base.trim_end_matches('/');
        if path_or_url.is_empty() {
            return base_trimmed.to_owned();
        }
        if path_or_url.starts_with('/') || path_or_url.starts_with('?') {
            let mut out: String = String::with_capacity(base_trimmed.len() + path_or_url.len());
            out.push_str(base_trimmed);
            out.push_str(path_or_url);
            return out;
        }
        let mut out: String = String::with_capacity(base_trimmed.len() + 1 + path_or_url.len());
        out.push_str(base_trimmed);
        out.push('/');
        out.push_str(path_or_url);
        out
    }

    /// Creates a [`RequestBuilder`] pre-populated with this client's defaults for `method` and `path_or_url`.
    ///
    /// # Arguments
    ///
    /// - `Method` - HTTP method to send.
    /// - `T` - Absolute URL or path relative to `base_url`.
    ///
    /// # Returns
    ///
    /// - `RequestBuilder` - Pre-configured request builder ready for optional customization and `.send()` / `.send_async()`.
    pub fn request<T>(&self, method: Method, path_or_url: T) -> RequestBuilder
    where
        T: AsRef<str>,
    {
        let Self { inner } = self;
        let resolved_url: String = self.resolve_target(path_or_url.as_ref());
        let headers: HashMap<String, String> = if inner.default_headers.is_empty() {
            HashMap::new()
        } else {
            inner.default_headers.clone()
        };
        let tmp: Tmp = Tmp {
            visit_url: HashSet::new(),
            root_cert: inner.root_cert.clone(),
        };
        RequestBuilder {
            request: HttpRequest {
                method,
                url: resolved_url,
                headers,
                body: Body::empty(),
                config: inner.config.clone(),
                tmp,
            },
        }
    }

    /// Starts a `GET` request pre-configured with this client's defaults.
    ///
    /// # Arguments
    ///
    /// - `T` - Absolute URL or path relative to `base_url`.
    ///
    /// # Returns
    ///
    /// - `RequestBuilder` - Pre-configured `GET` request builder.
    #[inline]
    pub fn get<T>(&self, path_or_url: T) -> RequestBuilder
    where
        T: AsRef<str>,
    {
        self.request(Method::Get, path_or_url)
    }

    /// Starts a `POST` request pre-configured with this client's defaults.
    ///
    /// # Arguments
    ///
    /// - `T` - Absolute URL or path relative to `base_url`.
    ///
    /// # Returns
    ///
    /// - `RequestBuilder` - Pre-configured `POST` request builder.
    #[inline]
    pub fn post<T>(&self, path_or_url: T) -> RequestBuilder
    where
        T: AsRef<str>,
    {
        self.request(Method::Post, path_or_url)
    }

    /// Starts a `PUT` request pre-configured with this client's defaults.
    ///
    /// # Arguments
    ///
    /// - `T` - Absolute URL or path relative to `base_url`.
    ///
    /// # Returns
    ///
    /// - `RequestBuilder` - Pre-configured `PUT` request builder.
    #[inline]
    pub fn put<T>(&self, path_or_url: T) -> RequestBuilder
    where
        T: AsRef<str>,
    {
        self.request(Method::Put, path_or_url)
    }

    /// Starts a `DELETE` request pre-configured with this client's defaults.
    ///
    /// # Arguments
    ///
    /// - `T` - Absolute URL or path relative to `base_url`.
    ///
    /// # Returns
    ///
    /// - `RequestBuilder` - Pre-configured `DELETE` request builder.
    #[inline]
    pub fn delete<T>(&self, path_or_url: T) -> RequestBuilder
    where
        T: AsRef<str>,
    {
        self.request(Method::Delete, path_or_url)
    }

    /// Starts a `PATCH` request pre-configured with this client's defaults.
    ///
    /// # Arguments
    ///
    /// - `T` - Absolute URL or path relative to `base_url`.
    ///
    /// # Returns
    ///
    /// - `RequestBuilder` - Pre-configured `PATCH` request builder.
    #[inline]
    pub fn patch<T>(&self, path_or_url: T) -> RequestBuilder
    where
        T: AsRef<str>,
    {
        self.request(Method::Patch, path_or_url)
    }

    /// Starts a `HEAD` request pre-configured with this client's defaults.
    ///
    /// # Arguments
    ///
    /// - `T` - Absolute URL or path relative to `base_url`.
    ///
    /// # Returns
    ///
    /// - `RequestBuilder` - Pre-configured `HEAD` request builder.
    #[inline]
    pub fn head<T>(&self, path_or_url: T) -> RequestBuilder
    where
        T: AsRef<str>,
    {
        self.request(Method::Head, path_or_url)
    }

    /// Starts an `OPTIONS` request pre-configured with this client's defaults.
    ///
    /// # Arguments
    ///
    /// - `T` - Absolute URL or path relative to `base_url`.
    ///
    /// # Returns
    ///
    /// - `RequestBuilder` - Pre-configured `OPTIONS` request builder.
    #[inline]
    pub fn options<T>(&self, path_or_url: T) -> RequestBuilder
    where
        T: AsRef<str>,
    {
        self.request(Method::Options, path_or_url)
    }
}