| Crates.io | fetchttp |
| lib.rs | fetchttp |
| version | 1.0.0 |
| created_at | 2025-06-05 09:07:44.347755+00 |
| updated_at | 2025-06-05 09:10:00.934833+00 |
| description | `fetch` Web API Implementation In Rust! |
| homepage | |
| repository | https://github.com/MuntasirSZN/fetchttp |
| max_upload_size | |
| id | 1701282 |
| size | 293,209 |
A WHATWG Fetch API compliant HTTP client library for Rust that provides the familiar fetch() interface you know and love from web development.
Add fetchttp to your Cargo.toml:
[dependencies]
fetchttp = "0.1.0"
tokio = { version = "1.0", features = ["full"] }
serde_json = "1.0" # For JSON support
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(())
}
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(())
}
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(())
}
use fetchttp::*;
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let controller = AbortController::new();
let signal = controller.signal().clone();
let mut init = RequestInit::new();
init.signal = Some(signal);
// Cancel the request after 1 second
tokio::spawn(async move {
sleep(Duration::from_secs(1)).await;
controller.abort();
});
match fetch("https://httpbin.org/delay/5", Some(init)).await {
Ok(response) => println!("Request completed: {}", response.status()),
Err(FetchError::Abort(_)) => println!("Request was cancelled"),
Err(e) => println!("Request failed: {}", e),
}
Ok(())
}
fetch(url, init) - Perform an HTTP requestRequest - Represents an HTTP requestRequestInit - Configuration for requestsRequestMode - CORS mode settingsRequestCredentials - Credential handlingRequestCache - Cache controlRequestRedirect - Redirect handlingResponse - Represents an HTTP responseResponseInit - Configuration for responsesResponseType - Response type informationReadableStream - Request/response body handlingHeaders - HTTP header managementFetchError - Main error typeTypeError - Type validation errorsNetworkError - Network-related errorsAbortError - Request cancellation errorsAbortController - Controls request cancellationAbortSignal - Signals request cancellationResponse and request bodies can be consumed in multiple ways:
// Text
let text = response.text().await?;
// JSON
let data: MyStruct = response.json().await?;
// Bytes
let bytes = response.array_buffer().await?;
// Blob (alias for array_buffer)
let blob = response.blob().await?;
The library provides comprehensive error handling:
match fetch("https://example.com", None).await {
Ok(response) => {
if response.ok() {
println!("Success: {}", response.status());
} else {
println!("HTTP Error: {}", response.status());
}
}
Err(FetchError::Type(e)) => {
eprintln!("Type error: {}", e);
}
Err(FetchError::Network(e)) => {
eprintln!("Network error: {}", e);
}
Err(FetchError::Abort(e)) => {
eprintln!("Request aborted: {}", e);
}
}
let mut init = RequestInit::new();
init.method = Some("PATCH".to_string());
init.body = Some(ReadableStream::from_json(&data));
let response = fetch("https://api.example.com/resource/1", Some(init)).await?;
use std::fs;
let file_content = fs::read("document.pdf")?;
let mut init = RequestInit::new();
init.method = Some("POST".to_string());
init.body = Some(ReadableStream::from_bytes(file_content.into()));
let response = fetch("https://api.example.com/upload", Some(init)).await?;
let response = fetch("https://httpbin.org/response-headers", None).await?;
for (name, value) in response.headers().entries() {
println!("{}: {}", name, value);
}
// Check specific header
if let Some(content_type) = response.headers().get("content-type")? {
println!("Content-Type: {}", content_type);
}
# Build the library
cargo build
# Run tests
cargo test
# Run benchmarks
cargo bench
# Generate documentation
cargo doc --open
The library is designed for performance with:
See benches/ for detailed performance benchmarks.
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
This project is licensed under the MIT License - see the LICENSE file for details.
| Feature | fetchttp | reqwest | hyper | ureq |
|---|---|---|---|---|
| WHATWG Fetch API | â | â | â | â |
| Async/Await | â | â | â | â |
| JSON Support | â | â | â | â |
| Connection Pooling | â | â | â | â |
| Abort Signals | â | â | â | â |
| Web API Compatibility | â | â | â | â |
Made with â¤ī¸ by MuntasirSZN