### Example of adding multiple query parameters Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.RequestBuilder.html Demonstrates how to add multiple query parameters to a GET request using the `params` method. ```rust attohttpc::get("http://foo.bar").params(&[("p1", "v1"), ("p2", "v2")]); ``` -------------------------------- ### GET Request Builder Source: https://docs.rs/attohttpc/0.30.1/attohttpc/fn.get.html This snippet shows how to initiate a GET request using the `get` function from the attohttpc library. ```APIDOC ## GET / ### Description Creates a new `RequestBuilder` with the GET method. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body for GET" } ``` ### Response #### Success Response (200) - **RequestBuilder** (object) - An object that can be used to configure and send the GET request. #### Response Example ```json { "example": "RequestBuilder object" } ``` ``` -------------------------------- ### POST /https://my-api.org/do/something Source: https://docs.rs/attohttpc/0.30.1/attohttpc/index.html Example of making a POST request with headers, query parameters, and a JSON body. ```APIDOC ## POST /https://my-api.org/do/something ### Description This endpoint demonstrates how to make a POST request to a specified URL, including setting custom headers, query parameters, and a JSON payload. ### Method POST ### Endpoint https://my-api.org/do/something ### Parameters #### Query Parameters - **qux** (string) - Optional - A query parameter named 'qux' with value 'baz'. #### Request Body - **obj** (json) - Required - A JSON object to be sent as the request body. ### Request Example ```rust let obj = json!({ "hello": "world", }); let resp = attohttpc::post("https://my-api.org/do/something") .header("X-My-Header", "foo") // set a header for the request .param("qux", "baz") // set a query parameter .json(&obj)? // set the request body (json feature required) .send()?; // send the request ``` ### Response #### Success Response (200) - **text** (string) - The response body as text. #### Response Example ``` // Assuming the server responds with text println!("{}", resp.text()?); ``` ``` -------------------------------- ### Create GET Request Builder with attohttpc Source: https://docs.rs/attohttpc/0.30.1/attohttpc/fn.get.html Use this function to create a new `RequestBuilder` for making HTTP GET requests. It requires a URL as input. ```rust pub fn get(base_url: U) -> RequestBuilder where U: AsRef, ``` -------------------------------- ### GET attohttpc::header::DATE Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/constant.DATE.html Documentation for the DATE constant representing the HTTP Date header. ```APIDOC ## DATE ### Description Contains the date and time at which the message was originated. ### Constant `pub const DATE: HeaderName;` ``` -------------------------------- ### Consuming Iteration of HeaderMap Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderMap.html Examples demonstrating how to consume a HeaderMap via into_iter, handling both single and multiple values per header key. ```rust let mut map = HeaderMap::new(); map.insert(header::CONTENT_LENGTH, "123".parse().unwrap()); map.insert(header::CONTENT_TYPE, "json".parse().unwrap()); let mut iter = map.into_iter(); assert_eq!(iter.next(), Some((Some(header::CONTENT_LENGTH), "123".parse().unwrap()))); assert_eq!(iter.next(), Some((Some(header::CONTENT_TYPE), "json".parse().unwrap()))); assert!(iter.next().is_none()); ``` ```rust let mut map = HeaderMap::new(); map.append(header::CONTENT_LENGTH, "123".parse().unwrap()); map.append(header::CONTENT_LENGTH, "456".parse().unwrap()); map.append(header::CONTENT_TYPE, "json".parse().unwrap()); map.append(header::CONTENT_TYPE, "html".parse().unwrap()); map.append(header::CONTENT_TYPE, "xml".parse().unwrap()); let mut iter = map.into_iter(); assert_eq!(iter.next(), Some((Some(header::CONTENT_LENGTH), "123".parse().unwrap()))); assert_eq!(iter.next(), Some((None, "456".parse().unwrap()))); assert_eq!(iter.next(), Some((Some(header::CONTENT_TYPE), "json".parse().unwrap()))); assert_eq!(iter.next(), Some((None, "html".parse().unwrap()))); assert_eq!(iter.next(), Some((None, "xml".parse().unwrap()))); assert!(iter.next().is_none()); ``` -------------------------------- ### Get a reference to the first value Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.OccupiedEntry.html Returns a reference to the first value in the entry. Panics if no values are associated with the entry. ```rust let mut map = HeaderMap::new(); map.insert(HOST, "hello.world".parse().unwrap()); if let Entry::Occupied(mut e) = map.entry("host") { assert_eq!(e.get(), &"hello.world"); e.append("hello.earth".parse().unwrap()); assert_eq!(e.get(), &"hello.world"); } ``` -------------------------------- ### Invalid Header Parsing Examples - HeaderName Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderName.html Demonstrates invalid inputs for `from_static` which will cause a panic at compile time. This includes headers with invalid symbols or uppercase characters. ```rust // Parsing a header that contains invalid symbols(s): HeaderName::from_static("content{}{}length"); // This line panics! // Parsing a header that contains invalid uppercase characters. let a = HeaderName::from_static("foobar"); let b = HeaderName::from_static("FOOBAR"); // This line panics! ``` -------------------------------- ### MultipartFile constructor and configuration methods Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.MultipartFile.html Methods for creating a new MultipartFile and configuring its properties. ```rust pub fn new(name: &'key str, file: &'data [u8]) -> Self ``` ```rust pub fn with_type(self, mime_type: impl AsRef) -> Result ``` ```rust pub fn with_filename(self, filename: &'key str) -> Self ``` -------------------------------- ### get Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderMap.html Retrieves a reference to the value associated with a specific header key. ```APIDOC ## get ### Description Returns a reference to the value associated with the key. If multiple values exist, the first one is returned. ### Parameters #### Query Parameters - **key** (AsHeaderName) - Required - The header name to look up. ### Response #### Success Response (200) - **Option<&T>** - Returns the value if found, otherwise None. ``` -------------------------------- ### Using StatusCode Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.StatusCode.html Demonstrates basic usage of StatusCode constants and conversion methods. ```rust use http::StatusCode; assert_eq!(StatusCode::from_u16(200).unwrap(), StatusCode::OK); assert_eq!(StatusCode::NOT_FOUND.as_u16(), 404); assert!(StatusCode::OK.is_success()); ``` -------------------------------- ### Get HeaderValue length Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderValue.html The `len` method returns the length of the `HeaderValue` in bytes. ```rust pub fn len(&self) -> usize ``` -------------------------------- ### Configure crate features Source: https://docs.rs/attohttpc Shows how to enable specific features for the attohttpc crate in a Cargo.toml file. ```toml attohttpc = { version = "...", features = ["json", "form", ...] } ``` -------------------------------- ### Get Type ID Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.TextReader.html Retrieves the `TypeId` of the current type. This is part of the `Any` trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### HeaderMap::entry Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderMap.html Gets the given key’s corresponding entry in the map for in-place manipulation. ```APIDOC ## HeaderMap::entry ### Description Provides an entry API for in-place manipulation of a header value. ### Parameters - **key** (IntoHeaderName) - Required - The header name to access. ### Response - **Entry<'_, T>** - An entry object for the specified key. ``` -------------------------------- ### Define and Inspect HTTP Methods Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.Method.html Demonstrates creating a Method from bytes and checking its properties like idempotency and string representation. ```rust use http::Method; assert_eq!(Method::GET, Method::from_bytes(b"GET").unwrap()); assert!(Method::GET.is_idempotent()); assert_eq!(Method::POST.as_str(), "POST"); ``` -------------------------------- ### Basic HeaderMap Usage Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderMap.html Demonstrates fundamental operations on HeaderMap, including insertion, checking for keys, accessing values, removal, and verifying emptiness. ```rust let mut headers = HeaderMap::new(); headers.insert(HOST, "example.com".parse().unwrap()); headers.insert(CONTENT_LENGTH, "123".parse().unwrap()); assert!(headers.contains_key(HOST)); assert!(!headers.contains_key(LOCATION)); assert_eq!(headers[HOST], "example.com"); headers.remove(HOST); assert!(!headers.contains_key(HOST)); ``` -------------------------------- ### Unwrap Error Value Source: https://docs.rs/attohttpc/0.30.1/attohttpc/type.Result.html Use `unwrap_err()` to get the contained `Err` value. Panics if the value is an `Ok`. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### POST / Source: https://docs.rs/attohttpc/0.30.1/attohttpc/fn.post.html Initializes a new RequestBuilder configured with the POST HTTP method for a given base URL. ```APIDOC ## POST ### Description Creates a new `RequestBuilder` instance configured with the POST method for the specified base URL. ### Method POST ### Parameters #### Path Parameters - **base_url** (AsRef) - Required - The base URL to which the POST request will be directed. ### Response - **RequestBuilder** - Returns a `RequestBuilder` object configured for further request customization. ``` -------------------------------- ### Unwrap Ok Value Source: https://docs.rs/attohttpc/0.30.1/attohttpc/type.Result.html Use `unwrap()` to get the contained `Ok` value. Panics if the value is an `Err`. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### POST Request with JSON Source: https://docs.rs/attohttpc Demonstrates how to perform a POST request with custom headers, query parameters, and a JSON body. ```APIDOC ## POST [URL] ### Description Sends a POST request to the specified URL with custom headers, query parameters, and a JSON payload. ### Method POST ### Request Example ```json { "hello": "world" } ``` ### Response #### Success Response (2XX) - **body** (text) - The response body returned by the server. ``` -------------------------------- ### Getting Canonical Reason Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.StatusCode.html Retrieves the standard reason phrase for a status code, intended for human readers. ```rust let status = http::StatusCode::OK; assert_eq!(status.canonical_reason(), Some("OK")); ``` -------------------------------- ### Creating a StatusCode Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.StatusCode.html Demonstrates how to create a StatusCode instance from a u16 value or a byte slice. Includes error handling for invalid values. ```APIDOC ## Creating a StatusCode ### `from_u16(src: u16) -> Result` Converts a u16 to a status code. The function validates the correctness of the supplied u16. It must be greater or equal to 100 and less than 1000. #### Example ```rust use http::StatusCode; let ok = StatusCode::from_u16(200).unwrap(); assert_eq!(ok, StatusCode::OK); let err = StatusCode::from_u16(99); assert!(err.is_err()); ``` ### `from_bytes(src: &[u8]) -> Result` Converts a `&[u8]` to a status code. ``` -------------------------------- ### ProxySettings Methods Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.ProxySettings.html Methods for creating and utilizing proxy configurations. ```APIDOC ## ProxySettings::builder ### Description Get a new builder for ProxySettings. ## ProxySettings::from_env ### Description Get the proxy configuration from the environment using the curl/Unix proxy conventions. Only ALL_PROXY, HTTP_PROXY, HTTPS_PROXY and NO_PROXY are supported. ## ProxySettings::for_url ### Description Get the proxy URL to use for the given URL. Returns None if there is no proxy configured for the scheme or if the hostname matches a pattern in the no proxy list. ### Parameters #### Path Parameters - **url** (Url) - Required - The URL to check for proxy configuration. ``` -------------------------------- ### Get mutable request headers Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.RequestBuilder.html Retrieves a mutable reference to the request's HeaderMap, allowing modifications. ```rust pub fn headers_mut(&mut self) -> &mut HeaderMap ``` -------------------------------- ### Try Create HeaderMap with Capacity Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderMap.html Attempts to create an empty HeaderMap with a specified capacity, returning a Result. This allows for error handling if the requested capacity exceeds the maximum allowed size. ```rust let map: HeaderMap = HeaderMap::try_with_capacity(10).unwrap(); assert!(map.is_empty()); assert_eq!(12, map.capacity()); ``` -------------------------------- ### Initialize a HEAD request with attohttpc Source: https://docs.rs/attohttpc/0.30.1/attohttpc/fn.head.html Creates a new RequestBuilder configured for the HEAD method using a base URL. ```rust pub fn head(base_url: U) -> RequestBuilder where U: AsRef, ``` -------------------------------- ### Get a mutable reference to the first value Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.OccupiedEntry.html Returns a mutable reference to the first value. Panics if no values are associated with the entry. ```rust let mut map = HeaderMap::default(); map.insert(HOST, "hello.world".to_string()); if let Entry::Occupied(mut e) = map.entry("host") { e.get_mut().push_str("-2"); assert_eq!(e.get(), &"hello.world-2"); } ``` -------------------------------- ### MultipartFile Implementations Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.MultipartFile.html Details on the implementations and traits for the MultipartFile struct. ```APIDOC ## Implementations for MultipartFile ### `Clone` Trait Allows creating a duplicate of a `MultipartFile` instance. #### `clone(&self) -> MultipartFile<'key, 'data>` Returns a duplicate of the value. #### `clone_from(&mut self, source: &Self)` Performs copy-assignment from `source`. ### `Debug` Trait Provides formatting for debugging purposes. #### `fmt(&self, f: &mut Formatter<'_>) -> Result` Formats the value using the given formatter. ### Auto Trait Implementations These are standard Rust traits automatically implemented for `MultipartFile`: - `Freeze` - `RefUnwindSafe` - `Send` - `Sync` - `Unpin` - `UnwindSafe` ### Blanket Implementations These are implementations provided by Rust's standard library for generic types, applicable to `MultipartFile`: - `Any` - `Borrow` - `BorrowMut` - `CloneToUninit` (Nightly-only experimental) - `From` - `Into` - `ToOwned` - `TryFrom` - `TryInto` - `VZip` - `ErasedDestructor` ``` -------------------------------- ### Type Conversion Traits Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.IterMut.html Documentation for `TryFrom`, `TryInto`, and related type conversion functionalities. ```APIDOC ## Type Conversion Traits ### `TryFrom` for `T` Allows conversion from type `U` into type `T`. - **`type Error`**: The type returned in the event of a conversion error. - **`fn try_from(value: U) -> Result>::Error>`**: Performs the conversion. ### `TryInto` for `T` Allows conversion from type `T` into type `U`. - **`type Error`**: The type returned in the event of a conversion error. - **`fn try_into(self) -> Result>::Error>`**: Performs the conversion. ### `VZip` for `T` Provides functionality for zipping multiple lanes. - **`fn vzip(self) -> V`**: Zips the lanes. ``` -------------------------------- ### Into Err Value (Never Panics) Source: https://docs.rs/attohttpc/0.30.1/attohttpc/type.Result.html Use `into_err()` to get the contained `Err` value. This method is guaranteed not to panic. It is an experimental API. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Into Ok Value (Never Panics) Source: https://docs.rs/attohttpc/0.30.1/attohttpc/type.Result.html Use `into_ok()` to get the contained `Ok` value. This method is guaranteed not to panic. It is an experimental API. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### TryFrom and TryInto for Type Conversions Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.RequestBuilder.html Details on how to perform fallible type conversions using TryFrom and TryInto. ```APIDOC ## TryFrom for T ### Description Provides a fallible way to convert a value of type `U` into a value of type `T`. ### Method `try_from` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) `Result>::Error>` #### Response Example None ## TryInto for T ### Description Provides a fallible way to convert a value of type `T` into a value of type `U`. ### Method `try_into` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) `Result>::Error>` #### Response Example None ## Error Type for Conversions ### Description The `Error` type associated with `TryFrom` and `TryInto` conversions, indicating failure. ### Method None ### Endpoint None ### Parameters None ### Request Example None ### Response #### Success Response (200) `Infallible` (for `TryFrom`) `>::Error` (for `TryInto`) #### Response Example None ``` -------------------------------- ### Expect Error with Custom Message Source: https://docs.rs/attohttpc/0.30.1/attohttpc/type.Result.html Use `expect_err()` to get the contained `Err` value. Panics with a custom message if the value is an `Ok`. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### X_DNS_PREFETCH_CONTROL Header Constant Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/constant.X_DNS_PREFETCH_CONTROL.html Documentation for the X_DNS_PREFETCH_CONTROL constant used to manage DNS prefetching. ```APIDOC ## Constant X_DNS_PREFETCH_CONTROL ### Description Controls DNS prefetching. The `x-dns-prefetch-control` HTTP response header controls DNS prefetching, a feature by which browsers proactively perform domain name resolution. ### Definition `pub const X_DNS_PREFETCH_CONTROL: HeaderName;` ``` -------------------------------- ### Retrieve Header Values Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderMap.html Access values associated with a specific key. get returns a reference, while get_mut provides a mutable reference. ```rust let mut map = HeaderMap::new(); assert!(map.get("host").is_none()); map.insert(HOST, "hello".parse().unwrap()); assert_eq!(map.get(HOST).unwrap(), &"hello"); assert_eq!(map.get("host").unwrap(), &"hello"); map.append(HOST, "world".parse().unwrap()); assert_eq!(map.get("host").unwrap(), &"hello"); ``` ```rust let mut map = HeaderMap::default(); map.insert(HOST, "hello".to_string()); map.get_mut("host").unwrap().push_str("-world"); assert_eq!(map.get(HOST).unwrap(), &"hello-world"); ``` -------------------------------- ### Convert HashMap to HeaderMap Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderMap.html Demonstrates the use of TryFrom to convert a standard library HashMap into a HeaderMap. ```rust use std::collections::HashMap; use std::convert::TryInto; use http::HeaderMap; let mut map = HashMap::new(); map.insert("X-Custom-Header".to_string(), "my value".to_string()); let headers: HeaderMap = (&map).try_into().expect("valid headers"); assert_eq!(headers["X-Custom-Header"], "my value"); ``` -------------------------------- ### Iterate over header values with GetAll Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.GetAll.html Demonstrates how to retrieve all values for a specific header key and iterate through them using the iter method. ```rust let mut map = HeaderMap::new(); map.insert(HOST, "hello.world".parse().unwrap()); map.append(HOST, "hello.earth".parse().unwrap()); let values = map.get_all("host"); let mut iter = values.iter(); assert_eq!(&"hello.world", iter.next().unwrap()); assert_eq!(&"hello.earth", iter.next().unwrap()); assert!(iter.next().is_none()); ``` -------------------------------- ### Get HeaderMap Capacity Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderMap.html Returns the current capacity of the HeaderMap, which is the approximate number of headers it can hold before needing to reallocate its internal storage. ```rust let mut map = HeaderMap::new(); assert_eq!(0, map.capacity()); map.insert(HOST, "hello.world".parse().unwrap()); assert_eq!(6, map.capacity()); ``` -------------------------------- ### Initialize RequestBuilder with OPTIONS method Source: https://docs.rs/attohttpc/0.30.1/attohttpc/fn.options.html Creates a new RequestBuilder instance configured for the OPTIONS HTTP method. ```rust pub fn options(base_url: U) -> RequestBuilder where U: AsRef, ``` -------------------------------- ### Body Content Type Method Source: https://docs.rs/attohttpc/0.30.1/attohttpc/body/trait.Body.html Gets the content type associated with the body, if one exists. This is a provided method in the Body trait. ```rust fn content_type(&mut self) -> IoResult> ``` -------------------------------- ### TRACE Method Initialization Source: https://docs.rs/attohttpc/0.30.1/attohttpc/fn.trace.html Initializes a new `RequestBuilder` with the TRACE HTTP method. This is useful for debugging and diagnosing network issues by requesting that the origin server echo back the received request. ```APIDOC ## POST /trace ### Description Creates a new `RequestBuilder` configured to send an HTTP TRACE request. ### Method TRACE ### Endpoint / ### Parameters #### Query Parameters - **base_url** (string) - Required - The base URL for the request. ### Request Example ```json { "example": "TRACE / HTTP/1.1\r\nHost: example.com\r\n\r\n" } ``` ### Response #### Success Response (200) - **response** (string) - The echoed request from the server. #### Response Example ```json { "example": "HTTP/1.1 200 OK\r\nContent-Type: message/http\r\n\r\nTRACE / HTTP/1.1\r\nHost: example.com\r\n\r\n" } ``` ``` -------------------------------- ### Providing a Default Value with unwrap_or Source: https://docs.rs/attohttpc/0.30.1/attohttpc/type.Result.html Use `unwrap_or` to get the `Ok` value or a specified default if the Result is `Err`. Arguments are eagerly evaluated. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Header: FROM Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/constant.FROM.html The FROM header contains an Internet email address for a human user who controls the requesting user agent. It is recommended for robotic user agents to include this header for contact purposes. ```APIDOC ## Constant FROM ### Description Contains an Internet email address for a human user who controls the requesting user agent. If you are running a robotic user agent (e.g. a crawler), the From header should be sent, so you can be contacted if problems occur on servers, such as if the robot is sending excessive, unwanted, or invalid requests. ### Source `attohttpc::header::FROM` ``` -------------------------------- ### Get Number of Keys in HeaderMap Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderMap.html Retrieves the number of unique keys present in the HeaderMap. This count will be less than or equal to the total number of values. ```rust let mut map = HeaderMap::new(); assert_eq!(0, map.keys_len()); map.insert(ACCEPT, "text/plain".parse().unwrap()); map.insert(HOST, "localhost".parse().unwrap()); assert_eq!(2, map.keys_len()); map.insert(ACCEPT, "text/html".parse().unwrap()); assert_eq!(2, map.keys_len()); ``` -------------------------------- ### Access Request Method Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.RequestInspector.html Retrieves the current HTTP method of the request. Use this to inspect the request's method (e.g., GET, POST). ```rust pub fn method(&self) -> &Method ``` -------------------------------- ### Session Initialization and Request Builders Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.Session.html Methods for creating a new Session and initiating requests with different HTTP methods. ```APIDOC ## Session Struct ### Description `Session` is a type that can carry settings over multiple requests. The settings applied to the `Session` are applied to every request created from this `Session`. `Session` can be cloned cheaply and sent to other threads as it uses std::sync::Arc internally. ## Session Methods ### `new()` #### Description Create a new `Session` with default settings. #### Method `pub fn new() -> Session` ### `get()` #### Description Create a new `RequestBuilder` with the GET method and this Session’s settings applied on it. #### Method `pub fn get(&self, base_url: U) -> RequestBuilder` ### `post()` #### Description Create a new `RequestBuilder` with the POST method and this Session’s settings applied on it. #### Method `pub fn post(&self, base_url: U) -> RequestBuilder` ### `put()` #### Description Create a new `RequestBuilder` with the PUT method and this Session’s settings applied on it. #### Method `pub fn put(&self, base_url: U) -> RequestBuilder` ### `delete()` #### Description Create a new `RequestBuilder` with the DELETE method and this Session’s settings applied on it. #### Method `pub fn delete(&self, base_url: U) -> RequestBuilder` ### `head()` #### Description Create a new `RequestBuilder` with the HEAD method and this Session’s settings applied on it. #### Method `pub fn head(&self, base_url: U) -> RequestBuilder` ### `options()` #### Description Create a new `RequestBuilder` with the OPTIONS method and this Session’s settings applied on it. #### Method `pub fn options(&self, base_url: U) -> RequestBuilder` ### `patch()` #### Description Create a new `RequestBuilder` with the PATCH method and this Session’s settings applied on it. #### Method `pub fn patch(&self, base_url: U) -> RequestBuilder` ### `trace()` #### Description Create a new `RequestBuilder` with the TRACE method and this Session’s settings applied on it. #### Method `pub fn trace(&self, base_url: U) -> RequestBuilder` ``` -------------------------------- ### Body Trait Implementation for Multipart Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.Multipart.html Provides methods for handling the multipart body, such as determining its kind, writing it to a writer, and getting its content type. ```APIDOC ## impl Body for Multipart<'_> ### fn kind(&mut self) -> IoResult Determine the kind of the request body. ### fn write(&mut self, writer: W) -> IoResult<()> Write out the request body into the given writer. ### fn content_type(&mut self) -> IoResult> Gets the content type this body is tied to if it has one. ``` -------------------------------- ### IF_MODIFIED_SINCE Header Constant Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/constant.IF_MODIFIED_SINCE.html Documentation for the IF_MODIFIED_SINCE header constant used to make conditional GET or HEAD requests based on modification dates. ```APIDOC ## IF_MODIFIED_SINCE ### Description The IF_MODIFIED_SINCE constant represents the 'If-Modified-Since' HTTP header. It makes a request conditional, where the server returns the resource only if it has been modified after the specified date. If not modified, the server returns a 304 status code. ### Usage - Only applicable for GET or HEAD requests. - If used with If-None-Match, it is ignored unless the server does not support If-None-Match. - Primarily used to update cached entities that lack an ETag. ``` -------------------------------- ### Iterator Adapters: Collection and Partitioning Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.IntoIter.html This section details methods for collecting iterator items into collections and partitioning them based on a predicate. ```APIDOC ## Iterator Adapters: Collection and Partitioning ### Description Methods for consuming iterators to create collections or partition elements. ### Methods #### `collect(self) -> B` - **Description**: Transforms an iterator into a collection. - **Type Parameters**: - `B`: The type of the collection, must implement `FromIterator`. - **Returns**: `B` #### `try_collect( &mut self, ) -> <::Residual as Residual>::TryType` - **Description**: Fallibly transforms an iterator into a collection, short-circuiting on failure. This is a nightly-only experimental API. - **Type Parameters**: - `B`: The type of the collection, must implement `FromIterator` and satisfy `Try` constraints. - **Returns**: A `TryType` representing the result of the collection attempt. #### `collect_into(self, collection: &mut E) -> &mut E` - **Description**: Collects all items from an iterator into a mutable collection. This is a nightly-only experimental API. - **Type Parameters**: - `E`: The type of the collection, must implement `Extend`. - **Parameters**: - `collection` (&mut E): A mutable reference to the collection to extend. - **Returns**: `&mut E` #### `partition(self, f: F) -> (B, B)` - **Description**: Consumes an iterator, creating two collections based on a predicate. - **Type Parameters**: - `B`: The type of the collections, must implement `Default` and `Extend`. - **Parameters**: - `f` (F): A closure that takes a reference to an item and returns a boolean. - **Returns**: A tuple of two collections `(B, B)`. #### `partition_in_place<'a, T, P>(self, predicate: P) -> usize` - **Description**: Reorders elements in-place according to a predicate and returns the count of `true` elements. This is a nightly-only experimental API. - **Type Parameters**: - `T`: The type of the elements. - `P`: The type of the predicate closure. - **Parameters**: - `predicate` (P): A closure that takes a reference to an element and returns a boolean. - **Returns**: `usize` (the number of elements for which the predicate returned `true`). #### `is_partitioned

(self, predicate: P) -> bool` - **Description**: Checks if elements are partitioned according to a predicate. This is a nightly-only experimental API. - **Parameters**: - `predicate` (P): A closure that takes an item and returns a boolean. - **Returns**: `bool` ``` -------------------------------- ### RequestBuilder Initialization Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.RequestBuilder.html Methods to initialize a new RequestBuilder instance. ```APIDOC ## new(method, base_url) ### Description Creates a new RequestBuilder with the base URL and the given method. ### Parameters - **method** (Method) - Required - The HTTP method to use. - **base_url** (AsRef) - Required - The base URL for the request. ## try_new(method, base_url) ### Description Attempts to create a new RequestBuilder, returning a Result. Returns an error if the URL is invalid or the method is CONNECT. ``` -------------------------------- ### Iterator enumerate() Method Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.Drain.html Creates an iterator that yields pairs of (index, element), starting with index 0. Useful when the position of an element is needed. ```rust fn enumerate(self) -> Enumerate where Self: Sized, ``` -------------------------------- ### Unwrap or Default Value Source: https://docs.rs/attohttpc/0.30.1/attohttpc/type.Result.html Use `unwrap_or_default()` to get the contained `Ok` value or the default value for the type if it's an `Err`. Requires the type to implement `Default`. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### Create TextReader Instance Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.TextReader.html Instantiates a new TextReader with a given inner reader and charset. Ensure the charset is correctly specified for accurate conversion. ```rust pub fn new(inner: R, charset: Charset) -> Self ``` -------------------------------- ### Convert HeaderValue to string slice Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderValue.html Use `to_str` to get a `&str` slice from a `HeaderValue` if it only contains visible ASCII characters. This function scans the entire header value. ```rust let val = HeaderValue::from_static("hello"); assert_eq!(val.to_str().unwrap(), "hello"); ``` -------------------------------- ### Create RequestBuilder with new Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.RequestBuilder.html Creates a new RequestBuilder with the specified HTTP method and base URL. Panics if the base URL is invalid or the method is CONNECT. ```rust pub fn new(method: Method, base_url: U) -> Self where U: AsRef ``` -------------------------------- ### HeaderName Methods Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderName.html Methods for creating and interacting with HeaderName instances. ```APIDOC ## HeaderName::from_bytes ### Description Converts a slice of bytes to an HTTP header name, normalizing the input. ### Parameters - **src** (&[u8]) - Required - The byte slice representing the header name. ### Response - **Result** - Returns the HeaderName or an error if the input is invalid. ## HeaderName::from_lowercase ### Description Converts a slice of bytes to an HTTP header name, expecting the input to already be lowercase. Useful for HTTP/2.0 or HTTP/3.0. ### Parameters - **src** (&[u8]) - Required - The lowercase byte slice. ### Response - **Result** - Returns the HeaderName or an error if the input contains uppercase characters or is invalid. ## HeaderName::from_static ### Description Converts a static string to an HTTP header name. Requires the string to be lowercase. ### Parameters - **src** (&'static str) - Required - The static string header name. ### Response - **HeaderName** - Returns the HeaderName. ### Errors - **Panics** - Panics if the static string contains invalid characters or uppercase letters. ## HeaderName::as_str ### Description Returns a string representation of the header name. ### Response - **&str** - The lowercase string representation. ``` -------------------------------- ### Collection and Partitioning Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.ValueIter.html Adapters for collecting iterator elements into collections or partitioning them. ```APIDOC ## fn collect(self) ### Description Transforms an iterator into a collection. ### Method `collect` ### Parameters - `B` (FromIterator) - The type of collection to create. ### Response - `B` - The resulting collection. ``` ```APIDOC ## fn try_collect( &mut self, ) ### Description Fallibly transforms an iterator into a collection, short circuiting if a failure is encountered. ### Method `try_collect` ### Parameters - `B` (::Residual as Residual).TryType - The type of collection to create, supporting fallible collection. ### Response - `<::Residual as Residual>::TryType` - The resulting collection or an error if collection failed. ``` ```APIDOC ## fn collect_into(self, collection: &mut E) ### Description Collects all the items from an iterator into a collection. ### Method `collect_into` ### Parameters - `collection` (&mut E) - A mutable reference to the collection to extend. ### Response - `&mut E` - The mutable reference to the collection after items have been added. ``` ```APIDOC ## fn partition(self, f: F) ### Description Consumes an iterator, creating two collections from it based on a predicate. ### Method `partition` ### Parameters - `f` (FnMut(&Self::Item) -> bool) - The closure to determine which partition an element belongs to. ### Response - `(B, B)` - A tuple containing two collections: one for elements where the predicate returned true, and one for false. ``` ```APIDOC ## fn partition_in_place<'a, T, P>(self, predicate: P) ### Description Reorders the elements of this iterator _in-place_ according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. ### Method `partition_in_place` ### Parameters - `predicate` (FnMut(&T) -> bool) - The closure to determine the partitioning criteria. ### Response - `usize` - The number of elements for which the predicate returned `true`. ``` ```APIDOC ## fn is_partitioned

(self, predicate: P) ### Description Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. ### Method `is_partitioned` ### Parameters - `predicate` (FnMut(Self::Item) -> bool) - The closure to check the partitioning. ### Response - `bool` - `true` if the iterator is partitioned, `false` otherwise. ``` -------------------------------- ### Get Number of Headers in HeaderMap Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderMap.html Retrieves the total number of header values stored in the map. This count can be greater than the number of unique keys if a key has multiple associated values. ```rust let mut map = HeaderMap::new(); assert_eq!(0, map.len()); map.insert(ACCEPT, "text/plain".parse().unwrap()); map.insert(HOST, "localhost".parse().unwrap()); assert_eq!(2, map.len()); map.append(ACCEPT, "text/html".parse().unwrap()); assert_eq!(3, map.len()); ``` -------------------------------- ### Lazily Computing a Default Value with unwrap_or_else Source: https://docs.rs/attohttpc/0.30.1/attohttpc/type.Result.html Use `unwrap_or_else` to get the `Ok` value or compute a default value using a closure if the Result is `Err`. This is preferred over `unwrap_or` for expensive default computations. ```rust fn count(x: &str) -> usize { x.len() } assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### Create PUT RequestBuilder with attohttpc Source: https://docs.rs/attohttpc/0.30.1/attohttpc/fn.put.html Use this function to initiate an HTTP PUT request. It requires a base URL as a string reference. ```rust pub fn put(base_url: U) -> RequestBuilder where U: AsRef, ``` -------------------------------- ### Enable HTTP basic authentication Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.RequestBuilder.html Enables HTTP basic authentication for the request using the provided username and an optional password. ```rust pub fn basic_auth( self, username: impl Display, password: Option, ) -> Self ``` -------------------------------- ### Iterate over HeaderMap values Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderMap.html Demonstrates how to iterate over values in a HeaderMap. ```rust let mut map = HeaderMap::new(); map.insert(HOST, "hello".parse().unwrap()); map.append(HOST, "goodbye".parse().unwrap()); map.insert(CONTENT_LENGTH, "123".parse().unwrap()); for value in map.values() { println!("{:?}", value); } ``` -------------------------------- ### VacantEntry Methods Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.VacantEntry.html Methods available for interacting with a VacantEntry instance. ```APIDOC ## VacantEntry Methods ### key() Returns a reference to the entry's key. ### into_key() Takes ownership of the key. ### insert(value: T) Inserts the value into the entry and returns a mutable reference to it. ### try_insert(value: T) Attempts to insert the value into the entry, returning a Result with a mutable reference or a MaxSizeReached error. ### insert_entry(value: T) Inserts the value and returns an OccupiedEntry for further manipulation. ### try_insert_entry(value: T) Attempts to insert the value and returns a Result containing an OccupiedEntry or a MaxSizeReached error. ``` -------------------------------- ### Perform an HTTP POST request Source: https://docs.rs/attohttpc Demonstrates sending a JSON-encoded POST request with headers and query parameters. Requires the 'json' feature flag. ```rust let obj = json!({ "hello": "world", }); let resp = attohttpc::post("https://my-api.org/do/something") .header("X-My-Header", "foo") // set a header for the request .param("qux", "baz") // set a query parameter .json(&obj)? // set the request body (json feature required) .send()?; // send the request // Check if the status is a 2XX code. if resp.is_success() { // Consume the response body as text and print it. println!("{}", resp.text()?); } ``` -------------------------------- ### TryFrom HashMap Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderMap.html Converting a standard HashMap into a HeaderMap. ```APIDOC ## TryFrom ### Description Attempts to convert a standard library HashMap into a HeaderMap. This is useful for initializing headers from existing key-value collections. ### Method try_from ### Parameters #### Request Body - **c** (&'a HashMap) - Required - The source HashMap to convert. ### Response #### Success Response (200) - **Result** (HeaderMap) - The resulting HeaderMap on success. #### Error Response - **Error** (Error) - The error type returned if the conversion fails. ``` -------------------------------- ### get_all Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderMap.html Returns a view of all values associated with a specific header key. ```APIDOC ## get_all ### Description Returns a view of all values associated with a key, allowing iteration over multiple values for the same header. ### Parameters #### Query Parameters - **key** (AsHeaderName) - Required - The header name to look up. ### Response #### Success Response (200) - **GetAll<'_, T>** - A view object containing all values for the key. ``` -------------------------------- ### Iterator Adapters: Other Utilities Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.IntoIter.html Miscellaneous iterator adapter methods like `by_ref`. ```APIDOC ## Iterator Adapters: Other Utilities ### Description Provides utility methods for working with iterators. ### Methods #### `by_ref(&mut self) -> &mut Self` - **Description**: Creates a “by reference” adapter for the iterator instance. - **Returns**: `&mut Self` ``` -------------------------------- ### Request Preparation and Sending Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.RequestBuilder.html Methods for preparing and sending the HTTP request. ```APIDOC ## Request Preparation and Sending ### Description These methods are used to finalize the request configuration and execute it. ### Methods #### `prepare(self) -> PreparedRequest` Creates a `PreparedRequest` from the current `RequestBuilder`. This method will panic if an error occurs during preparation. #### `try_prepare(self) -> Result>` Attempts to create a `PreparedRequest` from the current `RequestBuilder`. Returns a `Result` which is `Ok` on success or `Err` if preparation fails. #### `send(self) -> Result` Sends the request directly using the `RequestBuilder` configuration. Returns a `Result` containing the `Response` on success or an error if the request fails. ``` -------------------------------- ### Create a TextReader with charset from headers or default Source: https://docs.rs/attohttpc/0.30.1/attohttpc/struct.ResponseReader.html Creates a `TextReader` for decoding the response body. It uses charset information from response headers, falls back to a default encoding, or uses ISO-8859-1 if none is available. Requires the `charsets` feature. ```rust pub fn text_reader(self) -> TextReader> ``` -------------------------------- ### HTTP Request Methods Source: https://docs.rs/attohttpc The attohttpc crate provides functions for standard HTTP methods. ```APIDOC ## Supported HTTP Methods - **get**: Create a new RequestBuilder with the GET method. - **post**: Create a new RequestBuilder with the POST method. - **put**: Create a new RequestBuilder with the PUT method. - **delete**: Create a new RequestBuilder with the DELETE method. - **head**: Create a new RequestBuilder with the HEAD method. - **options**: Create a new RequestBuilder with the OPTIONS method. - **patch**: Create a new RequestBuilder with the PATCH method. - **trace**: Create a new RequestBuilder with the TRACE method. ``` -------------------------------- ### HeaderName Comparisons Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.HeaderName.html Details the PartialEq implementations for HeaderName, supporting case-insensitive comparisons against strings. ```APIDOC ## PartialEq for HeaderName ### Description Provides equality comparison logic for HeaderName, including case-insensitive comparisons against string types. ### Parameters #### Request Body - **other** (str/HeaderName) - Required - The value to compare against the HeaderName instance. ### Response #### Success Response (200) - **bool** - Returns true if the values are equal (case-insensitive for strings). ``` -------------------------------- ### Take ownership of the key Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.VacantEntry.html Consume the entry to take ownership of the underlying HeaderName. ```rust let mut map = HeaderMap::new(); if let Entry::Vacant(v) = map.entry("x-hello") { assert_eq!(v.into_key().as_str(), "x-hello"); } ``` -------------------------------- ### Partitioning Source: https://docs.rs/attohttpc/0.30.1/attohttpc/header/struct.ValueIterMut.html Methods for partitioning iterator elements into different collections. ```APIDOC ## fn partition(self, f: F) -> (B, B) ### Description Consumes an iterator, creating two collections from it. ### Method N/A (method on iterator) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) N/A #### Response Example None ``` ```APIDOC ## fn partition_in_place<'a, T, P>(self, predicate: P) -> usize ### Description Reorders the elements of this iterator _in-place_ according to the given predicate, such that all those that return `true` precede all those that return `false`. Returns the number of `true` elements found. ### Method N/A (method on iterator) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) N/A #### Response Example None ```