reqwest_wasm/
lib.rs

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.12")]
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 add 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//!
195//! [hyper]: http://hyper.rs
196//! [blocking]: ./blocking/index.html
197//! [client]: ./struct.Client.html
198//! [response]: ./struct.Response.html
199//! [get]: ./fn.get.html
200//! [builder]: ./struct.RequestBuilder.html
201//! [serde]: http://serde.rs
202//! [redirect]: crate::redirect
203//! [Proxy]: ./struct.Proxy.html
204//! [cargo-features]: https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-features-section
205
206macro_rules! if_wasm {
207    ($($item:item)*) => {$(
208        #[cfg(target_arch = "wasm32")]
209        $item
210    )*}
211}
212
213macro_rules! if_hyper {
214    ($($item:item)*) => {$(
215        #[cfg(not(target_arch = "wasm32"))]
216        $item
217    )*}
218}
219
220pub use http::header;
221pub use http::Method;
222pub use http::{StatusCode, Version};
223pub use url::Url;
224
225// universal mods
226#[macro_use]
227mod error;
228mod into_url;
229mod response;
230
231pub use self::error::{Error, Result};
232pub use self::into_url::IntoUrl;
233pub use self::response::ResponseBuilderExt;
234
235/// Shortcut method to quickly make a `GET` request.
236///
237/// See also the methods on the [`reqwest::Response`](./struct.Response.html)
238/// type.
239///
240/// **NOTE**: This function creates a new internal `Client` on each call,
241/// and so should not be used if making many requests. Create a
242/// [`Client`](./struct.Client.html) instead.
243///
244/// # Examples
245///
246/// ```rust
247/// # async fn run() -> Result<(), reqwest::Error> {
248/// let body = reqwest::get("https://www.rust-lang.org").await?
249///     .text().await?;
250/// # Ok(())
251/// # }
252/// ```
253///
254/// # Errors
255///
256/// This function fails if:
257///
258/// - native TLS backend cannot be initialized
259/// - supplied `Url` cannot be parsed
260/// - there was an error while sending request
261/// - redirect limit was exhausted
262pub async fn get<T: IntoUrl>(url: T) -> crate::Result<Response> {
263    Client::builder().build()?.get(url).send().await
264}
265
266fn _assert_impls() {
267    fn assert_send<T: Send>() {}
268    fn assert_sync<T: Sync>() {}
269    fn assert_clone<T: Clone>() {}
270
271    assert_send::<Client>();
272    assert_sync::<Client>();
273    assert_clone::<Client>();
274
275    assert_send::<Request>();
276    assert_send::<RequestBuilder>();
277
278    #[cfg(not(target_arch = "wasm32"))]
279    {
280        assert_send::<Response>();
281    }
282
283    assert_send::<Error>();
284    assert_sync::<Error>();
285}
286
287if_hyper! {
288    #[cfg(test)]
289    #[macro_use]
290    extern crate doc_comment;
291
292    #[cfg(test)]
293    doctest!("../README.md");
294
295    pub use self::async_impl::{
296        Body, Client, ClientBuilder, Request, RequestBuilder, Response, Upgraded,
297    };
298    pub use self::proxy::Proxy;
299    #[cfg(feature = "__tls")]
300    // Re-exports, to be removed in a future release
301    pub use tls::{Certificate, Identity};
302    #[cfg(feature = "multipart")]
303    pub use self::async_impl::multipart;
304
305
306    mod async_impl;
307    #[cfg(feature = "blocking")]
308    pub mod blocking;
309    mod connect;
310    #[cfg(feature = "cookies")]
311    pub mod cookie;
312    #[cfg(feature = "trust-dns")]
313    mod dns;
314    mod proxy;
315    pub mod redirect;
316    #[cfg(feature = "__tls")]
317    pub mod tls;
318    mod util;
319}
320
321if_wasm! {
322    mod wasm;
323    mod util;
324
325    pub use self::wasm::{Body, Client, ClientBuilder, Request, RequestBuilder, Response};
326    #[cfg(feature = "multipart")]
327    pub use self::wasm::multipart;
328}