https://github.com/muntasirszn/fetchttp
`fetch` Web API Implementation In Rust!
https://github.com/muntasirszn/fetchttp
client fetch http hyper rust
Last synced: 26 days ago
JSON representation
`fetch` Web API Implementation In Rust!
- Host: GitHub
- URL: https://github.com/muntasirszn/fetchttp
- Owner: MuntasirSZN
- License: mit
- Created: 2025-06-05T07:23:35.000Z (10 months ago)
- Default Branch: main
- Last Pushed: 2025-09-16T01:01:56.000Z (7 months ago)
- Last Synced: 2025-09-16T03:12:14.694Z (7 months ago)
- Topics: client, fetch, http, hyper, rust
- Language: Rust
- Homepage: https://docs.rs/fetchttp
- Size: 272 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
- Codeowners: CODEOWNERS
- Security: SECURITY.md
Awesome Lists containing this project
README
# fetchttp
[](https://crates.io/crates/fetchttp)
[](https://docs.rs/fetchttp)
[](https://opensource.org/licenses/MIT)
[](https://github.com/MuntasirSZN/fetchttp/actions/workflows/test.yml)
A **WHATWG Fetch API** compliant HTTP client library for Rust that provides the familiar `fetch()` interface you know and love from web development.
## ⨠Features
- đ **WHATWG Fetch API Compliant** - Follows the official 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
- đ **Connection Pooling** - Automatic connection reuse for better performance
## đ Quick Start
Add `fetchttp` to your `Cargo.toml`:
```toml
[dependencies]
fetchttp = "1.0.0"
tokio = { version = "1.0", features = ["full"] }
serde_json = "1.0" # For JSON support
```
### Simple GET Request
```rust
use fetchttp::*;
#[tokio::main]
async fn main() -> Result<(), Box> {
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
```rust
use fetchttp::*;
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), Box> {
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
```rust
use fetchttp::*;
#[tokio::main]
async fn main() -> Result<(), Box> {
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(())
}
```
### Request Cancellation
```rust
use fetchttp::*;
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() -> Result<(), Box> {
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(())
}
```
## đ API Reference
### Core Functions
- **`fetch(url, init)`** - Perform an HTTP request
### Request Types
- **`Request`** - Represents an HTTP request
- **`RequestInit`** - Configuration for requests
- **`RequestMode`** - CORS mode settings
- **`RequestCredentials`** - Credential handling
- **`RequestCache`** - Cache control
- **`RequestRedirect`** - Redirect handling
### Response Types
- **`Response`** - Represents an HTTP response
- **`ResponseInit`** - Configuration for responses
- **`ResponseType`** - Response type information
### Body and Streams
- **`ReadableStream`** - Request/response body handling
- **`Headers`** - HTTP header management
### Error Handling
- **`FetchError`** - Main error type
- **`TypeError`** - Type validation errors
- **`NetworkError`** - Network-related errors
- **`AbortError`** - Request cancellation errors
### Abort Support
- **`AbortController`** - Controls request cancellation
- **`AbortSignal`** - Signals request cancellation
## đ Body Consumption
Response and request bodies can be consumed in multiple ways:
```rust
// 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?;
```
## đĄī¸ Error Handling
The library provides comprehensive error handling:
```rust
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);
}
}
```
## đ§ Advanced Usage
### Custom HTTP Methods
```rust
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?;
```
### File Upload
```rust
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?;
```
### Response Headers
```rust
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);
}
```
## đī¸ Building and Testing
```bash
# Build the library
cargo build
# Run tests
cargo test
# Run benchmarks
cargo bench
# Generate documentation
cargo doc --open
```
## đ Performance
The library is designed for performance with:
- Connection pooling via hyper
- Efficient body streaming
- Zero-copy operations where possible
- Minimal allocations
See `benches/` for detailed performance benchmarks.
## đ¤ Contributing
Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
## đ License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## đ Comparison with Other Libraries
| Feature | fetchttp | reqwest | hyper | ureq |
|---------|----------|---------|-------|------|
| WHATWG Fetch API | â
| â | â | â |
| Async/Await | â
| â
| â
| â |
| JSON Support | â
| â
| â | â
|
| Connection Pooling | â
| â
| â
| â |
| Abort Signals | â
| â
| â | â |
| Web API Compatibility | â
| â | â | â |
## đ Links
- [Documentation](https://docs.rs/fetchttp)
- [Repository](https://github.com/MuntasirSZN/fetchttp)
- [Issues](https://github.com/MuntasirSZN/fetchttp/issues)
- [WHATWG Fetch Specification](https://fetch.spec.whatwg.org/)
---
Made with â¤ī¸ by [MuntasirSZN](https://github.com/MuntasirSZN)