Expand description
§fetchttp
A WHATWG Fetch API compliant HTTP client library for Rust.
This library provides a familiar fetch()
API that closely follows the
WHATWG Fetch specification, making it easy
for developers familiar with web APIs to use in Rust applications.
§Features
- Specification Compliant: Implements the WHATWG Fetch API specification
- Async/Await Support: Built on Tokio for modern async Rust
- Type Safety: Leverages Rust’s type system for safe HTTP operations
- JSON Support: Built-in JSON serialization/deserialization with serde
- Flexible Bodies: Support for text, bytes, and JSON request/response bodies
- Header Management: Complete header manipulation API
- Request/Response Cloning: Efficient cloning following the specification
- Abort Signals: Request cancellation support
§Quick Start
§Simple GET Request
use fetchttp::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let response = fetch("https://api.github.com/users/octocat", None).await?;
if response.ok() {
let user: serde_json::Value = response.json().await?;
println!("User: {}", user["name"]);
}
Ok(())
}
§POST Request with JSON
use fetchttp::*;
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let data = json!({
"name": "John Doe",
"email": "john@example.com"
});
let mut init = RequestInit::new();
init.method = Some("POST".to_string());
init.body = Some(ReadableStream::from_json(&data));
let response = fetch("https://api.example.com/users", Some(init)).await?;
if response.ok() {
println!("User created successfully!");
}
Ok(())
}
§Custom Headers
use fetchttp::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut headers = Headers::new();
headers.set("Authorization", "Bearer your-token")?;
headers.set("User-Agent", "MyApp/1.0")?;
let mut init = RequestInit::new();
init.headers = Some(headers);
let response = fetch("https://api.example.com/protected", Some(init)).await?;
let text = response.text().await?;
println!("Response: {}", text);
Ok(())
}
§API Overview
The main entry point is the fetch
function, which takes a URL and optional
RequestInit
configuration. The function returns a Response
that can be
consumed in various ways:
Response::text()
- Get response as textResponse::json()
- Parse response as JSONResponse::array_buffer()
- Get response as bytesResponse::blob()
- Get response as blob (bytes)
§Error Handling
The library uses a comprehensive error system with specific error types:
TypeError
- Invalid arguments or operationsNetworkError
- Network-related failuresAbortError
- Request was aborted
All errors implement the standard Rust error traits.
Structs§
- Abort
Controller - A controller for managing abort signals.
- Abort
Error - An abort error indicating the operation was cancelled.
- Abort
Signal - A signal that can be used to cancel operations.
- Bytes
- A cheaply cloneable and sliceable chunk of contiguous memory.
- Headers
- HTTP headers container following the WHATWG Fetch specification.
- JsonMap
- Represents a JSON key/value type.
- Network
Error - A network error indicating connection or protocol failures.
- Readable
Stream - A readable stream representing request or response body data.
- Request
- An HTTP request following the WHATWG Fetch specification.
- Request
Init - Configuration for creating requests.
- Response
- An HTTP response following the WHATWG Fetch specification.
- Response
Init - Configuration for creating responses.
- Type
Error - A type error indicating invalid arguments or operations.
Enums§
- Fetch
Error - The main error type for fetch operations.
- Json
Value - Represents any valid JSON value.
- Request
Cache - Cache mode for requests.
- Request
Credentials - Credentials mode for requests.
- Request
Mode - CORS mode for requests.
- Request
Redirect - Redirect mode for requests.
- Response
Type - Response type classification.
Functions§
- fetch
- Perform an HTTP request using the Fetch API.
Type Aliases§
- Result
- Convenient Result type alias for fetch operations.