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