### Build Weather Client Example Source: https://context7.com/bdbai/nyquest/llms.txt A complete example demonstrating how to build a Nyquest client and use it to fetch weather information from an external API. It includes basic error handling for non-successful HTTP responses. ```rust use nyquest::{ClientBuilder, blocking::Request}; fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() .user_agent("curl/7.68.0 nyquest/0") .build_blocking()?; // Fetch weather for Tokyo (NRT airport) let response = client.request(Request::get("https://wttr.in/nrt"))?; let status = response.status(); if !status.is_successful() { let text = response.text()?; panic!("wttr.in returned non-success response {}: \n{}", status, text); } let weather = response.text()?; println!("{}", weather); Ok(()) } ``` -------------------------------- ### Perform a Simple GET Request (Async) Source: https://context7.com/bdbai/nyquest/llms.txt Use the `r#async::get` shortcut for asynchronous GET requests. This function returns a future that resolves to the response. Use `.await` to get the response and `.text().await` for the body. ```rust use nyquest::r#async; async fn fetch_data() -> nyquest::Result<()> { // Quick async GET request let response = r#async::get("https://httpbin.org/get").await?; println!("Status: {}", response.status()); // Get response body as text let body = response.text().await?; println!("Body: {}", body); Ok(()) } ``` -------------------------------- ### Perform a Simple GET Request (Blocking) Source: https://context7.com/bdbai/nyquest/llms.txt Use the `blocking::get` shortcut for quick GET requests without explicitly creating a client. This is suitable for single requests; create a client instance for multiple requests. ```rust use nyquest::blocking; fn main() -> nyquest::Result<()> { nyquest_preset::register(); // Quick GET request using shortcut let response = blocking::get("https://httpbin.org/get")?; println!("Status: {}", response.status()); println!("Content-Length: {:?}", response.content_length()); // Get response body as text let body = response.text()?; println!("Body: {}", body); Ok(()) } ``` -------------------------------- ### Use Predefined Header Constants Source: https://context7.com/bdbai/nyquest/llms.txt Utilize constants from the `header` module for standard HTTP header names to ensure consistency and avoid typos. This example demonstrates setting common headers for a request. ```rust use nyquest::{ClientBuilder, blocking::Request, header}; fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() .with_header(header::ACCEPT, "application/json") .with_header(header::ACCEPT_LANGUAGE, "en-US,en;q=0.9") .build_blocking()?; let response = client.request( Request::get("https://httpbin.org/headers") .with_header(header::AUTHORIZATION, "Bearer token123") .with_header(header::CACHE_CONTROL, "no-cache") .with_header(header::CONTENT_TYPE, "application/json") .with_header(header::USER_AGENT, "CustomAgent/1.0") )?; println!("Response: {}", response.text()?); Ok(()) } ``` -------------------------------- ### Handle Nyquest Errors Source: https://context7.com/bdbai/nyquest/llms.txt Demonstrates how to handle various typed errors provided by Nyquest, such as network issues, timeouts, and non-successful HTTP status codes. This example uses blocking requests. ```rust use nyquest::{ClientBuilder, blocking::Request, Error}; fn main() { nyquest_preset::register(); let client = ClientBuilder::default() .request_timeout(std::time::Duration::from_millis(1)) .build_blocking() .expect("Failed to create client"); match client.request(Request::get("https://httpbin.org/delay/5")) { Ok(response) => { match response.with_successful_status() { Ok(resp) => println!("Success: {}", resp.text().unwrap()), Err(Error::NonSuccessfulStatusCode(status)) => { println!("HTTP error: {}", status); } Err(e) => println!("Error: {}", e), } } Err(Error::InvalidUrl) => println!("Invalid URL provided"), Err(Error::Io(e)) => println!("IO error: {}", e), Err(Error::ResponseTooLarge) => println!("Response exceeded size limit"), Err(Error::RequestTimeout) => println!("Request timed out"), Err(e) => println!("Other error: {}", e), } } ``` -------------------------------- ### Register Nyquest Preset Backend Source: https://context7.com/bdbai/nyquest/llms.txt Register the preset backend at program startup. This automatically selects the appropriate backend based on the target platform. ```rust fn main() { nyquest_preset::register(); // Now nyquest clients can be created and used let client = nyquest::ClientBuilder::default() .build_blocking() .expect("Failed to build client"); } ``` -------------------------------- ### Create an Async Nyquest Client Source: https://context7.com/bdbai/nyquest/llms.txt Build an asynchronous HTTP client. Async clients return `Send` futures and do not require a specific async runtime. Configure options like base URL, user agent, timeouts, and redirect/cookie behavior. ```rust use nyquest::ClientBuilder; use std::time::Duration; async fn create_async_client() -> nyquest::Result<()> { let client = ClientBuilder::default() .base_url("https://api.example.com") .user_agent("MyApp/1.0") .request_timeout(Duration::from_secs(30)) .no_redirects() .no_cookies() .build_async() .await?; println!("Async client created: {:?}", client); Ok(()) } ``` -------------------------------- ### Configure Nyquest Client with Options Source: https://context7.com/bdbai/nyquest/llms.txt Customize HTTP client behavior using ClientBuilder options like base URL, timeouts, caching, and security settings. Ensure to use `dangerously_ignore_certificate_errors` only for development. ```rust use nyquest::ClientBuilder; use std::time::Duration; fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() // Base URL for relative request URIs .base_url("https://api.example.com/v1") // Custom User-Agent header .user_agent("MyApp/2.0 (Rust)") // Default headers for all requests .with_header("Authorization", "Bearer token") .with_header("Accept", "application/json") // Request timeout (implementation precision varies by backend) .request_timeout(Duration::from_secs(30)) // Maximum response body size for text()/bytes() methods .max_response_buffer_size(50 * 1024 * 1024) // 50MB // Disable response caching .no_caching() // Bypass system proxy settings .no_proxy() // Disable cookie handling between requests .no_cookies() // Disable automatic redirect following .no_redirects() // WARNING: Only for development/testing - ignores SSL certificate errors .dangerously_ignore_certificate_errors() .build_blocking()?; println!("Configured client: {:?}", client); Ok(()) } ``` -------------------------------- ### Register Default Nyquest Backend Source: https://github.com/bdbai/nyquest/blob/main/presets/default/README.md Call this at program startup to register the default nyquest backend based on the target platform. Refer to nyquest documentation for usage details. ```rust nyquest_backend::register(); ``` -------------------------------- ### Make Async HTTP Requests Source: https://context7.com/bdbai/nyquest/llms.txt Construct and send asynchronous HTTP requests using the `Request` builder and the client's `request` method. Operations must be awaited. ```rust use nyquest::{ClientBuilder, r#async::Request}; async fn make_async_requests() -> nyquest::Result<()> { let client = ClientBuilder::default() .base_url("https://httpbin.org") .build_async() .await?; // GET request let response = client.request( Request::get("/get") .with_header("Accept", "application/json") ).await?; let body = response.text().await?; println!("Response: {}", body); Ok(()) } ``` -------------------------------- ### Create a Blocking Nyquest Client Source: https://context7.com/bdbai/nyquest/llms.txt Build a blocking HTTP client with configurable options like base URL, user agent, headers, timeouts, and caching behavior. Clients are thread-safe and should be reused. ```rust use nyquest::ClientBuilder; use std::time::Duration; fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() .base_url("https://api.example.com") .user_agent("MyApp/1.0") .with_header("Authorization", "Bearer token123") .request_timeout(Duration::from_secs(30)) .max_response_buffer_size(10 * 1024 * 1024) // 10MB .no_caching() .build_blocking()?; // Client is now ready for requests println!("Client created: {:?}", client); Ok(()) } ``` -------------------------------- ### Register Reqwest Backend for Nyquest Source: https://github.com/bdbai/nyquest/blob/main/backends/reqwest/README.md Register the reqwest backend to use it as the default for the nyquest HTTP client. This requires the nyquest crate to be in scope. ```rust nyquest_backend_reqwest::register(); // Now you can use nyquest with the reqwest backend // (This example requires the nyquest crate to be in scope) // let response = nyquest::r#async::get("https://httpbin.org/get").await?; ``` -------------------------------- ### Make Blocking HTTP Requests Source: https://context7.com/bdbai/nyquest/llms.txt Construct and send blocking HTTP requests using the `Request` builder and the client's `request` method. Requires setting a base URL for the client. ```rust use nyquest::{ClientBuilder, blocking::Request}; fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() .base_url("https://httpbin.org") .build_blocking()?; // GET request with custom header let response = client.request( Request::get("/headers") .with_header("X-Custom-Header", "custom-value") )?; println!("GET response: {}", response.text()?); // HEAD request let response = client.request(Request::head("/get"))?; println!("HEAD status: {}", response.status()); // DELETE request let response = client.request(Request::delete("/delete"))?; println!("DELETE status: {}", response.status()); Ok(()) } ``` -------------------------------- ### Multipart Form Upload Source: https://context7.com/bdbai/nyquest/llms.txt Enable the `multipart` feature to upload files and form fields as multipart/form-data. Create parts with `Part` and `PartBody` types. ```rust use nyquest::{ClientBuilder, blocking::{Request, Body, Part, PartBody}}; fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() .build_blocking()?; let file_content = b"Hello, this is file content!"; // Multipart form with file upload (requires "multipart" feature) let response = client.request( Request::post("https://httpbin.org/post") .with_body(Body::multipart([ // Text field Part::new_with_content_type( "description", "text/plain", PartBody::text("File description") ), // File upload Part::new_with_content_type( "file", "application/octet-stream", PartBody::bytes(file_content.to_vec()) ) .with_filename("document.txt") .with_header("X-Custom-Part-Header", "value"), ])) )?; println!("Upload response: {}", response.text()?); Ok(()) } ``` -------------------------------- ### POST Request with Binary Body Source: https://context7.com/bdbai/nyquest/llms.txt Use `Body::binary_bytes` for binary data with `application/octet-stream` content type, or `Body::bytes` for custom content types. ```rust use nyquest::{ClientBuilder, blocking::{Request, Body}}; fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() .build_blocking()?; let binary_data: Vec = vec![0x00, 0x01, 0x02, 0x03, 0xFF]; // POST with binary body (application/octet-stream) let response = client.request( Request::post("https://httpbin.org/post") .with_body(Body::binary_bytes(binary_data)) )?; println!("Response: {}", response.text()?); // POST with custom binary content type let image_data: &'static [u8] = &[0x89, 0x50, 0x4E, 0x47]; // PNG header let response = client.request( Request::post("https://httpbin.org/post") .with_body(Body::bytes(image_data, "image/png")) )?; println!("Image upload response: {}", response.status()); Ok(()) } ``` -------------------------------- ### Stream Response Body (Async) Source: https://context7.com/bdbai/nyquest/llms.txt Use this for asynchronous streaming downloads, reading response bodies as `futures_io::AsyncRead` streams. Requires the `async-stream` feature. ```rust use nyquest::{ClientBuilder, r#async::Request}; use futures::io::AsyncReadExt; async fn stream_response() -> nyquest::Result<()> { let client = ClientBuilder::default() .build_async() .await?; let response = client.request(Request::get("https://httpbin.org/stream/5")).await?; // Convert response to AsyncRead stream (requires "async-stream" feature) let mut stream = response.into_async_read(); let mut buffer = [0u8; 1024]; loop { let bytes_read = stream.read(&mut buffer).await?; if bytes_read == 0 { break; } print!("{}", String::from_utf8_lossy(&buffer[..bytes_read])); } Ok(()) } ``` -------------------------------- ### Reading Response Headers Source: https://context7.com/bdbai/nyquest/llms.txt Use `get_header` to retrieve response header values. Multiple values may be returned if the header appears multiple times. ```rust use nyquest::{ClientBuilder, blocking::Request}; fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() .build_blocking()?; let response = client.request(Request::get("https://httpbin.org/response-headers?X-Custom=value1&X-Custom=value2"))?; // Get content-length if known if let Some(len) = response.content_length() { println!("Content-Length: {}", len); } // Get header values (may return multiple values) let content_type = response.get_header("content-type")?; println!("Content-Type: {:?}", content_type); let custom_headers = response.get_header("x-custom")?; for value in custom_headers { println!("X-Custom: {}", value); } Ok(()) } ``` -------------------------------- ### POST Request with Plain Text Body Source: https://context7.com/bdbai/nyquest/llms.txt Send a POST request with a plain text body using `Body::plain_text`. For custom content types, use `Body::text`. ```rust use nyquest::{ClientBuilder, blocking::{Request, Body}}; fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() .build_blocking()?; // POST with plain text body let response = client.request( Request::post("https://httpbin.org/post") .with_header("X-Request-ID", "12345") .with_body(Body::plain_text("Hello, World!")) )?; println!("Response: {}", response.text()?); // POST with custom content type let response = client.request( Request::post("https://httpbin.org/post") .with_body(Body::text("data", "application/xml")) )?; println!("XML Response: {}", response.text()?); Ok(()) } ``` -------------------------------- ### POST Request with Form Data Source: https://context7.com/bdbai/nyquest/llms.txt Send a POST request with URL-encoded form data using the `body_form!` macro. The macro accepts key-value pairs. ```rust use nyquest::{ClientBuilder, blocking::Request, body_form}; fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() .build_blocking()?; // POST with URL-encoded form data using macro let response = client.request( Request::post("https://httpbin.org/post") .with_body(body_form! { "username" => "john_doe", "password" => "secret123", "remember" => "true", }) )?; println!("Status: {}", response.status()); println!("Response: {}", response.text()?); Ok(()) } ``` -------------------------------- ### POST Request with JSON Body Source: https://context7.com/bdbai/nyquest/llms.txt Send a POST request with a JSON body using `Body::json`. Requires the `json` feature to be enabled. Response can be deserialized into a struct. ```rust use nyquest::{ClientBuilder, blocking::{Request, Body}}; use serde::{Serialize, Deserialize}; #[derive(Serialize)] struct CreateUser { name: String, email: String, age: u32, } #[derive(Deserialize, Debug)] struct ApiResponse { json: CreateUser, url: String, } fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() .build_blocking()?; let user = CreateUser { name: "John Doe".to_string(), email: "john@example.com".to_string(), age: 30, }; // POST with JSON body (requires "json" feature) let response = client.request( Request::post("https://httpbin.org/post") .with_body(Body::json(&user)?) )?; // Deserialize JSON response let api_response: ApiResponse = response.json()?; println!("Response: {:?}", api_response); Ok(()) } ``` -------------------------------- ### Stream Response Body (Blocking) Source: https://context7.com/bdbai/nyquest/llms.txt Use this when you need to read large response bodies or process real-time data using a blocking `std::io::Read` stream. Requires the `blocking-stream` feature. ```rust use nyquest::{ClientBuilder, blocking::Request}; use std::io::Read; fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() .build_blocking()?; let response = client.request(Request::get("https://httpbin.org/stream/5"))?; // Convert response to Read stream (requires "blocking-stream" feature) let mut stream = response.into_read(); let mut buffer = [0u8; 1024]; loop { let bytes_read = stream.read(&mut buffer)?; if bytes_read == 0 { break; } print!("{}", String::from_utf8_lossy(&buffer[..bytes_read])); } Ok(()) } ``` -------------------------------- ### Stream Request Body (Blocking) Source: https://context7.com/bdbai/nyquest/llms.txt Upload data from `std::io::Read + Seek` streams using blocking I/O. Use `Body::stream` for sized streams or `Body::stream_unsized` for chunked transfer encoding. Requires the `blocking-stream` feature. ```rust use nyquest::{ClientBuilder, blocking::{Request, Body}}; use std::io::Cursor; fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() .build_blocking()?; let data = b"Large file content here..."; let stream = Cursor::new(data.to_vec()); // Upload with known size (requires "blocking-stream" feature) let response = client.request( Request::post("https://httpbin.org/post") .with_body(Body::stream(stream, "application/octet-stream", data.len() as u64)) )?; println!("Upload response: {}", response.text()?); Ok(()) } ``` -------------------------------- ### Handling Response Status Codes Source: https://context7.com/bdbai/nyquest/llms.txt The `StatusCode` type provides methods to check response status categories. Use `with_successful_status()` to convert non-2xx responses to errors. ```rust use nyquest::{ClientBuilder, blocking::Request, StatusCode}; fn main() -> nyquest::Result<()> { nyquest_preset::register(); let client = ClientBuilder::default() .build_blocking()?; let response = client.request(Request::get("https://httpbin.org/status/404"))?; let status = response.status(); // Check status code categories println!("Status code: {}", status.code()); println!("Is informational (1xx): {}", status.is_informational()); println!("Is successful (2xx): {}", status.is_successful()); println!("Is redirection (3xx): {}", status.is_redirection()); println!("Is client error (4xx): {}", status.is_client_error()); println!("Is server error (5xx): {}", status.is_server_error()); // Compare with u16 if status == 404 { println!("Resource not found"); } // Convert non-successful status to error let response = client.request(Request::get("https://httpbin.org/get"))?; let response = response.with_successful_status()?; // Returns Error if not 2xx println!("Success: {}", response.text()?); Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.