### Initiate a GET Request Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Start a GET request to a specified URL using an existing client. The response is awaited. ```rust let resp = client.get("https://example.com").send().await?; ``` -------------------------------- ### Example: Building and sending a multipart form Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/types.md This example demonstrates how to construct a `Form` with text and file fields, and then send it using a `client`. Note the use of `.await` for file operations and sending. ```rust let form = Form::new() .text("username", "alice") .text("password", "secret") .file("avatar", "/path/to/avatar.png").await?; client.post(url) .multipart(form) .send() .await?; ``` -------------------------------- ### SOCKS Proxy Example Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/proxy.md Configure a SOCKS proxy for all traffic. This example requires the `socks` feature to be enabled. ```rust #[cfg(feature = "socks")] let client = { let proxy = reqwest::Proxy::all("socks5://127.0.0.1:9050")?; reqwest::Client::builder() .proxy(proxy) .build()?; }; ``` -------------------------------- ### Example: Custom Store Implementation Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/cookies.md Provides an example implementation of the `CookieStore` trait, demonstrating how to create a custom cookie store. ```APIDOC ### Example: Custom Store Implementation ```rust use std::sync::Arc; use reqwest::cookie::CookieStore; use http::HeaderValue; use url::Url; struct MyCustomCookieStore { // Store cookies however you want } impl CookieStore for MyCustomCookieStore { fn set_cookies( &self, cookie_headers: &mut dyn Iterator, url: &Url, ) { for header in cookie_headers { if let Ok(cookie_str) = header.to_str() { // Parse and store cookie println!("Storing cookie: {}", cookie_str); } } } fn cookies(&self, url: &Url) -> Option { // Return matching cookies for this URL println!("Getting cookies for: {}", url); None // Return None if no cookies } } impl MyCustomCookieStore { fn new() -> Self { MyCustomCookieStore {} } } ``` ``` -------------------------------- ### Async GET Request with JSON Response Source: https://github.com/seanmonstar/reqwest/blob/master/README.md This asynchronous example demonstrates making a GET request to an IP address API, parsing the JSON response into a HashMap, and printing it. Ensure Tokio is set up for async execution. ```rust use std::collections::HashMap; #[tokio::main] async fn main() -> Result<(), Box> { let resp = reqwest::get("https://httpbin.org/ip") .await?; let resp = resp.json::>().await?; println!("{resp:#?}"); Ok(()) } ``` -------------------------------- ### Initiate a Request with Custom Method Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Start a request with a custom HTTP method and a URL. The response is awaited. ```rust let resp = client.request(Method::CUSTOM("QUERY"), url).send().await?; ``` -------------------------------- ### Client::get Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Begin a GET request. ```APIDOC ## Client::get ### Description Begin a GET request. ### Method `get(url: T: IntoUrl)` ### Endpoint `/` (relative to client base URL if configured) ### Parameters #### Path Parameters - **url** (T: IntoUrl) - Required - URL to request ### Returns `RequestBuilder` ``` -------------------------------- ### Proxy URL Conversion Examples Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/proxy.md Demonstrates the equivalent ways to create an HTTP proxy URL using the Proxy::http function with &str, String, and Url types. ```rust let p1 = Proxy::http("http://proxy:8080")?; let p2 = Proxy::http("http://proxy:8080".to_string())?; let p3 = Proxy::http(Url::parse("http://proxy:8080")?)?; ``` -------------------------------- ### Create a Configurable Client Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Use ClientBuilder to configure and construct a reusable HTTP client. This example sets a timeout for the client. ```rust let client = reqwest::Client::builder() .timeout(Duration::from_secs(30)) .build()?; ``` -------------------------------- ### Client::get() Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Begins a GET request to the specified URL. Returns a RequestBuilder for further configuration. ```APIDOC ## Client::get() ### Description Begin a GET request to the specified URL. ### Method ```rust pub async fn get(&self, url: T) -> RequestBuilder ``` ### Parameters #### Path Parameters - **url** (T: IntoUrl) - Required - URL to request ### Returns `RequestBuilder` - A builder for configuring and sending the request ### Example ```rust let resp = client.get("https://example.com").send().await?; ``` ``` -------------------------------- ### Basic GET Request with Reqwest Blocking Client Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Shows how to perform a simple GET request using the blocking client. Ensure the client is created and the response status and body are handled. ```rust use reqwest::blocking::Client; fn main() -> Result<(), Box> { let client = Client::new()?; let response = client.get("https://api.example.com/data").send()?; println!("Status: {}", response.status()); let body = response.text()?; println!("Body: {}", body); Ok(()) } ``` -------------------------------- ### Basic GET Request Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Demonstrates how to create a blocking client and send a basic GET request to retrieve data. ```APIDOC ## GET /data ### Description Sends a GET request to a specified URL and retrieves the response body as text. ### Method GET ### Endpoint https://api.example.com/data ### Parameters None explicitly defined in this example, but headers can be added. ### Request Example ```rust use reqwest::blocking::Client; fn main() -> Result<(), Box> { let client = Client::new()?; let response = client.get("https://api.example.com/data").send()?; println!("Status: {}", response.status()); let body = response.text()?; println!("Body: {}", body); Ok(()) } ``` ### Response #### Success Response (200) - **status** (StatusCode) - The HTTP status code of the response. - **body** (string) - The response body as a string. #### Response Example ``` Status: 200 OK Body: {"message": "Success"} ``` ``` -------------------------------- ### ClientBuilder::new Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Creates a new instance of ClientBuilder to start configuring a blocking client. ```APIDOC ## ClientBuilder::new ### Description Create a new blocking client builder. ### Returns `ClientBuilder` ``` -------------------------------- ### Example Custom Cookie Store Implementation Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/cookies.md An example implementation of the `CookieStore` trait. This store prints incoming cookies and returns `None` for outgoing cookies. It requires `reqwest::cookie::CookieStore`, `http::HeaderValue`, and `url::Url`. ```rust use std::sync::Arc; use reqwest::cookie::CookieStore; use http::HeaderValue; use url::Url; struct MyCustomCookieStore { // Store cookies however you want } impl CookieStore for MyCustomCookieStore { fn set_cookies( &self, cookie_headers: &mut dyn Iterator, url: &Url, ) { for header in cookie_headers { if let Ok(cookie_str) = header.to_str() { // Parse and store cookie println!("Storing cookie: {}", cookie_str); } } } fn cookies(&self, url: &Url) -> Option { // Return matching cookies for this URL println!("Getting cookies for: {}", url); None // Return None if no cookies } } impl MyCustomCookieStore { fn new() -> Self { MyCustomCookieStore {} } } ``` -------------------------------- ### Enable HTTP/2 Prior Knowledge Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/configuration.md Assumes HTTP/2 is available from the start, skipping the upgrade negotiation process. Requires the 'http2' feature. ```rust .http2_prior_knowledge() // Connect directly with HTTP/2 ``` -------------------------------- ### Configure SOCKS5 Proxy Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/proxy.md Set up a SOCKS5 proxy for HTTP requests when the 'socks' feature is enabled. This example demonstrates configuring the proxy via code. ```rust #[cfg(feature = "socks")] { let proxy = reqwest::Proxy::all("socks5://127.0.0.1:1080")?; let client = reqwest::Client::builder() .proxy(proxy) .build()?; } ``` -------------------------------- ### Convenience Async GET Request Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/README.md A simplified way to make an asynchronous GET request without explicitly creating a client. Suitable for simple, one-off requests. ```rust let response = reqwest::get(url).await?; ``` -------------------------------- ### Build Reqwest Client with Configuration Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/configuration.md Create a reqwest client with custom timeout and cookie store enabled. This is the starting point for configuring a client. ```rust let client = reqwest::Client::builder() .timeout(Duration::from_secs(30)) .cookie_store(true) .build()?; ``` -------------------------------- ### Make a GET Request with `reqwest::get` Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Use this convenience function for a single GET request without explicitly creating a `Client`. It creates an internal client for each call, so reuse a `Client` for multiple requests. ```rust let body = reqwest::get("https://example.com").await?.text().await?; ``` -------------------------------- ### Create a new Form builder Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/types.md Use `Form::new()` to initialize a new multipart form builder. This is the starting point for adding text and file fields. ```rust pub struct Form { // Internal representation } impl Form { pub fn new() -> Form } ``` -------------------------------- ### get Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Makes a single GET request without creating a `Client`. This function is useful for simple, one-off requests. Note that it creates a new internal client for each call, so for multiple requests, it's more efficient to create and reuse a `Client` instance. ```APIDOC ## get(url: T) -> Result ### Description Make a single GET request without creating a `Client`. ### Method GET ### Endpoint [URL provided as parameter] ### Parameters #### Path Parameters - **url** (T: IntoUrl) - Required - URL to request ### Request Example ```rust let body = reqwest::get("https://example.com").await?.text().await?; ``` ### Response #### Success Response (200) - **Response** (Response) - The HTTP response object. #### Response Example (Response object structure depends on the actual HTTP response) ``` -------------------------------- ### Build Reqwest Client Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Build the configured `Client` instance. This operation can fail if there are issues with TLS backend initialization, DNS resolver setup, or invalid configuration. ```rust let client = reqwest::Client::builder() .timeout(Duration::from_secs(10)) .cookie_store(true) .build()?; ``` -------------------------------- ### Build Reqwest Client Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/configuration.md Builds the `Client` instance. This operation can fail due to TLS backend initialization, DNS resolver setup, or invalid configuration. ```rust pub fn build(self) -> Result ``` -------------------------------- ### File Upload using Multipart Form Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/README.md Upload a file as part of a multipart form request. This example shows how to add text fields and a file to the form. ```rust let form = reqwest::multipart::Form::new() .text("name", "Alice") .file("avatar", "/path/to/avatar.png").await?; client.post(url).multipart(form).send().await? ``` -------------------------------- ### Create New Blocking Client Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Creates a new blocking client with default configuration. This is the basic way to start making synchronous HTTP requests. ```rust let client = reqwest::blocking::Client::new()?; let response = client.get("https://example.com").send()?; ``` -------------------------------- ### Set Connection Establishment Timeout Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Configure a timeout for establishing a new TCP connection. This is crucial for preventing long delays when a server is unresponsive or network issues occur during connection setup. ```rust builder.connect_timeout(Duration::from_secs(5)) ``` -------------------------------- ### Construct a Complex Multipart Form Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/multipart.md An example of building a comprehensive multipart form with multiple text fields and file uploads for different purposes like user profile information and media attachments. ```Rust let form = multipart::Form::new() // User fields .text("username", "alice") .text("email", "alice@example.com") .text("password", "secret") // Profile picture .file("avatar", "/path/to/avatar.png").await? // Cover image .file("cover", "/path/to/cover.jpg").await? // Preferences .text("theme", "dark") .text("notifications", "true"); client.post("https://api.example.com/profile") .multipart(form) .send() .await? ``` -------------------------------- ### Send Request and Get Response Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/request_builder.md Send the constructed request and receive the `Response`. This is the primary method for making HTTP requests. Ensure `client` and `url` are defined. ```rust let response = client.get(url).send().await?; println!("Status: {}", response.status()); ``` -------------------------------- ### Complete Response Handling Pattern Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/response.md Demonstrates a common pattern for sending a GET request, awaiting the response, and handling different status codes by either parsing JSON or returning an error. ```rust use reqwest::StatusCode; let response = client.get("https://api.example.com/data") .send() .await?; // Check status match response.status() { StatusCode::OK => { // Ensure status is success let data = response.json::().await?; Ok(data) } StatusCode::NOT_FOUND => { Err("Resource not found") } status => { Err(format!("Unexpected status: {}", status)) } } ``` -------------------------------- ### Build Client Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Build the configured `Client` instance. ```APIDOC ## `build` ### Description Build the configured `Client`. ### Method `build(self) -> Result` ### Returns `Result` - Configured client or error ### Errors - TLS backend initialization failed - DNS resolver setup failed - Invalid configuration ### Example ```rust let client = reqwest::Client::builder() .timeout(Duration::from_secs(10)) .cookie_store(true) .build()?; ``` ``` -------------------------------- ### Example of Session Maintenance with Cookies Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/cookies.md Demonstrates how Reqwest automatically handles cookies across multiple requests. After enabling the cookie store, the client will store cookies from responses and send them with subsequent requests to the same domain. ```rust let client = reqwest::Client::builder() .cookie_store(true) .build()?; // First request - server sends Set-Cookie header let resp1 = client.get("https://example.com/login") .send() .await?; // Second request - cookies automatically sent let resp2 = client.get("https://example.com/dashboard") .send() .await?; // Third request - still have cookies let resp3 = client.get("https://example.com/api/data") .send() .await?; ``` -------------------------------- ### Enable and Use Cookie Store Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/cookies.md Demonstrates how to enable the cookie store and shows a typical session flow involving login, data retrieval, and logout, where cookies are automatically managed. ```rust let client = reqwest::Client::builder() .cookie_store(true) .build()?; let login = client.post("https://api.example.com/login") .json(&json!({ "username": "alice", "password": "secret" })) .send() .await?; println!("Login status: {}", login.status()); let data = client.get("https://api.example.com/data") .send() .await?; .json::() .await?; println!("Data: {:?}", data); let _logout = client.post("https://api.example.com/logout") .send() .await?; ``` -------------------------------- ### Create and Use HTTP Proxy Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/proxy.md Demonstrates how to create an HTTP proxy and configure a Reqwest client to use it. Ensure the proxy URL is valid. ```rust let proxy = reqwest::Proxy::http("http://proxy.example.com:8080")?; let client = reqwest::Client::builder() .proxy(proxy) .build()?; ``` -------------------------------- ### Client::builder() Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Creates a new ClientBuilder to configure and construct a Client. This is the recommended way to create a client instance. ```APIDOC ## Client::builder() ### Description Creates a new `ClientBuilder` to configure and construct a `Client`. ### Method ```rust pub fn builder() -> ClientBuilder ``` ### Returns `ClientBuilder` - A builder for configuring and constructing a `Client`. ### Example ```rust let client = reqwest::Client::builder() .timeout(Duration::from_secs(30)) .build()?; ``` ``` -------------------------------- ### Create Proxy for All Connections Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/proxy.md Illustrates creating a proxy that applies to all connection types (HTTP and HTTPS). Use this for a general proxy setting. ```rust let proxy = reqwest::Proxy::all("http://proxy.example.com:8080")?; ``` -------------------------------- ### Catching Redirect Errors Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/redirect.md Example of how to catch and differentiate redirect-related errors from other network errors. ```rust match client.get(url).send().await { Ok(response) => { // Handle success } Err(e) if e.is_redirect() => { eprintln!("Redirect error: {}", e); } Err(e) => { eprintln!("Other error: {}", e); } } ``` -------------------------------- ### Build API Client with Authentication Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/configuration.md Configure a client with default headers for API keys and a custom user agent. Includes a default timeout. ```rust let mut headers = HeaderMap::new(); headers.insert("X-API-Key", "secret".parse()?); let client = reqwest::Client::builder() .default_headers(headers) .user_agent("MyApp/1.0") .timeout(Duration::from_secs(30)) .build()?; ``` -------------------------------- ### Create and Use HTTPS Proxy Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/proxy.md Shows how to create an HTTPS proxy and integrate it with a Reqwest client. Verify the proxy URL for secure connections. ```rust let proxy = reqwest::Proxy::https("https://secure-proxy.example.com:8443")?; let client = reqwest::Client::builder() .proxy(proxy) .build()?; ``` -------------------------------- ### Creating a RequestBuilder Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/request_builder.md RequestBuilder instances are created through client methods like get() or post(), not directly. ```rust let builder = client.get("https://example.com"); let builder = client.post(url).header("X-Custom", "value"); ``` -------------------------------- ### Async Client Initialization Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/README.md Use this to create a new asynchronous HTTP client. This is the default and recommended way to use Reqwest. ```rust use reqwest::Client; let client = Client::new(); let response = client.get(url).send().await?; ``` -------------------------------- ### Add Basic Authentication to Proxy Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/proxy.md Shows how to configure HTTP Basic authentication for an existing proxy. Provide the username and password for the proxy server. ```rust let proxy = reqwest::Proxy::http("http://proxy.example.com:8080")? .basic_auth("proxyuser", "proxypass"); ``` -------------------------------- ### Catching Redirect Errors at Specific URL Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/redirect.md Example of catching redirect errors and extracting the URL where the error occurred. ```rust match client.get("http://redirect-loop.example.com").send().await { Err(e) if e.is_redirect() => { if let Some(url) = e.url() { eprintln!("Redirect error at URL: {}", url); } } Ok(response) => { // Handle response } Err(e) => { eprintln!("Other error: {}", e); } } ``` -------------------------------- ### Client::new Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Create a new blocking client with default configuration. ```APIDOC ## Client::new ### Description Create a new blocking client with default configuration. ### Method `new()` ### Returns `Result` ### Example ```rust let client = reqwest::blocking::Client::new()?; let response = client.get("https://example.com").send()?; ``` ``` -------------------------------- ### Form::new Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/multipart.md Creates a new, empty multipart form builder. This is the starting point for constructing multipart requests. ```APIDOC ## Form::new ### Description Create a new empty multipart form. ### Constructor `pub fn new() -> Form` ### Returns `Form` ### Example ```rust let form = reqwest::multipart::Form::new() .text("username", "alice") .file("avatar", "/path/to/avatar.png").await?; client.post(url) .multipart(form) .send() .await?; ``` ``` -------------------------------- ### Client::request Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Begin a request with the specified method. ```APIDOC ## Client::request ### Description Begin a request with the specified method. ### Method `request(method: Method, url: T: IntoUrl)` ### Endpoint `/` (relative to client base URL if configured) ### Parameters #### Path Parameters - **method** (Method) - Required - HTTP method - **url** (T: IntoUrl) - Required - URL ### Returns `RequestBuilder` ``` -------------------------------- ### Automatic Cookie Handling Example Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/cookies.md Illustrates how Reqwest automatically handles cookies for session maintenance across multiple requests. ```APIDOC ## Automatic Cookie Handling Example ### Description This example shows how a Reqwest client with cookie support enabled automatically manages cookies. The first request receives a `Set-Cookie` header, and subsequent requests to the same domain will include the stored cookie. ### Code ```rust let client = reqwest::Client::builder() .cookie_store(true) .build()?; // First request - server sends Set-Cookie header let resp1 = client.get("https://example.com/login") .send() .await?; // Second request - cookies automatically sent let resp2 = client.get("https://example.com/dashboard") .send() .await?; // Third request - still have cookies let resp3 = client.get("https://example.com/api/data") .send() .await?; ``` ``` -------------------------------- ### Get Response Headers Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/response.md Access response headers to retrieve specific information like 'content-type'. The headers are stored in a HeaderMap. ```rust if let Some(content_type) = response.headers().get("content-type") { println!("Content-Type: {:?}", content_type); } ``` -------------------------------- ### Client::head Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Begin a HEAD request. ```APIDOC ## Client::head ### Description Begin a HEAD request. ### Method `head(url: T: IntoUrl)` ### Endpoint `/` (relative to client base URL if configured) ### Parameters #### Path Parameters - **url** (T: IntoUrl) - Required - URL to request ### Returns `RequestBuilder` ``` -------------------------------- ### Create and Populate a Multipart Form Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/multipart.md Demonstrates creating a new multipart form, adding a text field, and a file field, then sending it with a POST request. Requires the 'multipart' feature. ```rust let form = reqwest::multipart::Form::new() .text("username", "alice") .file("avatar", "/path/to/avatar.png").await?; client.post(url) .multipart(form) .send() .await? ``` -------------------------------- ### Get HTTP Status Code Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/response.md Retrieve the HTTP status code of a response. This is useful for conditional logic based on the request outcome. ```rust let response = client.get(url).send().await?; match response.status() { StatusCode::OK => println!("Success"), StatusCode::NOT_FOUND => println!("Not found"), StatusCode::INTERNAL_SERVER_ERROR => println!("Server error"), _ => println!("Other: {}", response.status()), } ``` -------------------------------- ### Multiple Requests with Reused Client Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Demonstrates creating a client once and reusing it for multiple requests, leveraging connection pooling. ```APIDOC ## Multiple GET Requests with Reused Client ### Description Shows how to initialize a client and use it to perform multiple HTTP requests efficiently by reusing underlying connections. ### Method GET ### Endpoint https://api.example.com/item/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The identifier for the item. ### Request Example ```rust use reqwest::blocking::Client; fn main() -> Result<(), Box> { let client = Client::new()?; // Make multiple requests, reusing connection pool for i in 1..=5 { let url = format!("https://api.example.com/item/{}", i); let response = client.get(&url).send()?; println!("Item {}: {}", i, response.status()); } Ok(()) } ``` ### Response #### Success Response (200 OK) - **status** (StatusCode) - The HTTP status code for each item request. #### Response Example ``` Item 1: 200 OK Item 2: 200 OK ... Item 5: 200 OK ``` ``` -------------------------------- ### Client::execute Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Execute a pre-built Request. ```APIDOC ## Client::execute ### Description Execute a pre-built Request. ### Method `execute(request: Request)` ### Parameters #### Path Parameters - **request** (Request) - Required - Built request ### Returns `Result` ``` -------------------------------- ### StatusCode Usage Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/types.md Demonstrates the usage of StatusCode enum for representing HTTP status codes, with examples of common codes and how to create custom ones. ```APIDOC ## StatusCode ### Description Represents standard HTTP status codes. All codes from the `http` crate are supported. ### Usage Examples ```rust // Common Status Codes StatusCode::OK // 200 StatusCode::CREATED // 201 StatusCode::ACCEPTED // 202 StatusCode::NO_CONTENT // 204 StatusCode::MOVED_PERMANENTLY // 301 StatusCode::FOUND // 302 StatusCode::SEE_OTHER // 303 StatusCode::NOT_MODIFIED // 304 StatusCode::TEMPORARY_REDIRECT // 307 StatusCode::PERMANENT_REDIRECT // 308 StatusCode::BAD_REQUEST // 400 StatusCode::UNAUTHORIZED // 401 StatusCode::FORBIDDEN // 403 StatusCode::NOT_FOUND // 404 StatusCode::METHOD_NOT_ALLOWED // 405 StatusCode::CONFLICT // 409 StatusCode::GONE // 410 StatusCode::INTERNAL_SERVER_ERROR // 500 StatusCode::NOT_IMPLEMENTED // 501 StatusCode::BAD_GATEWAY // 502 StatusCode::SERVICE_UNAVAILABLE // 503 ``` ### Creating Custom Status Codes ```rust StatusCode::from_u16(200)? ``` ``` -------------------------------- ### Client::post Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Begin a POST request. ```APIDOC ## Client::post ### Description Begin a POST request. ### Method `post(url: T: IntoUrl)` ### Endpoint `/` (relative to client base URL if configured) ### Parameters #### Path Parameters - **url** (T: IntoUrl) - Required - URL to request ### Returns `RequestBuilder` ``` -------------------------------- ### Get Next Chunk from Response Body Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/response.md Retrieves the next chunk of bytes from the response body. Returns `Ok(None)` when the body is exhausted. ```rust let mut response = client.get(url).send().await?; while let Some(chunk) = response.chunk().await? { println!("Chunk: {} bytes", chunk.len()); } ``` -------------------------------- ### Client::post() Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Begins a POST request to the specified URL. Returns a RequestBuilder for further configuration. ```APIDOC ## Client::post() ### Description Begin a POST request to the specified URL. ### Method ```rust pub async fn post(&self, url: T) -> RequestBuilder ``` ### Parameters #### Path Parameters - **url** (T: IntoUrl) - Required - URL to request ### Returns `RequestBuilder` ### Example ```rust let resp = client.post("https://api.example.com/users") .json(&user_data) .send() .await?; ``` ``` -------------------------------- ### Custom Redirect Policy - Specific Domain Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/redirect.md Implement a custom redirect policy that only allows redirects to URLs ending with 'example.com'. ```rust let custom = redirect::Policy::custom(|attempt| { // Only allow redirects within example.com domain if let Some(host) = attempt.url().host_str() { if host.ends_with("example.com") { attempt.follow() } else { attempt.stop() } } else { attempt.stop() } }); let client = reqwest::Client::builder() .redirect(custom) .build()?; ``` -------------------------------- ### Getting the Next Chunk from Response Body Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/response.md Asynchronously retrieves the next chunk of bytes from the response body. Returns `Ok(None)` when the body is exhausted. ```APIDOC ## `pub async fn chunk(&mut self) -> Result>` ### Description Get the next chunk from the response body. ### Returns `Result>` - `Ok(Some(bytes))` - Next chunk of data - `Ok(None)` - Body exhausted - `Err(e)` - Error reading chunk ### Example ```rust let mut response = client.get(url).send().await?; while let Some(chunk) = response.chunk().await? { println!("Chunk: {} bytes", chunk.len()); } ``` ``` -------------------------------- ### Blocking Client Initialization Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/README.md Use this to create a synchronous HTTP client. Requires the `blocking` feature to be enabled. ```rust use reqwest::blocking::Client; let client = Client::new()?; let response = client.get(url).send()?; ``` -------------------------------- ### Create a new ClientBuilder Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Instantiates a new ClientBuilder to begin configuring a reqwest Client. This can be done using either `ClientBuilder::new()` or `Client::builder()`. ```rust let builder = reqwest::ClientBuilder::new(); // or let builder = reqwest::Client::builder(); ``` -------------------------------- ### Part Methods Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/multipart.md Methods for configuring existing parts. ```APIDOC ## Part Methods ### `pub fn file_name(self, filename: S) -> Part` Set the filename for this part. #### Parameters - **filename** (S: Into) - Required - Filename #### Returns - `Part` #### Example ```rust let part = Part::bytes(data) .file_name("data.bin"); ``` ### `pub fn mime(self, mime: Mime) -> Part` Set the MIME type for this part. #### Parameters - **mime** (Mime) - Required - MIME type #### Returns - `Part` #### Example ```rust let part = Part::bytes(image_data) .mime("image/png".parse()?); let part = Part::text("data") .mime(mime::APPLICATION_JSON); ``` ### `pub fn header(self, key: K, value: V) -> Part` Add a custom header to this part. #### Parameters - **key** (K: IntoHeaderName) - Required - Header name - **value** (V: IntoHeaderValue) - Required - Header value #### Returns - `Part` #### Example ```rust let part = Part::file("/path/to/file").await? .header("Content-Disposition", "attachment; filename=\"file.pdf\""); ``` ### `pub fn headers(self, headers: HeaderMap) -> Part` Set multiple headers for this part. #### Parameters - **headers** (HeaderMap) - Required - All headers #### Returns - `Part` ``` -------------------------------- ### Create and Configure NoProxy Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/proxy.md Initialize an empty NoProxy configuration and add hosts or patterns that should bypass proxy settings. Supports exact hostnames, wildcard domains, IP addresses, and CIDR ranges. ```rust let no_proxy = reqwest::NoProxy::new() .add_host("localhost") .add_host("*.local") .add_host("127.0.0.1") .add_host("internal.company.com"); ``` -------------------------------- ### Part Constructor Methods Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/multipart.md Methods for creating individual parts for multipart requests. ```APIDOC ## Part Constructor Methods ### `pub fn text(value: T) -> Part` Create a text part. #### Parameters - **value** (T: Display) - Required - Text value #### Returns - `Part` #### Example ```rust let part = Part::text("Hello, world!"); ``` ### `pub async fn file

(path: P) -> Result` Create a file part from a file path. #### Parameters - **path** (P: AsRef) - Required - File path #### Returns - `Result` #### Details - Automatically detects MIME type from extension - Reads file name from path - Async because it reads file metadata #### Example ```rust let part = Part::file("/path/to/document.pdf").await?; let part = Part::file("image.jpg").await?; ``` ### `pub fn stream(stream: S) -> Part` Create a streaming part from a stream. #### Parameters - **stream** (S: TryStream + Send + 'static) - Required - Data stream - Type requirements: - `S::Ok: Into` - `S::Error: Into>` #### Returns - `Part` #### Requires - `stream` feature #### Example ```rust use futures::stream; let chunks = vec![Ok(Bytes::from("chunk1")), Ok(Bytes::from("chunk2"))]; let stream = stream::iter(chunks); let part = Part::stream(stream); ``` ### `pub fn bytes(bytes: B) -> Part` Create a part from bytes. #### Parameters - **bytes** (B: Into) - Required - Byte data #### Returns - `Part` #### Example ```rust let part = Part::bytes(b"file contents".to_vec()); ``` ``` -------------------------------- ### Create a file Part Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/types.md Use `Part::file` to create a multipart part from a file path. This is an asynchronous operation returning a `BoxFuture`. ```rust pub fn file(name: T, path: P) -> BoxFuture<'static, Result> ``` -------------------------------- ### With Timeout and Headers Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Configures a client with a timeout and demonstrates adding custom headers to a request. ```APIDOC ## GET /data with Timeout and Headers ### Description Sends a GET request with a specified timeout and custom headers, and checks for HTTP errors. ### Method GET ### Endpoint https://api.example.com/data ### Parameters #### Query Parameters None explicitly defined in this example. #### Headers - **Authorization** (string) - Required - Bearer token for authentication. ### Request Example ```rust use reqwest::blocking::Client; use std::time::Duration; fn main() -> Result<(), Box> { let client = Client::builder() .timeout(Duration::from_secs(30)) .build()?; let response = client.get("https://api.example.com/data") .header("Authorization", "Bearer token") .send()?; .error_for_status()?; let body = response.text()?; Ok(()) } ``` ### Response #### Success Response (200 OK) - **body** (string) - The response body as a string if the request is successful and no HTTP errors occur. #### Response Example ``` (Response body as text) ``` ``` -------------------------------- ### Using a Custom Cookie Store with Reqwest Client Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/cookies.md Demonstrates how to build a Reqwest client with a custom cookie store. The custom store is provided using `Client::builder().cookie_provider()` and must be wrapped in an `Arc`. ```rust let store = Arc::new(MyCustomCookieStore::new()); let client = reqwest::Client::builder() .cookie_provider(store) .build()?; // Use client normally - cookies use custom store let response = client.get(url).send().await?; ``` -------------------------------- ### Client::head() Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Begins a HEAD request to the specified URL. Returns a RequestBuilder for further configuration. ```APIDOC ## Client::head() ### Description Begin a HEAD request. ### Method ```rust pub async fn head(&self, url: T) -> RequestBuilder ``` ### Parameters #### Path Parameters - **url** (T: IntoUrl) - Required - URL to request ### Returns `RequestBuilder` ``` -------------------------------- ### Proxy::all Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/proxy.md Creates a proxy configuration for all connection types (HTTP and HTTPS). ```APIDOC ## Proxy::all ### Description Creates a proxy configuration for all connections (HTTP and HTTPS). ### Method `Proxy::all(url: U) -> Result` ### Parameters #### Path Parameters - **url** (U: IntoProxy) - Required - Proxy URL ### Request Example ```rust let proxy = reqwest::Proxy::all("http://proxy.example.com:8080")?; ``` ### Response #### Success Response (Result) - **Proxy** - The configured proxy object. #### Response Example (See Request Example) ``` -------------------------------- ### Client::request() Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Begins a request with the specified HTTP method and URL. Returns a RequestBuilder for further configuration. ```APIDOC ## Client::request() ### Description Begin a request with the specified HTTP method. ### Method ```rust pub async fn request(&self, method: Method, url: T) -> RequestBuilder ``` ### Parameters #### Path Parameters - **method** (Method) - Required - HTTP method (GET, POST, etc.) - **url** (T: IntoUrl) - Required - URL to request ### Returns `RequestBuilder` ### Example ```rust let resp = client.request(Method::CUSTOM("QUERY"), url).send().await?; ``` ``` -------------------------------- ### Upload a Single File Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/multipart.md Demonstrates how to upload a single file using `reqwest::multipart::Form`. Ensure the file path is correct and the server endpoint is valid. ```Rust use reqwest::multipart; let form = multipart::Form::new() .file("upload", "/path/to/file.txt").await?; let resp = client.post("https://api.example.com/upload") .multipart(form) .send() .await?; println!("Status: {}", resp.status()); ``` -------------------------------- ### Authenticated HTTP Proxy Configuration Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/proxy.md Configure an HTTP proxy with basic authentication credentials. Ensure the proxy URL and credentials are correct. ```rust let proxy = reqwest::Proxy::http("http://proxy.example.com:8080")? .basic_auth("username", "password"); let client = reqwest::Client::builder() .proxy(proxy) .build()?; ``` -------------------------------- ### Add a Prepared Part to a Multipart Form Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/multipart.md Shows how to add a pre-built `Part` object to a multipart form using the synchronous `part` method. ```rust let part = Part::text("value"); let form = Form::new() .part("field", part); ``` -------------------------------- ### Configure No-Proxy Exceptions Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/proxy.md Demonstrates how to specify hosts or patterns that should bypass the proxy. Use `NoProxy::new()` and `add_host` to define exceptions. ```rust let no_proxy = reqwest::NoProxy::new() .add_host("localhost") .add_host("example.internal"); let proxy = reqwest::Proxy::all("http://proxy.example.com:8080")? .no_proxy(no_proxy); ``` -------------------------------- ### File Path Handling in Multipart Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/multipart.md Demonstrates how to specify file paths for multipart uploads, noting compatibility across different operating systems. Use forward slashes for cross-platform compatibility. ```rust let part = Part::file("path/to/file.txt").await?; ``` ```rust let part = Part::file("path\\to\\file.txt").await?; ``` -------------------------------- ### Add Root Certificate to Client Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/types.md Shows how to load a certificate from a PEM file and add it as a root certificate to the Reqwest client builder. ```rust let pem = std::fs::read("ca.pem")?; let cert = Certificate::from_pem(&pem)?; let client = Client::builder() .add_root_certificate(cert) .build()?; ``` -------------------------------- ### Multiple Requests with Reused Client Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Illustrates making multiple requests efficiently by reusing a single `Client` instance. This leverages connection pooling for improved performance. ```rust use reqwest::blocking::Client; fn main() -> Result<(), Box> { let client = Client::new()?; // Make multiple requests, reusing connection pool for i in 1..=5 { let url = format!("https://api.example.com/item/{}", i); let response = client.get(&url).send()?; println!("Item {}: {}", i, response.status()); } Ok(()) } ``` -------------------------------- ### Use HTTP/2 Prior Knowledge Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Configure the client to use HTTP/2 directly without performing an HTTP/1.1 upgrade. This requires the `http2` feature to be enabled. ```rust builder.http2_prior_knowledge() ``` -------------------------------- ### Initiate a POST Request with JSON Body Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Begin a POST request to a URL and send JSON data in the request body. The response is awaited. ```rust let resp = client.post("https://api.example.com/users") .json(&user_data) .send() .await?; ``` -------------------------------- ### Create Identity from PKCS#12 Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/tls.md Create an `Identity` object from PKCS#12 formatted data (often `.p12` or `.pfx` files). Requires the data as a byte slice and the password. ```rust let pkcs12 = std::fs::read("client-cert.p12")?; let identity = Identity::from_pkcs12(&pkcs12, "password123")?; let client = reqwest::Client::builder() .identity(identity) .build()?; ``` -------------------------------- ### Create Custom HTTP Method Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/types.md Demonstrates how to create a custom HTTP method from a byte slice. This is useful for non-standard HTTP verbs. ```rust Method::from_bytes(b"CUSTOM")? ``` -------------------------------- ### Client::put Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md Begin a PUT request. ```APIDOC ## Client::put ### Description Begin a PUT request. ### Method `put(url: T: IntoUrl)` ### Endpoint `/` (relative to client base URL if configured) ### Parameters #### Path Parameters - **url** (T: IntoUrl) - Required - URL to request ### Returns `RequestBuilder` ``` -------------------------------- ### Configure HTTP/2 Initial Connection Window Size Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/configuration.md Sets the initial window size for the HTTP/2 connection. Requires the 'http2' feature. Defaults to 1048576. ```rust .http2_initial_connection_window_size(sz: impl Into>) -> ClientBuilder ``` -------------------------------- ### Parse and Use Url Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/types.md Demonstrates parsing a URL string and accessing its components. Requires the `url` crate. ```rust pub use url::Url; Url::parse("https://example.com")?; url.scheme() // "https" url.host_str() // Some("example.com") url.port() // Some(443) url.path() // "/" url.query() // Option<&str> url.fragment() // Option<&str> ``` -------------------------------- ### Configure HTTP/2 Initial Stream Window Size Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/configuration.md Sets the initial window size for HTTP/2 streams. Requires the 'http2' feature. Defaults to 65535. ```rust .http2_initial_stream_window_size(sz: impl Into>) -> ClientBuilder ``` -------------------------------- ### Using Custom Store Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/cookies.md Demonstrates how to integrate a custom cookie store with a Reqwest client builder. ```APIDOC ### Using Custom Store ```rust let store = Arc::new(MyCustomCookieStore::new()); let client = reqwest::Client::builder() .cookie_provider(store) .build()?; // Use client normally - cookies use custom store let response = client.get(url).send().await?; ``` ``` -------------------------------- ### Enable HTTP/2 Adaptive Window Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/configuration.md Dynamically adjusts the HTTP/2 window size based on network load. Defaults to false. ```rust .http2_adaptive_window(enabled: bool) -> ClientBuilder ``` -------------------------------- ### Configure All Proxy Types Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/configuration.md Set a proxy for all protocols (e.g., SOCKS5). Multiple calls can be chained for different rules. ```rust .proxy(Proxy::all("socks5://127.0.0.1:1080")?) ``` -------------------------------- ### Configure Production TLS Versions Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/tls.md Set minimum and maximum TLS versions for production environments. Requires `tls` module. ```rust let client = reqwest::Client::builder() .min_tls_version(tls::Version::TLS_1_2) .max_tls_version(tls::Version::TLS_1_3) .tls_sni(true) .build()?; ``` -------------------------------- ### Enable HTTP/2 Adaptive Window Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/client.md Enable adaptive flow control for HTTP/2. This allows the window size to adjust dynamically based on network conditions, requiring the `http2` feature. ```rust builder.http2_adaptive_window(true) ``` -------------------------------- ### Proxy::http Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/proxy.md Creates a proxy configuration for HTTP connections. ```APIDOC ## Proxy::http ### Description Creates a proxy configuration for HTTP connections. ### Method `Proxy::http(url: U) -> Result` ### Parameters #### Path Parameters - **url** (U: IntoProxy) - Required - HTTP proxy URL ### Request Example ```rust let proxy = reqwest::Proxy::http("http://proxy.example.com:8080")?; let client = reqwest::Client::builder() .proxy(proxy) .build()?; ``` ### Response #### Success Response (Result) - **Proxy** - The configured proxy object. #### Response Example (See Request Example for client configuration) ``` -------------------------------- ### Async Client Usage Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/blocking.md This is the correct way to use the Reqwest client in an async runtime. ```rust #[tokio::main] async fn main() { let client = reqwest::Client::new(); let resp = client.get("https://example.com").send().await.unwrap(); } ``` -------------------------------- ### Upload Multiple Files Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/api-reference/multipart.md Shows how to include multiple files in a single multipart form. Each file is added with a distinct field name. ```Rust let form = multipart::Form::new() .file("document", "/path/to/document.pdf").await? .file("image", "/path/to/image.jpg").await? .file("archive", "/path/to/archive.zip").await?; client.post(url).multipart(form).send().await? ``` -------------------------------- ### Build Development Reqwest Client Source: https://github.com/seanmonstar/reqwest/blob/master/_autodocs/configuration.md Configure a client for development by accepting invalid certificates and hostnames. Sets a default timeout. ```rust let client = reqwest::Client::builder() .dangerous_accept_invalid_certs(true) .dangerous_accept_invalid_hostnames(true) .timeout(Duration::from_secs(30)) .build()?; ```