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