reqwest/
lib.rs

1#![deny(missing_docs)]
2#![deny(missing_debug_implementations)]
3#![cfg_attr(docsrs, feature(doc_cfg))]
4#![cfg_attr(not(test), warn(unused_crate_dependencies))]
5#![cfg_attr(test, deny(warnings))]
6
7//! # reqwest
8//!
9//! The `reqwest` crate provides a convenient, higher-level HTTP
10//! [`Client`][client].
11//!
12//! It handles many of the things that most people just expect an HTTP client
13//! to do for them.
14//!
15//! - Async and [blocking] Clients
16//! - Plain bodies, [JSON](#json), [urlencoded](#forms), [multipart]
17//! - Customizable [redirect policy](#redirect-policies)
18//! - HTTP [Proxies](#proxies)
19//! - Uses [TLS](#tls) by default
20//! - Cookies
21//!
22//! The [`reqwest::Client`][client] is asynchronous. For applications wishing
23//! to only make a few HTTP requests, the [`reqwest::blocking`](blocking) API
24//! may be more convenient.
25//!
26//! Additional learning resources include:
27//!
28//! - [The Rust Cookbook](https://rust-lang-nursery.github.io/rust-cookbook/web/clients.html)
29//! - [Reqwest Repository Examples](https://github.com/seanmonstar/reqwest/tree/master/examples)
30//!
31//! ## Commercial Support
32//!
33//! For private advice, support, reviews, access to the maintainer, and the
34//! like, reach out for [commercial support][sponsor].
35//!
36//! ## Making a GET request
37//!
38//! For a single request, you can use the [`get`][get] shortcut method.
39//!
40//! ```rust
41//! # async fn run() -> Result<(), reqwest::Error> {
42//! let body = reqwest::get("https://www.rust-lang.org")
43//!     .await?
44//!     .text()
45//!     .await?;
46//!
47//! println!("body = {body:?}");
48//! # Ok(())
49//! # }
50//! ```
51//!
52//! **NOTE**: If you plan to perform multiple requests, it is best to create a
53//! [`Client`][client] and reuse it, taking advantage of keep-alive connection
54//! pooling.
55//!
56//! ## Making POST requests (or setting request bodies)
57//!
58//! There are several ways you can set the body of a request. The basic one is
59//! by using the `body()` method of a [`RequestBuilder`][builder]. This lets you set the
60//! exact raw bytes of what the body should be. It accepts various types,
61//! including `String` and `Vec<u8>`. If you wish to pass a custom
62//! type, you can use the `reqwest::Body` constructors.
63//!
64//! ```rust
65//! # use reqwest::Error;
66//! #
67//! # async fn run() -> Result<(), Error> {
68//! let client = reqwest::Client::new();
69//! let res = client.post("http://httpbin.org/post")
70//!     .body("the exact body that is sent")
71//!     .send()
72//!     .await?;
73//! # Ok(())
74//! # }
75//! ```
76//!
77//! ### Forms
78//!
79//! It's very common to want to send form data in a request body. This can be
80//! done with any type that can be serialized into form data.
81//!
82//! This can be an array of tuples, or a `HashMap`, or a custom type that
83//! implements [`Serialize`][serde].
84//!
85//! ```rust
86//! # use reqwest::Error;
87//! #
88//! # async fn run() -> Result<(), Error> {
89//! // This will POST a body of `foo=bar&baz=quux`
90//! let params = [("foo", "bar"), ("baz", "quux")];
91//! let client = reqwest::Client::new();
92//! let res = client.post("http://httpbin.org/post")
93//!     .form(&params)
94//!     .send()
95//!     .await?;
96//! # Ok(())
97//! # }
98//! ```
99//!
100//! ### JSON
101//!
102//! There is also a `json` method helper on the [`RequestBuilder`][builder] that works in
103//! a similar fashion the `form` method. It can take any value that can be
104//! serialized into JSON. The feature `json` is required.
105//!
106//! ```rust
107//! # use reqwest::Error;
108//! # use std::collections::HashMap;
109//! #
110//! # #[cfg(feature = "json")]
111//! # async fn run() -> Result<(), Error> {
112//! // This will POST a body of `{"lang":"rust","body":"json"}`
113//! let mut map = HashMap::new();
114//! map.insert("lang", "rust");
115//! map.insert("body", "json");
116//!
117//! let client = reqwest::Client::new();
118//! let res = client.post("http://httpbin.org/post")
119//!     .json(&map)
120//!     .send()
121//!     .await?;
122//! # Ok(())
123//! # }
124//! ```
125//!
126//! ## Redirect Policies
127//!
128//! By default, a `Client` will automatically handle HTTP redirects, having a
129//! maximum redirect chain of 10 hops. To customize this behavior, a
130//! [`redirect::Policy`][redirect] can be used with a `ClientBuilder`.
131//!
132//! ## Cookies
133//!
134//! The automatic storing and sending of session cookies can be enabled with
135//! the [`cookie_store`][ClientBuilder::cookie_store] method on `ClientBuilder`.
136//!
137//! ## Proxies
138//!
139//! **NOTE**: System proxies are enabled by default.
140//!
141//! System proxies look in environment variables to set HTTP or HTTPS proxies.
142//!
143//! `HTTP_PROXY` or `http_proxy` provide HTTP proxies for HTTP connections while
144//! `HTTPS_PROXY` or `https_proxy` provide HTTPS proxies for HTTPS connections.
145//! `ALL_PROXY` or `all_proxy` provide proxies for both HTTP and HTTPS connections.
146//! If both the all proxy and HTTP or HTTPS proxy variables are set the more specific
147//! HTTP or HTTPS proxies take precedence.
148//!
149//! These can be overwritten by adding a [`Proxy`] to `ClientBuilder`
150//! i.e. `let proxy = reqwest::Proxy::http("https://secure.example")?;`
151//! or disabled by calling `ClientBuilder::no_proxy()`.
152//!
153//! `socks` feature is required if you have configured socks proxy like this:
154//!
155//! ```bash
156//! export https_proxy=socks5://127.0.0.1:1086
157//! ```
158//!
159//! ## TLS
160//!
161//! A `Client` will use transport layer security (TLS) by default to connect to
162//! HTTPS destinations.
163//!
164//! - Additional server certificates can be configured on a `ClientBuilder`
165//!   with the [`Certificate`] type.
166//! - Client certificates can be added to a `ClientBuilder` with the
167//!   [`Identity`] type.
168//! - Various parts of TLS can also be configured or even disabled on the
169//!   `ClientBuilder`.
170//!
171//! See more details in the [`tls`] module.
172//!
173//! ## WASM
174//!
175//! The Client implementation automatically switches to the WASM one when the target_arch is wasm32,
176//! the usage is basically the same as the async api. Some of the features are disabled in wasm
177//! : [`tls`], [`cookie`], [`blocking`], as well as various `ClientBuilder` methods such as `timeout()` and `connector_layer()`.
178//!
179//! TLS and cookies are provided through the browser environment, so reqwest can issue TLS requests with cookies,
180//! but has limited configuration.
181//!
182//! ## Optional Features
183//!
184//! The following are a list of [Cargo features][cargo-features] that can be
185//! enabled or disabled:
186//!
187//! - **http2** *(enabled by default)*: Enables HTTP/2 support.
188//! - **default-tls** *(enabled by default)*: Provides TLS support to connect
189//!   over HTTPS.
190//! - **native-tls**: Enables TLS functionality provided by `native-tls`.
191//! - **native-tls-vendored**: Enables the `vendored` feature of `native-tls`.
192//! - **native-tls-alpn**: Enables the `alpn` feature of `native-tls`.
193//! - **rustls-tls**: Enables TLS functionality provided by `rustls`.
194//!   Equivalent to `rustls-tls-webpki-roots`.
195//! - **rustls-tls-manual-roots**: Enables TLS functionality provided by `rustls`,
196//!   without setting any root certificates. Roots have to be specified manually.
197//! - **rustls-tls-webpki-roots**: Enables TLS functionality provided by `rustls`,
198//!   while using root certificates from the `webpki-roots` crate.
199//! - **rustls-tls-native-roots**: Enables TLS functionality provided by `rustls`,
200//!   while using root certificates from the `rustls-native-certs` crate.
201//! - **blocking**: Provides the [blocking][] client API.
202//! - **charset** *(enabled by default)*: Improved support for decoding text.
203//! - **cookies**: Provides cookie session support.
204//! - **gzip**: Provides response body gzip decompression.
205//! - **brotli**: Provides response body brotli decompression.
206//! - **zstd**: Provides response body zstd decompression.
207//! - **deflate**: Provides response body deflate decompression.
208//! - **json**: Provides serialization and deserialization for JSON bodies.
209//! - **multipart**: Provides functionality for multipart forms.
210//! - **stream**: Adds support for `futures::Stream`.
211//! - **socks**: Provides SOCKS5 proxy support.
212//! - **hickory-dns**: Enables a hickory-dns async resolver instead of default
213//!   threadpool using `getaddrinfo`.
214//! - **system-proxy** *(enabled by default)*: Use Windows and macOS system
215//!   proxy settings automatically.
216//!
217//! ## Unstable Features
218//!
219//! Some feature flags require additional opt-in by the application, by setting
220//! a `reqwest_unstable` flag.
221//!
222//! - **http3** *(unstable)*: Enables support for sending HTTP/3 requests.
223//!
224//! These features are unstable, and experimental. Details about them may be
225//! changed in patch releases.
226//!
227//! You can pass such a flag to the compiler via `.cargo/config`, or
228//! environment variables, such as:
229//!
230//! ```notrust
231//! RUSTFLAGS="--cfg reqwest_unstable" cargo build
232//! ```
233//!
234//! ## Sponsors
235//!
236//! Support this project by becoming a [sponsor][].
237//!
238//! [hyper]: https://hyper.rs
239//! [blocking]: ./blocking/index.html
240//! [client]: ./struct.Client.html
241//! [response]: ./struct.Response.html
242//! [get]: ./fn.get.html
243//! [builder]: ./struct.RequestBuilder.html
244//! [serde]: http://serde.rs
245//! [redirect]: crate::redirect
246//! [Proxy]: ./struct.Proxy.html
247//! [cargo-features]: https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-features-section
248//! [sponsor]: https://seanmonstar.com/sponsor
249
250#[cfg(all(feature = "http3", not(reqwest_unstable)))]
251compile_error!(
252    "\
253    The `http3` feature is unstable, and requires the \
254    `RUSTFLAGS='--cfg reqwest_unstable'` environment variable to be set.\
255"
256);
257
258// Ignore `unused_crate_dependencies` warnings.
259// Used to pin the version.
260#[cfg(feature = "http3")]
261use slab as _;
262// Used in many features that they're not worth making it optional.
263use futures_core as _;
264use sync_wrapper as _;
265
266macro_rules! if_wasm {
267    ($($item:item)*) => {$(
268        #[cfg(target_arch = "wasm32")]
269        $item
270    )*}
271}
272
273macro_rules! if_hyper {
274    ($($item:item)*) => {$(
275        #[cfg(not(target_arch = "wasm32"))]
276        $item
277    )*}
278}
279
280pub use http::header;
281pub use http::Method;
282pub use http::{StatusCode, Version};
283pub use url::Url;
284
285// universal mods
286#[macro_use]
287mod error;
288// TODO: remove `if_hyper` if wasm has been migrated to new config system.
289if_hyper! {
290    mod config;
291}
292mod into_url;
293mod response;
294
295pub use self::error::{Error, Result};
296pub use self::into_url::IntoUrl;
297pub use self::response::ResponseBuilderExt;
298
299/// Shortcut method to quickly make a `GET` request.
300///
301/// See also the methods on the [`reqwest::Response`](./struct.Response.html)
302/// type.
303///
304/// **NOTE**: This function creates a new internal `Client` on each call,
305/// and so should not be used if making many requests. Create a
306/// [`Client`](./struct.Client.html) instead.
307///
308/// # Examples
309///
310/// ```rust
311/// # async fn run() -> Result<(), reqwest::Error> {
312/// let body = reqwest::get("https://www.rust-lang.org").await?
313///     .text().await?;
314/// # Ok(())
315/// # }
316/// ```
317///
318/// # Errors
319///
320/// This function fails if:
321///
322/// - native TLS backend cannot be initialized
323/// - supplied `Url` cannot be parsed
324/// - there was an error while sending request
325/// - redirect limit was exhausted
326pub async fn get<T: IntoUrl>(url: T) -> crate::Result<Response> {
327    Client::builder().build()?.get(url).send().await
328}
329
330fn _assert_impls() {
331    fn assert_send<T: Send>() {}
332    fn assert_sync<T: Sync>() {}
333    fn assert_clone<T: Clone>() {}
334
335    assert_send::<Client>();
336    assert_sync::<Client>();
337    assert_clone::<Client>();
338
339    assert_send::<Request>();
340    assert_send::<RequestBuilder>();
341
342    #[cfg(not(target_arch = "wasm32"))]
343    {
344        assert_send::<Response>();
345    }
346
347    assert_send::<Error>();
348    assert_sync::<Error>();
349
350    assert_send::<Body>();
351    assert_sync::<Body>();
352}
353
354if_hyper! {
355    #[cfg(test)]
356    #[macro_use]
357    extern crate doc_comment;
358
359    #[cfg(test)]
360    doctest!("../README.md");
361
362    pub use self::async_impl::{
363        Body, Client, ClientBuilder, Request, RequestBuilder, Response, Upgraded,
364    };
365    pub use self::proxy::{Proxy,NoProxy};
366    #[cfg(feature = "__tls")]
367    // Re-exports, to be removed in a future release
368    pub use tls::{Certificate, Identity};
369    #[cfg(feature = "multipart")]
370    pub use self::async_impl::multipart;
371
372
373    mod async_impl;
374    #[cfg(feature = "blocking")]
375    pub mod blocking;
376    mod connect;
377    #[cfg(feature = "cookies")]
378    pub mod cookie;
379    pub mod dns;
380    mod proxy;
381    pub mod redirect;
382    #[cfg(feature = "__tls")]
383    pub mod tls;
384    mod util;
385}
386
387if_wasm! {
388    mod wasm;
389    mod util;
390
391    pub use self::wasm::{Body, Client, ClientBuilder, Request, RequestBuilder, Response};
392    #[cfg(feature = "multipart")]
393    pub use self::wasm::multipart;
394}