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(¶ms) |
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 | //! `ALL_PROXY` or `all_proxy` provide proxies for both HTTP and HTTPS connections. |
145 | //! If both the all proxy and HTTP or HTTPS proxy variables are set the more specific |
146 | //! HTTP or HTTPS proxies take precedence. |
147 | //! |
148 | //! These can be overwritten by adding a [`Proxy`] to `ClientBuilder` |
149 | //! i.e. `let proxy = reqwest::Proxy::http("https://secure.example")?;` |
150 | //! or disabled by calling `ClientBuilder::no_proxy()`. |
151 | //! |
152 | //! `socks` feature is required if you have configured socks proxy like this: |
153 | //! |
154 | //! ```bash |
155 | //! export https_proxy=socks5://127.0.0.1:1086 |
156 | //! ``` |
157 | //! |
158 | //! ## TLS |
159 | //! |
160 | //! A `Client` will use transport layer security (TLS) by default to connect to |
161 | //! HTTPS destinations. |
162 | //! |
163 | //! - Additional server certificates can be configured on a `ClientBuilder` |
164 | //! with the [`Certificate`] type. |
165 | //! - Client certificates can be added to a `ClientBuilder` with the |
166 | //! [`Identity`] type. |
167 | //! - Various parts of TLS can also be configured or even disabled on the |
168 | //! `ClientBuilder`. |
169 | //! |
170 | //! See more details in the [`tls`] module. |
171 | //! |
172 | //! ## WASM |
173 | //! |
174 | //! The Client implementation automatically switches to the WASM one when the target_arch is wasm32, |
175 | //! the usage is basically the same as the async api. Some of the features are disabled in wasm |
176 | //! : [`tls`], [`cookie`], [`blocking`], as well as various `ClientBuilder` methods such as `timeout()` and `connector_layer()`. |
177 | //! |
178 | //! |
179 | //! ## Optional Features |
180 | //! |
181 | //! The following are a list of [Cargo features][cargo-features] that can be |
182 | //! enabled or disabled: |
183 | //! |
184 | //! - **http2** *(enabled by default)*: Enables HTTP/2 support. |
185 | //! - **default-tls** *(enabled by default)*: Provides TLS support to connect |
186 | //! over HTTPS. |
187 | //! - **native-tls**: Enables TLS functionality provided by `native-tls`. |
188 | //! - **native-tls-vendored**: Enables the `vendored` feature of `native-tls`. |
189 | //! - **native-tls-alpn**: Enables the `alpn` feature of `native-tls`. |
190 | //! - **rustls-tls**: Enables TLS functionality provided by `rustls`. |
191 | //! Equivalent to `rustls-tls-webpki-roots`. |
192 | //! - **rustls-tls-manual-roots**: Enables TLS functionality provided by `rustls`, |
193 | //! without setting any root certificates. Roots have to be specified manually. |
194 | //! - **rustls-tls-webpki-roots**: Enables TLS functionality provided by `rustls`, |
195 | //! while using root certificates from the `webpki-roots` crate. |
196 | //! - **rustls-tls-native-roots**: Enables TLS functionality provided by `rustls`, |
197 | //! while using root certificates from the `rustls-native-certs` crate. |
198 | //! - **blocking**: Provides the [blocking][] client API. |
199 | //! - **charset** *(enabled by default)*: Improved support for decoding text. |
200 | //! - **cookies**: Provides cookie session support. |
201 | //! - **gzip**: Provides response body gzip decompression. |
202 | //! - **brotli**: Provides response body brotli decompression. |
203 | //! - **zstd**: Provides response body zstd decompression. |
204 | //! - **deflate**: Provides response body deflate decompression. |
205 | //! - **json**: Provides serialization and deserialization for JSON bodies. |
206 | //! - **multipart**: Provides functionality for multipart forms. |
207 | //! - **stream**: Adds support for `futures::Stream`. |
208 | //! - **socks**: Provides SOCKS5 proxy support. |
209 | //! - **hickory-dns**: Enables a hickory-dns async resolver instead of default |
210 | //! threadpool using `getaddrinfo`. |
211 | //! |
212 | //! ## Unstable Features |
213 | //! |
214 | //! Some feature flags require additional opt-in by the application, by setting |
215 | //! a `reqwest_unstable` flag. |
216 | //! |
217 | //! - **http3** *(unstable)*: Enables support for sending HTTP/3 requests. |
218 | //! |
219 | //! These features are unstable, and experimental. Details about them may be |
220 | //! changed in patch releases. |
221 | //! |
222 | //! You can pass such a flag to the compiler via `.cargo/config`, or |
223 | //! environment variables, such as: |
224 | //! |
225 | //! ```notrust |
226 | //! RUSTFLAGS="--cfg reqwest_unstable" cargo build |
227 | //! ``` |
228 | //! |
229 | //! ## Sponsors |
230 | //! |
231 | //! Support this project by becoming a [sponsor][]. |
232 | //! |
233 | //! [hyper]: https://hyper.rs |
234 | //! [blocking]: ./blocking/index.html |
235 | //! [client]: ./struct.Client.html |
236 | //! [response]: ./struct.Response.html |
237 | //! [get]: ./fn.get.html |
238 | //! [builder]: ./struct.RequestBuilder.html |
239 | //! [serde]: http://serde.rs |
240 | //! [redirect]: crate::redirect |
241 | //! [Proxy]: ./struct.Proxy.html |
242 | //! [cargo-features]: https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-features-section |
243 | //! [sponsor]: https://seanmonstar.com/sponsor |
244 | |
245 | #[cfg (all(feature = "http3" , not(reqwest_unstable)))] |
246 | compile_error!( |
247 | "\ |
248 | The `http3` feature is unstable, and requires the \ |
249 | `RUSTFLAGS='--cfg reqwest_unstable'` environment variable to be set.\ |
250 | " |
251 | ); |
252 | |
253 | macro_rules! if_wasm { |
254 | ($($item:item)*) => {$( |
255 | #[cfg(target_arch = "wasm32" )] |
256 | $item |
257 | )*} |
258 | } |
259 | |
260 | macro_rules! if_hyper { |
261 | ($($item:item)*) => {$( |
262 | #[cfg(not(target_arch = "wasm32" ))] |
263 | $item |
264 | )*} |
265 | } |
266 | |
267 | pub use http::header; |
268 | pub use http::Method; |
269 | pub use http::{StatusCode, Version}; |
270 | pub use url::Url; |
271 | |
272 | // universal mods |
273 | #[macro_use ] |
274 | mod error; |
275 | mod into_url; |
276 | mod response; |
277 | |
278 | pub use self::error::{Error, Result}; |
279 | pub use self::into_url::IntoUrl; |
280 | pub use self::response::ResponseBuilderExt; |
281 | |
282 | /// Shortcut method to quickly make a `GET` request. |
283 | /// |
284 | /// See also the methods on the [`reqwest::Response`](./struct.Response.html) |
285 | /// type. |
286 | /// |
287 | /// **NOTE**: This function creates a new internal `Client` on each call, |
288 | /// and so should not be used if making many requests. Create a |
289 | /// [`Client`](./struct.Client.html) instead. |
290 | /// |
291 | /// # Examples |
292 | /// |
293 | /// ```rust |
294 | /// # async fn run() -> Result<(), reqwest::Error> { |
295 | /// let body = reqwest::get("https://www.rust-lang.org" ).await? |
296 | /// .text().await?; |
297 | /// # Ok(()) |
298 | /// # } |
299 | /// ``` |
300 | /// |
301 | /// # Errors |
302 | /// |
303 | /// This function fails if: |
304 | /// |
305 | /// - native TLS backend cannot be initialized |
306 | /// - supplied `Url` cannot be parsed |
307 | /// - there was an error while sending request |
308 | /// - redirect limit was exhausted |
309 | pub async fn get<T: IntoUrl>(url: T) -> crate::Result<Response> { |
310 | Client::builder().build()?.get(url).send().await |
311 | } |
312 | |
313 | fn _assert_impls() { |
314 | fn assert_send<T: Send>() {} |
315 | fn assert_sync<T: Sync>() {} |
316 | fn assert_clone<T: Clone>() {} |
317 | |
318 | assert_send::<Client>(); |
319 | assert_sync::<Client>(); |
320 | assert_clone::<Client>(); |
321 | |
322 | assert_send::<Request>(); |
323 | assert_send::<RequestBuilder>(); |
324 | |
325 | #[cfg (not(target_arch = "wasm32" ))] |
326 | { |
327 | assert_send::<Response>(); |
328 | } |
329 | |
330 | assert_send::<Error>(); |
331 | assert_sync::<Error>(); |
332 | |
333 | assert_send::<Body>(); |
334 | assert_sync::<Body>(); |
335 | } |
336 | |
337 | if_hyper! { |
338 | #[cfg (test)] |
339 | #[macro_use ] |
340 | extern crate doc_comment; |
341 | |
342 | #[cfg (test)] |
343 | doctest!("../README.md" ); |
344 | |
345 | pub use self::async_impl::{ |
346 | Body, Client, ClientBuilder, Request, RequestBuilder, Response, Upgraded, |
347 | }; |
348 | pub use self::proxy::{Proxy,NoProxy}; |
349 | #[cfg (feature = "__tls" )] |
350 | // Re-exports, to be removed in a future release |
351 | pub use tls::{Certificate, Identity}; |
352 | #[cfg (feature = "multipart" )] |
353 | pub use self::async_impl::multipart; |
354 | |
355 | |
356 | mod async_impl; |
357 | #[cfg (feature = "blocking" )] |
358 | pub mod blocking; |
359 | mod connect; |
360 | #[cfg (feature = "cookies" )] |
361 | pub mod cookie; |
362 | pub mod dns; |
363 | mod proxy; |
364 | pub mod redirect; |
365 | #[cfg (feature = "__tls" )] |
366 | pub mod tls; |
367 | mod util; |
368 | } |
369 | |
370 | if_wasm! { |
371 | mod wasm; |
372 | mod util; |
373 | |
374 | pub use self::wasm::{Body, Client, ClientBuilder, Request, RequestBuilder, Response}; |
375 | #[cfg (feature = "multipart" )] |
376 | pub use self::wasm::multipart; |
377 | } |
378 | |